【问题标题】:Inverting pixels of an RGB image in Python在 Python 中反转 RGB 图像的像素
【发布时间】:2018-05-03 02:37:46
【问题描述】:

我正在尝试反转 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__

我该如何解决这个问题?

谢谢。

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的回复。是否有适合我的代码的解决方案,因为我需要更详细地演示这些步骤?
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      将图片转成numpy数组,一行就可以对所有二维数组进行操作

      from PIL import Image
      import numpy as np
      
      image = Image.open('my_image.png')
      
      # Convert Image to numpy array
      image_array = np.array(image)
      
      print(image_array.shape)
      # Prints something like: (1024, 1024, 4)
      # So we have 4 two-dimensional arrays: R, G, B, and the alpha channel
      
      # Do `255 - x` for every element in the first 3 two-dimensional arrays: R, G, B
      # Keep the 4th array (alpha channel) untouched
      image_array[:, :, :3] = 255 - image_array[:, :, :3]
      
      # Convert numpy array back to Image
      inverted_image = Image.fromarray(image_array)
      
      inverted_image.save('inverted.png')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-07-19
        • 2015-03-07
        • 1970-01-01
        • 1970-01-01
        • 2012-08-25
        • 1970-01-01
        相关资源
        最近更新 更多