2015-11-17 70 views
1

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

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

现在的数据格式是什么?你是从一个PNG文件开始说的,还是你已经有一个640 x 480 x 3的数组? – kwinkunks

+0

我有jpeg格式的图像。 – Leo

回答

1

如果这是你想要的精确输出,那么我认为这样做的工作。你可以使用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)通常含有每像素的四个值,因为他们可以有一个“阿尔法”(不透明度)的信道。

+1

这正是我想要的!谢谢Kwinkunks先生。 – Leo

0

你可以尝试使用SciPy的和numpy的,并且这样做(未经测试)

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

它不起作用:TypeError:数组dtype('uint8')和格式说明符('%.18e%.18e%.18e ...)之间不匹配 – Leo

+0

尝试numpy.savetxt('out.txt',data, fmt =“%s”) – andyhasit