在Python中,可以使用多种方法来对比两张图片并找出不同之处。以下是几种常见的方法:
方法一:使用OpenCVOpenCV是一个强大的计算机视觉库,可以用来处理图像。以下是一个使用OpenCV的示例代码:
import cv2 import numpy as np def compare_images(img1_path, img2_path, output_path): # 读取图像 img1 = cv2.imread(img1_path) img2 = cv2.imread(img2_path) # 确保两张图片大小相同 if img1.shape != img2.shape: raise ValueError("两张图片大小不同") # 计算两张图片的差异 diff = cv2.absdiff(img1, img2) # 将差异转换为灰度图像 gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY) # 应用阈值以突出差异 _, thresh = cv2.threshold(gray, 30, 255, cv2.THRESH_BINARY) # 找到差异的轮廓 contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # 在原图上绘制轮廓 for contour in contours: if cv2.contourArea(contour) > 100: # 过滤掉小的差异 x, y, w, h = cv2.boundingRect(contour) cv2.rectangle(img1, (x, y), (x + w, y + h), (0, 255, 0), 2) # 保存结果图像 cv2.imwrite(output_path, img1) # 使用示例 compare_images('image1.jpg', 'image2.jpg', 'output.jpg')方法二:使用PIL和NumPy
PIL(Pillow)是Python的一个图像处理库,结合NumPy可以进行图像对比。以下是一个示例代码:
from PIL import Image, ImageDraw import numpy as np def compare_images(img1_path, img2_path, output_path): # 打开图像 img1 = Image.open(img1_path) img2 = Image.open(img2_path) # 确保两张图片大小相同 if img1.size != img2.size: raise ValueError("两张图片大小不同") # 将图像转换为NumPy数组 arr1 = np.array(img1) arr2 = np.array(img2) # 计算两张图片的差异 diff = np.abs(arr1 - arr2) # 将差异转换为灰度图像 gray_diff = np.mean(diff, axis=2) # 应用阈值以突出差异 thresh = (gray_diff > 30).astype(np.uint8) * 255 # 找到差异的轮廓 contours = np.argwhere(thresh) # 在原图上绘制轮廓 draw = ImageDraw.Draw(img1) for y, x in contours: draw.rectangle([x, y, x + 1, y + 1], outline="green") # 保存结果图像 img1.save(output_path) # 使用示例 compare_images('image1.jpg', 'image2.jpg', 'output.jpg')方法三:使用ImageChops模块
Pillow库中的ImageChops模块提供了一些基本的图像操作功能,可以用来对比图像。以下是一个示例代码:
from PIL import Image, ImageChops, ImageDraw def compare_images(img1_path, img2_path, output_path): # 打开图像 img1 = Image.open(img1_path) img2 = Image.open(img2_path) # 确保两张图片大小相同 if img1.size != img2.size: raise ValueError("两张图片大小不同") # 计算两张图片的差异 diff = ImageChops.difference(img1, img2) # 将差异转换为灰度图像 gray_diff = diff.convert("L") # 应用阈值以突出差异 thresh = gray_diff.point(lambda p: 255 if p > 30 else 0) # 找到差异的轮廓 contours = thresh.getbbox() # 在原图上绘制轮廓 draw = ImageDraw.Draw(img1) if contours: draw.rectangle(contours, outline="green") # 保存结果图像 img1.save(output_path) # 使用示例 compare_images('image1.jpg', 'image2.jpg', 'output.jpg')
以上三种方法都可以用来对比两张图片并找出不同之处。选择哪种方法取决于你的具体需求和偏好。
网友回复