from PIL import Imageimage = 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
PIL pixels are tuples, and tuples are immutable. You need to construct a new tuple. So, instead of the for loop, do:
pixels = <(pixel<0> + 20, pixel<1>, pixel<2>) for pixel in pixels>image.putdata(pixels)Also, if the pixel is already too red, adding 20 will overflow the value. You probably want something like min(pixel<0> + 20, 255) or int(255 * (pixel<0> / 255.) ** 0.9) instead of pixel<0> + 20.
You are watching: Tuple object does not support item assignment
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.
The second line should have been pixels<0>, with an S. You probably have a tuple named pixel, and tuples are immutable. Construct new pixels instead:
image = Image.open(“balloon.jpg”)pixels = <(pix<0> + 20,) + pix<1:> for pix in image.getdata()>image.putdate(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)
A tuple is immutable and thus you get the error you posted.
pixel = (pixel<0> + 20, pixel<1>, pixel<2>)
You have misspelt the second pixels as pixel. The following works:
pixels = <1,2,3>pixels<0> = 5It 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.
Thanks for contributing an answer to Stack Overflow!
Please be sure to answer the question. Provide details and share your research!
But avoid …
Asking for help, clarification, or responding to other answers.Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Post Your Answer Discard
Not the answer you're looking for? Browse other questions tagged python python-imaging-library or ask your own question.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev2021.9.24.40305