将像素值数组保存到文本文件中

3

我有一个灰度图像的像素值数组。我想将这些值导出到文本文件或CSV中。我一直在尝试使用各种函数来实现这一点,包括:xlsxwrite、write、CSV等,但是我迄今为止一直没有成功。以下是我的工作内容:

from PIL import Image
import numpy as np 
import sys

# load the original image
img_file = Image.open("seismic.png") 
img_file.show() 

# get original image parameters...
width, height = img_file.size
format = img_file.format
mode = img_file.mode

# Make image Greyscale
img_grey = img_file.convert('L') 
img_grey.save('result.png')
img_grey.show()

# Save Greyscale values
value = img_grey.load()

基本上,我想保存“value”以便在其他地方使用。

这个方面有什么不成功的地方吗? - Peter Wood
这不会产生错误,但我对如何处理所生成的数据感到不确定。 - Alexander Peace
你想将你的图像转换成类似于PGM文件格式的东西吗? - valepert
不,我只想将像素的值保存到文件中。 - Alexander Peace
1个回答

2

不必使用.load()方法,您可以使用以下代码(其中“x”为灰度图像):

value = np.asarray(x.getdata(),dtype=np.float64).reshape((x.size[1],x.size[0]))

这是来自:将RGB图像转换为灰度并在Python中操作像素数据 一旦完成此操作,使用numpy.savetxt将数组保存到文件非常简单。
numpy.savetxt("img_pixels.csv", value, delimiter=',')

注意:x.load()返回的是一个Pixel Access类的实例,不能使用你提到的csv writer进行操作。可以在这里找到用于提取和操作Pixel Access类中单个像素的方法:http://pillow.readthedocs.io/en/3.1.x/reference/PixelAccess.html

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接