如何将.txt文件中的RGB值转换为在Python中显示图像 [英] How to convert RGB values from .txt file to display an image in Python

查看:35
本文介绍了如何将.txt文件中的RGB值转换为在Python中显示图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含RGB值的.txt文件,当我打开并读取这些文件时,像素值是str格式的。如何将这些值转换为在Python中显示图像。image

这是我尝试读取值时的。它们都是字符串格式。

编辑:您可以在此处找到该文件的链接https://drive.google.com/file/d/1mAxlcMj_SVeK0axJhbPJqO4k_egJoYli/view?usp=sharing

推荐答案

这样做非常简单:

#!/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文件(与PhotoshopGIMPOpenCVPIL/PillowImageMagick兼容)、而不是使用PIL/PillowOpenCV或任何额外的库,并且使其大小约为原始文件的1/4,则可以非常简单地以二进制形式编写它,只需将上面最后一行替换为:

# Save "na" as binary PPM image
with open('result.ppm','wb') as f:
   f.write(f'P6
{w} {h}
255
'.encode())
   f.write(na.tobytes())

事实上,您不需要任何Python,如果您编写了一个NetPBM文件,PhotoshopGIMPPIL/Pillow

,您可以在终端的命令行直接完成
awk 'NR==1{$0="P3
" $2 " " $1 "
255"} {gsub(/,/,"
")} 1' image.txt > result.ppm

该脚本基本上是消息您第一行,因此它是这样的:

418 870
... rest of your data ...

至此:

P3
870 418
255
... rest of your data ...

这篇关于如何将.txt文件中的RGB值转换为在Python中显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆