有没有一种方法可以在python中将P3 ppm转换为jpg



我有一个ppm图像文件,我想把它转换成jpg,但问题是ppm是p3,我只知道如何把p6转换成jpg,不知道从p3到p6的转换是如何工作的,也不知道是否有从p3直接转换成jpg。我知道有一些方法可以使用ImageMagick,但我不知道它是如何工作的。因此,如果有人有一些p3到p6或p3到jpg的代码,如果他们能分享,我将不胜感激

这应该能够很好地读取ASCII P3 NetPBM-除非注释中有数字-否则所有赌注都会被取消:

#!/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")

您可以使用ImageMagick命令转换,请参阅以下答案

我还发现了在C语言上的实现

也可以根据需要Python实现使用wand

最新更新