如何从 .t​​xt 文件转换 RGB 值以在 Python 中显示图像

How to convert RGB values from .txt file to display an image in Python

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

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

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

要阅读 txt 文件,您需要此代码

file= open("filename.txt")
lines = file.readlines()

然后你可以用函数

得到每一行的数字
lines[0].split(",")

终于可以用pillow来做image with the data

    from PIL import Image
     
    img = Image.new('RGB', (60, 30), color = 'red')
    img.save('pil_red.png')

需要确定两个步骤来解决这个问题:

1.解析文件 以获取像素和图像的宽度和高度。在这一步,你需要知道信息是如何被 存储在文件中。

2。使用OpenCV显示图像。下面是一个将矩阵显示为图像的基本示例:

import numpy as np
import cv2
# image of 100 x 100 pixels , with 3 channels 
height=100 
width=100
channels=3 
color_bg=(0,0,0) 
imgdim = (height, width, channels ) 
blank_image = np.full(imgdim, color_bg, np.uint8)
#Simple way to change the pixel(x=1,y=2) color to the (B=255,G=0,R=0) tuple color 
blank_image[1,2]= (255,0,0) 

cv2.imshow("blank", blank_image)
cv2.waitKey(0)

请阅读 Basics operations with opencv-python 的文档以了解有关 numpy 的概念和性能建议。

这很简单:

#!/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文件(兼容PhotoshopGIMPOpenCV, PIL/PillowImageMagick), without using PIL/PillowOpenCV 或任何额外的库,并使其大小约为原始文件的 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,如果你写一个NetPBM可以被[=35=读取的文件,你可以直接在Terminal的命令行中完成]Photoshop, GIMP, PIL/Pillow

awk 'NR==1{[=13=]="P3\n"  " "  "\n255"} {gsub(/,/,"\n")} 1' image.txt > result.ppm

该脚本基本上是 "massages" 你的第一行,所以它来自:

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

对此:

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