Problem:
I want to import all ".pgm" files from several folders and store them as ".png".
For this I use the following lines of code:
from glob import glob files=glob('yaleB*/*.pgm') print 'number of files is',len(files) count=0 for f in files: new_f=f[:-3]+'png' !convert $f $new_f count += 1 if count % 100==0: print count,f,new_f Unfortunately, I always get this error: "command not found: convert"
Is there a simple fix for this?
My assumption is, that this is an "old" command (Jupyter Notebook where I took this code from is from 2014..)
2 Answers
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) 1The 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.
1