I am using the PIL library.
I am trying to make an image look red-er, this is what i've got.
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')
However I get this error: TypeError: 'tuple' object does not support item assignment
The second line should have been
pixels[0]
, with an S. You probably have a tuple namedpixel
, and tuples are immutable. Construct new pixels instead:You have misspelt the second
pixels
aspixel
. The following works:It appears that due to the typo you were trying to accidentally modify some tuple called
pixel
, and in Python tuples are immutable. Hence the confusing error message.You probably want the next transformation for you pixels:
Tuples, in python can't have their values changed. If you'd like to change the contained values though I suggest using a list:
[1,2,3]
not(1,2,3)
PIL pixels are tuples, and tuples are immutable. You need to construct a new tuple. So, instead of the for loop, do:
Also, if the pixel is already too red, adding 20 will overflow the value. You probably want something like
min(pixel[0] + 20, 255)
orint(255 * (pixel[0] / 255.) ** 0.9)
instead ofpixel[0] + 20
.And, to be able to handle images in lots of different formats, do
image = image.convert("RGB")
after opening the image. The convert method will ensure that the pixels are always (r, g, b) tuples.A tuple is immutable and thus you get the error you posted.
In your specific case, as correctly pointed out in other answers, you should write: