这很简单:
#!/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.txt').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
h, w, *pixels = re.findall(r'[0-9]+', contents)
# Now make pixels into Numpy array of uint8 and reshape to correct height, width and depth
na = np.array(pixels, dtype=np.uint8).reshape((int(h),int(w),3))
# Now make the Numpy array into a PIL Image and save
Image.fromarray(na).save("result.png")
如果您想使用 OpenCV 而不是 PIL/Pillow 编写输出图像,请将上面的最后一行更改为以下内容,以便进行 RGB->BGR 重新排序并改用cv2.imwrite():
# Save with OpenCV instead
cv2.imwrite('result.png', na[...,::-1])
如果你想写一个 PPM 文件(兼容 Photoshop、GIMP、OpenCV、PIL/Pillow 和 ImageMagick),没有使用 PIL/Pillow 或 OpenCV 或任何额外的库,并且大约 1 /4 原始文件的大小,您可以通过将上面的最后一行替换为以下内容非常简单地以二进制形式编写它:
# Save "na" as binary PPM image
with open('result.ppm','wb') as f:
f.write(f'P6\n{w} {h}\n255\n'.encode())
f.write(na.tobytes())
其实你不需要任何Python,直接在Terminal的命令行下写一个Photoshop可以读取的NetPBM文件就可以了, GIMP、PIL/枕头
awk 'NR==1{$0="P3\n" $2 " " $1 "\n255"} {gsub(/,/,"\n")} 1' image.txt > result.ppm
那个脚本基本上是“massages”你的第一行,所以它是从这个开始的:
418 870
... rest of your data ...
到这里:
P3
870 418
255
... rest of your data ...