Converting .pgm to .png in Python

Solution 1:

you can try using os and pillow

import os
from PIL import Image

for file in os.listdir():
    filename, extension  = os.path.splitext(file)
    if extension == ".pgm":
        new_file = "{}.png".format(filename)
        with Image.open(file) as im:
            im.save(new_file)

Solution 2:

The exclamation mark (!) means it is an external command, and convert is part of the ImageMagick package.

So you would need to install ImageMagick for it to work. Note that if you install v7 or newer, the command would become:

!magick INPUT.PGM OUTPUT.PNG

However, if you want to convert all PGM files in the current directory to PNG files, you don't even need a loop, you can do them all in one go with:

magick mogrify -format png *.pgm

Yet more caveats... there is no real need from a Python point of view to convert PGM files to PNG, since OpenCV, PIL/Pillow, wand and scikit-image can all read PGM files anyway. So can GIMP, feh, eog, Photoshop.