问题
I tried to save an RGB matrix in text format but without success. The resolution of the image is 640 x 480. I'm looking for matrix with 640 columns and 480 rows and for every element the corresponding RGB value. For example:
(230, 200, 20) (130, 11, 13) ... # and the others 658 columns
(200, 230, 20) (11, 130, 13) ...
... # and the others 478 rows
回答1:
If that's the exact output you want, then I think this does the job. You can use str.format() to get whatever you need.
# 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)
Note that some image types (e.g. PNG) commonly contain four values per pixel, because they can have an 'alpha' (opacity) channel.
回答2:
You could try using scipy and numpy, and do something like this (untested)
from scipy import misc
import numpy
data = misc.imread('img1.png')
numpy.savetxt('out.txt', data)
来源:https://stackoverflow.com/questions/33757706/saving-rgb-matrix-as-text