Search code examples
pythonimagemagickfile-conversionwandppm

Convert from PPM P3 to PPM P6 and back using Python Wand


I was originally trying to use Python Pillow to convert a ppm p3 image to jpg, png, etc, when I realized that Pillow only allows ppm p6.

I've tried a whole bunch of ways to solve this problem, but I haven't found a solution. I discovered that using ImageMagick, you could convert an image to ppm p3 and back to p6, so I thought that if I could find a way to use ImageMagick in my python file, I could convert p3 images to p6, allowing them to be used by python pillow.

So I installed ImageMagick and python Wand to try and achieve this. However, I don't know how to do this with Wand or if Wand even supports this. I've done a lot of research on the web, and I've looked through the documentation, but I can't seem to find an answer.

Another alternative that I took to solve my issue is to try and manually convert between ppm p3 and p6 by writing to files. In other words, taking the ASCII data and turning it into binary data and vice versa. This possible solution also stumped me because of how difficult it is to read a binary file and somehow decipher that information into acceptable p3 ASCII.

I know that I can just manually convert between p3 and other formats using ImageMagick directly, but I want to do it using python because I'm trying to write a python application that can do basic image manipulation, and I want to write it so that users can upload and use p3 images. I also wrote an algorithm for a class project that only specifically works with ppm p3 images, and it'd be nice if there was a way to convert from jpg to ppm p3 quickly to use that algorithm and then quickly convert back.

If there's a way (regardless of whether it uses Wand or not) to convert between ppm p3 and ppm p6 using python, please let me know!


Solution

  • You can control whether you get P3 or P6 by setting compression as follows:

    from wand.image import Image                                                                                          
    
    # By default, you will get P6 (compressed binary)
    with Image(width=100, height=100, pseudo='plasma:') as img: 
        img.save(filename='P6.ppm') 
    
    # If you specify "compression='no'", you will get P3 (uncompressed ASCII)
    with Image(width=100, height=100, pseudo='plasma:') as img: 
        img.compression = 'no' 
        img.save(filename='P3.ppm')
    

    Keywords: Python, wand, compression, PPM, NetPBM, P3, P6 rawbits.