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
广告
© . All rights reserved.