Python Pillow - ImageChops.invert() 函式



在 Python 影像處理庫 Pillow (PIL) 中,位於 ImageOps 模組中的 invert 函式提供了一種方便的方法來執行影像中畫素值的負正反轉。

此 PIL.ImageChops.invert 函式用於反轉影像或通道的畫素值。它透過從最大可能的畫素值中減去每個畫素值來計算反轉值。該操作實現如下:

$$\mathrm{out\:=\:MAX\:−\:image}$$

語法

以下是函式的語法:

PIL.ImageChops.invert(image)

引數

以下是此函式引數的詳細資訊:

  • image - 將反轉其畫素值的輸入影像。

返回值

此函式的返回型別為 Image。

示例

示例 1

這是一個使用 ImageChops.invert() 函式對 JPEG 影像檔案執行畫素值負正反轉的示例。

from PIL import Image, ImageChops

# Open a PNG image file
original_image = Image.open('Images/Car_2.jpg')

# Invert the pixel values of the image
inverted_image = ImageChops.invert(original_image)

# Display the input and resulting images
original_image.show()
inverted_image.show()

輸出

輸入影像

balck yellow car

輸出影像

blue car

示例 2

此示例演示了在將 ImageChops.invert() 應用於 BMP 型別輸入影像之前和之後畫素值。

from PIL import Image, ImageChops

# Open an image file
original_image = Image.open('Images/lena.bmp')

# Display the pixel values before inversion
print("Pixel values in the original image at (0, 0) before inversion:", original_image.getpixel((0, 0)))

# Apply the ImageChops.invert() function to invert pixel values
inverted_image = ImageChops.invert(original_image)

# Display the pixel values after inversion
print("Pixel values in the inverted image at (0, 0) after inversion:", inverted_image.getpixel((0, 0)))

# Display the input and resulting images
original_image.show()
inverted_image.show()

輸出

輸入影像

girl picture

輸出影像

imagechops invert

示例 3

以下示例演示如何使用 ImageChops.invert() 函式對 RGB 影像的單個通道應用反轉操作。

from PIL import Image, ImageChops

# Open an image file
original_image = Image.open('Images/flowers.jpg')

# Split the channels of the image
red, green, blue = original_image.split()

# Invert the green channel
inverted_green_channel = ImageChops.invert(green)

# Merge the channels back into an RGB image
image_with_inverted_green = Image.merge('RGB', (red, inverted_green_channel, blue))

# Display the input and resulting images
original_image.show()
image_with_inverted_green.show()

輸出

輸入影像

sun rays on pink flower

輸出影像

chops invert
python_pillow_function_reference.htm
廣告