Python Pillow - ImageChops.difference() 函数



PIL.ImageChops.difference 函数计算两张图像逐像素差的绝对值。它返回一个新图像,其中每个像素表示输入图像中对应像素之间差异的绝对值。

操作定义如下:

$$\mathrm{out\:=\:abs(image1\:-\:image2)}$$

语法

以下是函数的语法:

PIL.ImageChops.difference(image1, image2)

参数

以下是该函数参数的详细信息:

  • image1 - 第一个输入图像。

  • image2 - 第二个输入图像。

返回值

此函数的返回类型为 Image。

示例

示例 1

在此示例中,我们将使用 getpixel() 函数来观察在对两个输入图像应用 ImageChops.difference() 函数后得到的像素值。

from PIL import Image, ImageChops
import numpy as np

# Create two random RGB images
image1 = Image.fromarray(np.array([(235, 64, 3), (255, 0, 0), (255, 255, 0), (255, 255, 255), (164, 0, 3)]), mode="RGB")
print("Pixel values of image1 at (0, 0):", image1.getpixel((0, 0)))

image2 = Image.fromarray(np.array([(25, 14, 3), (25, 222, 0), (255, 155, 0), (255, 55, 100), (180, 0, 78)]), mode="RGB")
print("Pixel values of image2 at (0, 0):", image2.getpixel((0, 0)))

# Compute the absolute pixel-wise difference between the two images
result = ImageChops.difference(image1, image2)
print("Pixel value in result at (0, 0) after difference:", result.getpixel((0, 0)))

输出

Pixel values of image1 at (0, 0): (235, 0, 0)
Pixel values of image2 at (0, 0): (25, 0, 0)
Pixel value in result at (0, 0) after difference: (210, 0, 0)

示例 2

在此示例中,ImageChops.difference() 函数用于计算两个 JPEG 图像(image1 和 image2)之间的绝对像素差。

from PIL import Image, ImageChops
import numpy as np

# Open two image files
image1 = Image.open('Images/butterfly.jpg')
image2 = Image.open('Images/flowers.jpg')

# Compute the absolute pixel-wise difference between the two images
result = ImageChops.difference(image1, image2)

# Display the input and resulting images
image1.show()
image2.show()
result.show()

输出

输入图像 1

butterfly on flower

输入图像 2

sun rays on pink flower

输出图像

imagechops difference

示例 3

在此示例中,ImageChops.difference() 函数用于两个 JPEG 图像文件,以计算这两个图像之间的绝对像素差。

from PIL import Image, ImageChops

# Open two image files
image1 = Image.open('Images/pillow-logo.png')
image2 = Image.open('Images/test_img.png')

# Compute the absolute pixel-wise difference between the two images
result = ImageChops.difference(image1, image2)

# Display the input and resulting images
image1.show()
image2.show()
result.show()

# Print the pixel values at a specific location (e.g., (100, 100))
print("Pixel value in image1 at (100, 100):", image1.getpixel((100, 100)))
print("Pixel value in image2 at (100, 100):", image2.getpixel((100, 100)))
print("Pixel value in result at (100, 100) after difference:", result.getpixel((100, 100)))

输出

输入图像 1

pillow logo s

输入图像 2

test img

输出图像

chops difference
Pixel value in image1 at (100, 100): (183, 84, 131, 255)
Pixel value in image2 at (100, 100): (174, 65, 9, 255)
Pixel value in result at (100, 100) after difference: (9, 19, 122, 0)
python_pillow_function_reference.htm
广告