Python PIL编辑像素与ImageDraw.poin

2024-04-25 01:28:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个图像生成程序,我在尝试直接编辑图像的像素时遇到了问题。

我最初的方法是,简单地说:

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)

这很好,但我认为直接编辑像素可能会快一点。我计划使用“非常”高的分辨率(可能是10000px乘以10000px),所以即使每像素的时间稍微减少,总体上也会大大减少。

我试着用这个:

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比绘制图像快,但是我对任何其他更快的方法持开放态度。

提前谢谢!


Tags: 方法in图像image编辑newmysome
1条回答
网友
1楼 · 发布于 2024-04-25 01:28:44

您需要将元组索引作为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")

相关问题 更多 >