I have a ppm image file and i want to convert it to a jpg but the problem is that the ppm is p3 and i only know how to convert p6 to jpg and don't understand how the conversion from p3 to p6 works or if there is a direct conversion from p3 to jpg. I know there is some way using ImageMagick but i don't get how this works. So if anyone has some code for p3 to p6 or p3 to jpg i would be very thankful if they could share it.
CodePudding user response:
This should be able to read an ASCII P3 NetPBM fairly well - unless you have numbers in the comments - then all bets are off:
#!/usr/bin/env python3
import re
import numpy as np
from PIL import Image
from pathlib import Path
# Open image file, slurp the lot
contents = Path('image.ppm').read_text()
# Make a list of anything that looks like numbers using a regex...
# ... taking first as height, second as width and remainder as pixels
Pidentifier, h, w, *pixels = re.findall(r'[0-9] ', contents)
h = int(h)
w = int(w)
# Now make pixels into Numpy array of uint8 and reshape to correct height, width and depth
na = np.array(pixels[w*h*-3:], dtype=np.uint8).reshape((h,w,3))
# Now make the Numpy array into a PIL Image and save
Image.fromarray(na).save("result.jpg")
CodePudding user response:
You can use ImageMagick command convert, see this answer
Also i found realization on C language
Also as you need Python realization uses wand library