对象不支持项目分配

对象不支持项目分配

本文介绍了'tuple'对象不支持项目分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PIL库.

我正在尝试使图像看起来更红,这就是我所得到的.

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

但是我收到此错误:TypeError: 'tuple' object does not support item assignment

However I get this error: TypeError: 'tuple' object does not support item assignment

推荐答案

PIL像素是元组,而元组是不可变的.您需要构造一个新的元组.因此,请执行以下操作,而不是for循环:

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)

此外,如果像素已经太红,则加20将使该值溢出.您可能希望使用min(pixel[0] + 20, 255)int(255 * (pixel[0] / 255.) ** 0.9)之类的东西,而不是pixel[0] + 20.

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.

并且,为了能够处理许多不同格式的图像,请在打开图像后执行image = image.convert("RGB"). convert 方法将确保像素始终( r,g,b)元组.

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.

这篇关于'tuple'对象不支持项目分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 15:50