将 RGB 矩阵保存为文本

Saving RGB matrix as text

我试图以文本格式保存 RGB 矩阵,但没有成功。图像的分辨率为 640 x 480。我正在寻找具有 640 列和 480 行的矩阵,并且每个元素都有对应的 RGB 值。例如:

(230, 200, 20) (130, 11, 13) ... # and the others 658 columns
(200, 230, 20) (11, 130, 13) ... 
... # and the others 478 rows

您可以尝试使用 scipy 和 numpy,并执行类似的操作(未经测试)

from scipy import misc
import numpy
data = misc.imread('img1.png')
numpy.savetxt('out.txt', data)

如果这就是您想要的确切输出,那么我认为这可以完成工作。您可以使用 str.format() 来获得您需要的任何东西。

# Read the image file.
from scipy import misc
data = misc.imread('image.jpg')

# Make a string with the format you want.
text = ''
for row in data:
    for e in row:
        text += '({}, {}, {}) '.format(e[0], e[1], e[2])
    text += '\n'

# Write the string to a file.
with open('image.txt', 'w') as f:
    f.write(text)

请注意,某些图像类型(例如 PNG)通常每个像素包含四个值,因为它们可以有一个 'alpha'(不透明度)通道。