python 创建灰度图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2111150/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
create a grayscale image
提问by Vince
I am reading binary data from one file that specifies intensity values across x and y coordinates (not a open-source image format) and want to convert it to a PNG image (or other widely supported format). I have the data loaded into an array (using the array module) where each element is a integer from 0 to 255. To save this to a PNG I can create a 3 item tuple of each element (x) like so:
我正在从一个文件中读取二进制数据,该文件指定跨 x 和 y 坐标的强度值(不是开源图像格式),并希望将其转换为 PNG 图像(或其他广泛支持的格式)。我将数据加载到一个数组中(使用数组模块),其中每个元素都是 0 到 255 之间的整数。要将其保存到 PNG,我可以创建每个元素 (x) 的 3 项元组,如下所示:
t = (x, x, x)
add apply it across the array using the map(), then save the image using putdata(). However, the conversion to the array of tuples takes a long time (few minutes). Is there a way to specify the rgb value using only one integer (not a tuple). I guessing an alternative would be to use NumPy, but I don't know where to start, so any help in this regard would also be appreciated.
add 使用 map() 将其应用于整个数组,然后使用 putdata() 保存图像。但是,转换为元组数组需要很长时间(几分钟)。有没有办法只使用一个整数(不是元组)来指定 rgb 值。我想另一种选择是使用 NumPy,但我不知道从哪里开始,所以在这方面的任何帮助也将不胜感激。
Thanks in advance for the help.
在此先感谢您的帮助。
回答by Nadia Alramli
When you create the new image, give it the mode L:
创建新图像时,将其设置为模式 L:
im = Image.new('L', size)
im.putdata([x1, x2, x3, ...])
Where data is a list of values not tuples.
其中 data 是值列表而不是元组。
回答by tkerwin
There are several ways to do this, but if you already have the data in memory, look into using Image.frombuffer
or Image.fromstring
using the 'L'
mode (for 8-bit greyscale data).
有几种方法可以做到这一点,但如果您已经在内存中拥有数据,请考虑使用Image.frombuffer
或Image.fromstring
使用'L'
模式(对于 8 位灰度数据)。
回答by David Sowsy
Would im.putpixel(xy, colour) be what you are looking for?
im.putpixel(xy, colour) 会是你要找的吗?