How to save png copies of ppm images in Python

Question:

I have a folder full of ppm images and I want to save png copies of them.

How do I do that?

I’ve tried executing the following code but nothing happens.

import cv2
import numpy as np
import glob
import sys
import os.path

from os.path import isfile,join 
from PIL import Image

target_path = '/Users/lfw/test'
trg = os.listdir(target_path)
count = 0
 for i in trg:
  fullpath = os.path.join(target_path ,i)
  if os.path.isfile(fullpath): 
  im = Image.open(fullpath)
  im.save(str(count) + 'output.png')
  count = count + 1
Asked By: AZDDKKS

||

Answers:

Let’s say you have on your desktop a root folder called test containing my_script.py and a subfolder called input where all the ppm files are stored.

You can use the following code to save a png copy of every ppm image.

my_script.py

import os 
import cv2 
from glob import glob 

cwd = os.getcwd()
input_dir = os.path.join(cwd, "input\*.ppm")    
ppms = glob(input_dir)   

counter = 1 

for ppm in ppms: 
    cv2.imwrite(str(counter)+".png", cv2.imread(ppm))
    counter += 1 

NOTE: I’ve written the code in a particular way that let’s you mantain the old ppm files and creates brand new png copies of the original images. If you want to actually replace the ppms with pngs I can edit the answer making it doing the desired job.

Answered By: Employee

There’s no real need to write any Python, you can just use ImageMagick in the Terminal – as installed on most Linux distros and available for macOS and Windows:

magick mogrify -format png *ppm

If you want the output files in a different folder, use:

mkdir -p newFolder
magick mogrify -format png -path newFolder *ppm

If you have many files to do, you can do them in parallel with GNU Parallel like this:

parallel convert {} {.}.png ::: *ppm

If you use v6 or older of ImageMagick, that becomes:

mogrify -format png *ppm
Answered By: Mark Setchell
from PIL import Image 
import glob, os
directory = r'D:DATASET...'
for infile in glob.glob(os.path.join(directory, "*.ppm")):
    file, ext = os.path.splitext(infile)
    im = Image.open(infile)
    im.save(file + ".png")
Answered By: Erfan Khoshnevisan
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.