0

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.

Ben0981
  • 39
  • 6
  • Does this answer your question? [Importing PPM images with python and PIL module](https://stackoverflow.com/questions/4101576/importing-ppm-images-with-python-and-pil-module) – mkrieger1 Apr 10 '22 at 14:17
  • You should be able to adapt this very easily to read an ASCII P3 NetPBM file https://stackoverflow.com/a/66364502/2836621 – Mark Setchell Apr 10 '22 at 14:25

2 Answers2

1

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")
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
  • 1
    It _would_ be nice if PIL supported ASCII PPMs, but apparently it doesn't... https://github.com/python-pillow/Pillow/blob/main/src/PIL/PpmImagePlugin.py#L27 – AKX Apr 10 '22 at 18:23
  • 1
    @AKX Agreed - but I guess they are pretty busy folk and only volunteering at that... – Mark Setchell Apr 10 '22 at 18:26
  • Thanks for the code, it generates a jpg in the right size without showing any errors but the resulting file is completely black so somewhere something went wrong. Any help would be appreciated. – Ben0981 Apr 10 '22 at 20:15
  • If you can share your image, via Dropbox or Google Drive along with anything you know about - like dimensions or range - I’ll take a look. – Mark Setchell Apr 10 '22 at 21:39
0

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

h1w
  • 78
  • 5