我正在开发一个图像生成程序,我在尝试直接编辑图像像素时遇到了问题。
I am working on an image-generation program, and I have an issue trying to directly edit the pixels of an image.
我的原始方法有效,很简单:
My original method, which works, was simply:
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像素×10000像素),所以即使每个像素的时间略有减少也会大幅减少。
This works fine, but I thought directly editing pixels might be slightly faster. I plan on using "very" high resolutions (maybe 10000px by 10000px), so even a slight decrease in time per pixel will be a large decrease overall.
我试过使用这个:
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实际像素如何[x] [y] 工作?我似乎在这里缺少一个基本概念(我从未在此之前直接编辑像素),或者至少只是不了解所需的参数。我甚至尝试了 pixels [x] [y] =(0,0,0),但这引发了同样的错误。
How does the actual pixels[x][y] work? I seem to be missing a fundamental concept here (I've never worked with directly editing pixels prior to this), or at least just not understanding what arguments are required. I even tried pixels[x][y] = (0, 0, 0), but that raised the same error.
此外,是否有更快的方式来编辑像素?我听说使用像素[x] [y] = some_color 比绘制到图像要快,但我对任何其他更快的方法都开放。
In addition, is there a faster way to edit the pixels? I've heard that using the pixels[x][y] = some_color is faster than drawing to the image, but I'm open to any other faster method.
提前致谢!
推荐答案你需要传递一个元组索引作为 pixels [(x,y)] 或只是 pixels [x,y] ,例如:
You need to pass a tuple index as pixels[(x, y)] or simply pixels[x, y], for example:
#-*- 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")更多推荐
Python PIL编辑像素与ImageDraw.point
发布评论