我正在开发图像生成程序,但在尝试直接编辑图像像素时遇到问题。
我原来的有效方法很简单:
image = Image.new('RGBA', (width, height), background)
drawing_image = ImageDraw.Draw(image)
# in some loop that determines what to draw and at what color
drawing_image.point((x, y), color)
这很好用,但我认为直接编辑像素可能会稍微快一些。我计划使用“非常”高分辨率(可能是 10000 像素 x 10000 像素),因此即使每个像素的时间略有减少,总体上也会有很大的减少。
我试过用这个:
image = Image.new('RGBA', (width, height), background)
pixels = image.load()
# in some loop that determines what to draw and at what color
pixels[x][y] = color # note: color is a hex-formatted string, i.e "#00FF00"
这给了我一个错误:
Traceback (most recent call last):
File "my_path\my_file.py", line 100, in <module>
main()
File "my_path\my_file.py", line 83, in main
pixels[x][y] = color
TypeError: argument must be sequence of length 2
实际 pixels[x][y] 是如何工作的?我似乎在这里缺少一个基本概念(在此之前我从未使用过直接编辑像素),或者至少只是不理解需要什么参数。我什至尝试过 pixels[x][y] = (0, 0, 0),但出现了同样的错误。
另外,有没有更快的编辑像素的方法?我听说使用 pixels[x][y] = some_color 比绘制图像更快,但我愿意接受任何其他更快的方法。
提前致谢!
请您参考如下方法:
您需要将元组索引作为 pixels[(x, y)] 或简单地传递给 pixels[x, y],例如:
#-*- coding: utf-8 -*-
#!python
from PIL import Image
width = 4
height = 4
background = (0, 0, 0, 255)
image = Image.new("RGBA", (width, height), background)
pixels = image.load()
pixels[0, 0] = (255, 0, 0, 255)
pixels[0, 3] = (0, 255, 0, 255)
pixels[3, 3] = (0, 0, 255, 255)
pixels[3, 0] = (255, 255, 255, 255)
image.save("image.png")
