Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'tuple' object does not support item assignment

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

like image 664
dgamma3 Avatar asked Oct 07 '11 12:10

dgamma3


People also ask

Does tuple object support item assignment?

Tuples are immutable objects. “Immutable” means you cannot change the values inside a tuple. You can only remove them.

Which object does not support item assignment in Python?

The Python "TypeError: 'type' object does not support item assignment" occurs when we assign a data type to a variable and use square brackets to change an index or a key. To solve the error, set the variable to a mutable container object, e.g. my_list = [] . Here are 2 examples of how the error occurs.

How do you assign a value to a tuple?

Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called. But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple.

Does set support item assignment in Python?

How to Solve Python TypeError: 'set' object does not support item assignment. In Python, you cannot access the elements of sets using indexing. If you try to change a set in place using the indexing operator [], you will raise the TypeError: 'set' object does not support item assignment.


1 Answers

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.

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.

like image 144
Petr Viktorin Avatar answered Sep 18 '22 22:09

Petr Viktorin