Python Pillow - 颜色反转



Python Pillow 中的颜色反转是一种流行的照片效果,它通过将图像的颜色反转为色轮上的互补色调来转换图像。它会导致诸如黑色变为白色,白色变为黑色以及其他颜色变化。

此技术也称为图像反转或颜色取反,是图像处理中一种系统地改变图像中颜色的一种方法。在颜色反转的图像中,颜色以这样的方式转换,即明亮区域变暗,黑暗区域变亮,并且颜色在整个颜色范围内反转。

将颜色反转应用于图像

在 Python Pillow 中,颜色反转是通过反转整个图像光谱中的颜色来实现的。该库在其 ImageOps 模块 中提供了 **invert()** 函数,允许您将颜色反转应用于图像。此函数旨在反转给定图像的颜色,有效地应用颜色反转效果。该方法的语法如下:

PIL.ImageOps.invert(image)

其中,

  • **image** - 这是要反转的输入图像。

示例

以下示例使用 PIL.ImageOps.invert() 函数创建输入图像的反转版本。

from PIL import Image
import PIL.ImageOps

# Open an image
input_image = Image.open('Images/butterfly.jpg')

# Create an inverted version of the image
inverted_image = PIL.ImageOps.invert(input_image)

# Display the input image
input_image.show()

# Display the inverted image
inverted_image.show()

输入图像

butterfly and flowers

输出反转图像

butterfly inverted image

将颜色反转应用于 RGBA 图像

虽然 **ImageOps** 模块中的大多数函数都设计用于处理 L(灰度)和 RGB 图像。当您尝试将此反转函数应用于具有 RGBA 模式(包括用于透明度的 Alpha 通道)的图像时,它确实会引发 OSError,指出它不支持该图像模式。

示例

以下是一个示例,演示了如何在处理透明度时使用 RGBA 图像。

from PIL import Image
import PIL.ImageOps

# Open an image
input_image = Image.open('Images/python logo.png')

# Display the input image
input_image.show()

# Check if the image has an RGBA mode
if input_image.mode == 'RGBA':
    
   # Split the RGBA image into its components
   r, g, b, a = input_image.split()
   
   # Create an RGB image by merging the red, green, and blue components
   rgb_image = Image.merge('RGB', (r, g, b))
   
   # Invert the RGB image
   inverted_image = PIL.ImageOps.invert(rgb_image)
   
   # Split the inverted image into its components
   r2, g2, b2 = inverted_image.split()
   
   # Merge the inverted RGB image with the original alpha channel to maintain transparency
   final_transparent_image = Image.merge('RGBA', (r2, g2, b2, a))
   
   # Show the final transparent image
   final_transparent_image.show()
else:
   # Invert the image for non-RGBA images
   inverted_image = PIL.ImageOps.invert(input_image)
   inverted_image.show()

输入图像

python logo

输出反转图像

inverted python logo
广告

© . All rights reserved.