Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python ';元组';对象不支持项分配_Python_Python Imaging Library - Fatal编程技术网

Python ';元组';对象不支持项分配

Python ';元组';对象不支持项分配,python,python-imaging-library,Python,Python Imaging Library,我正在使用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:“tupl

我正在使用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”对象不支持项分配

第二行应该是
像素[0]
,带有S。您可能有一个名为
像素的元组,元组是不可变的。而是构造新像素:

image = Image.open('balloon.jpg')

pixels = [(pix[0] + 20,) + pix[1:] for pix in image.getdata()]

image.putdate(pixels)

您将第二个
像素
拼错为
像素
。以下工作:

pixels = [1,2,3]
pixels[0] = 5

似乎由于打字错误,您试图意外地修改一些名为
pixel
的元组,而在Python中元组是不可变的。因此出现了令人困惑的错误消息。

元组是不可变的,因此您会得到您发布的错误

>>> pixels = [1, 2, 3]
>>> pixels[0] = 5
>>> pixels = (1, 2, 3)
>>> pixels[0] = 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

元组,在python中不能更改其值。如果您想更改包含的值,我建议使用列表:


[1,2,3]
不是
(1,2,3)

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

pixels = [(pixel[0] + 20, pixel[1], pixel[2]) for pixel in pixels]
image.putdata(pixels)
此外,如果像素已经太红,则添加20将使值溢出。您可能需要
min(像素[0]+20255)
int(255*(像素[0]/255.)**0.9)
而不是
pixel[0]+20


而且,为了能够处理多种不同格式的图像,请在打开图像后执行
image=image.convert(“RGB”)
。该方法将确保像素始终是(r、g、b)元组。

您可能希望对像素进行下一次变换:

pixels = map(list, image.getdata())

我相信PIL可以简单地在你的图像上加上一层红色。如果图像中有任何红色像素,此方法将失败!我认为你的解决方案更接近我的问题。然而,即使我这样做:像素=(0,0,0)。我得到的图片与导入的图片完全相同。您可能指的是min(像素[0]+20255)
pixels = map(list, image.getdata())