2015-11-17 68 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