在Python中反转RGB图像的像素

时间:2017-11-19 22:05:01

标签: python image-processing python-imaging-library pillow attributeerror

我正在尝试反转RGB图像的像素。也就是说,简单地从255中减去每个像素的每个通道(红色,绿色,蓝色)的强度值。

到目前为止,我有以下内容:

from PIL import Image

im = Image.open('xyz.png')
rgb_im = im.convert('RGB')
width, height = im.size

output_im = Image.new('RGB', (width,height))

for w in range(width):
    for h in range(height):
        r,g,b = rgb_im.getpixel((w,h))
        output_r = 255 - r
        output_g = 255 - g
        output_b = 255 - b
        output_im[w,h] = (output_r, output_g, output_b)

当我运行上面的脚本时,我收到以下错误:

Traceback (most recent call last):
  File "image_inverse.py", line 31, in <module>
    output_im[w,h] = (output_r, output_g, output_b)
  File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 528, in __getattr__
    raise AttributeError(name)
AttributeError: __setitem__

我该如何解决这个问题?

感谢。

2 个答案:

答案 0 :(得分:0)

我猜你可以使用矢量化操作,如果图像是一个numpy数组

from PIL import Image
im = Image.open('xyz.png')
im = 255 - im

答案 1 :(得分:0)

您可以使用img.putpixel为每个像素分配r,g,b值 -

from PIL import Image

im = Image.open('xyz.png')
rgb_im = im.convert('RGB')
width, height = im.size

output_im = Image.new('RGB', (width,height))

for w in range(width):
    for h in range(height):
        r,g,b = rgb_im.getpixel((w,h))
        output_r = 255 - r
        output_g = 255 - g
        output_b = 255 - b
        alpha = 1
        output_im.putpixel((w, h), (output_r, output_g, output_b, alpha))