简体   繁体   中英

Inverting pixels of an RGB image in Python

I'm trying to invert the pixels of an RGB image. That is, simply subtracting the intensity value of each channel (red, green, blue) of each pixel from 255 .

I have the following so far:

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)

When I run the above script, I get the following error:

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__

How can I solve this issue?

Thanks.

I guess you can use a vectorized operation if the image is a numpy array

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

You can use img.putpixel to assign the r,g,b,a values at each pixel-

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

Convert image to numpy array, and you can perform the operation on all 2-dimensional arrays in one line

在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM