我正在使用PIL库。
我正在尝试使图像看起来更红,这就是我所得到的。
from PIL import Image
image = Image.open('balloon.jpg')
pixels = list(image.getdata())
for pixel in pixels:
pixel[0] = pixel[0] + 20
image.putdata(pixels)
image.save('new.bmp')
但是我得到这个错误: TypeError: 'tuple' object does not support item assignment
PIL像素是元组,并且元组是不可变的。您需要构造一个新的元组。因此,代替for循环,请执行以下操作:
pixels = [(pixel[0] + 20, pixel[1], pixel[2]) for pixel in pixels]
image.putdata(pixels)
同样,如果像素已经太红,则加20将使该值溢出。您可能想要类似min(pixel[0] + 20, 255)
或int(255 * (pixel[0] / 255.) ** 0.9)
代替的东西pixel[0] + 20
。
并且,为了能够处理许多不同格式image = image.convert("RGB")
的图像,请在打开图像后再进行操作。的转换方法将确保像素是始终(R,G,B)的元组。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句