如何使用每个像素的RGB值构建图像 [英] How to build an image with every pixel's RGB value
问题描述
我正在使用Python和PIL库,我为图像的每个像素及其位置提供RGB信息。有什么方法可以根据这些信息构建图像吗?
I am using Python and the PIL library and I have the RGB information for every pixel of an image along with their location. Is there any way that I can build an image from this information?
推荐答案
当然可以。如果您的源数据稀疏(即您没有每个像素位置的值),您可能需要执行以下操作:
Certainly. If your source data is sparse (ie. you don't have a value for every pixel location) you probably want to do the following:
- 创建所需尺寸的空图像
- 确保您的颜色数据按照栅格顺序存储(即按y然后x排序)
- 迭代通过数据并存储每个位置的像素值
因此,假设您有一个元组数组,例如(x,y,(r,g,b))
,你可以这样做:
So, assuming you have an array of tuples such as (x, y, (r,g,b))
, you can do something like:
from pil import Image
WIDTH=640
HEIGHT=480
img = Image.new(WIDTH, HEIGHT, 'RGB')
# Define this based on your data
my_raster_sort(my_image_data)
img_data = img.load()
for x, y, color in my_image_data:
img_data[x,y] = color
如果您的源图像数据已完成(即您有每个位置的颜色值)然后转换你可能会更快将数据放入使用所需内存布局格式化的缓冲区中,然后使用 Image.frombuffer
。
If your source image data is complete (ie. you have a colour value for every position) then it would probably be faster to transform your data into a buffer formatted with the desired memory layout, and then create an image in one step using Image.frombuffer
.
这篇关于如何使用每个像素的RGB值构建图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!