Python 比较两张图片差异:查找不同像素
要实现这个功能,可以使用 Python 的 PIL 库(Pillow)来读取两张图片,并比较每个像素的 RGB 值来确定是否相同。
以下是一个示例代码:
from PIL import Image
def find_different_pixels(image1_path, image2_path):
# 打开两张图片
image1 = Image.open(image1_path)
image2 = Image.open(image2_path)
# 确保两张图片的大小一致
if image1.size != image2.size:
raise ValueError('图片大小不一致')
# 获取两张图片的像素数据
pixels1 = image1.load()
pixels2 = image2.load()
# 遍历每个像素,比较 RGB 值
different_pixels = []
for x in range(image1.width):
for y in range(image1.height):
if pixels1[x, y] != pixels2[x, y]:
different_pixels.append((x, y))
return different_pixels
# 示例用法
image1_path = 'image1.jpg'
image2_path = 'image2.jpg'
different_pixels = find_different_pixels(image1_path, image2_path)
print('不同的像素数量:', len(different_pixels))
print('不同的像素坐标:', different_pixels)
上述代码中,find_different_pixels 函数接受两张图片的路径作为输入,并返回不同像素的坐标列表。在示例用法中,我们传入两张图片的路径,并打印出不同像素的数量和坐标。
请注意,这个方法只能比较两张大小相同的图片。如果两张图片的大小不一致,会抛出一个 ValueError 异常。
原文地址: https://www.cveoy.top/t/topic/pzUq 著作权归作者所有。请勿转载和采集!