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
廣告