python imagedraw_Python PIL编辑像素与ImageDraw.point

在使用Python PIL库编辑图像时,通过ImageDraw.point方法可以有效地绘制像素。然而,直接访问像素进行编辑可能会更快。问题在于尝试将颜色(一个字符串)赋值给像素时,需要传递一个长度为2的序列。解决方法是使用像素的元组索引,如pixels[x, y] = (r, g, b, a)。此外,直接修改像素确实比使用ImageDraw更快。" 49955859,2116373,递归原理详解:打印数字,"['递归', '数据结构', '算法']
摘要由CSDN通过智能技术生成

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)

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.

I tried using this:

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"

This gives me an error:

Traceback (most recent call last):

File "my_path\my_file.py", line 100, in

main()

File "my_path\my_file.py", line 83, in main

pixels[x][y] = color

TypeError: argument must be sequence of length 2

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.

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.

Thanks in advance!

解决方案

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")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值