帮我写一个python脚本,用于对比两张图片的差异
时间: 2023-06-03 22:07:26 浏览: 214
易语言图片差异对比源码.rar
好的,以下是用Python对比两张图片差异的脚本代码:
```python
from PIL import Image
def compare_images(image1_path, image2_path):
img1 = Image.open(image1_path)
img2 = Image.open(image2_path)
if img1.size != img2.size:
print("The images have different sizes.")
return False
pairs = zip(img1.getdata(), img2.getdata())
if len(img1.getbands()) == 1:
dif = sum(abs(p1 - p2) for p1, p2 in pairs)
else:
dif = sum(abs(c1 - c2) for p1, p2 in pairs for c1, c2 in zip(p1, p2))
n_components = img1.size[0] * img1.size[1] * 3
difference = (dif / 255.0 * 100) / n_components
print("The images are {:.2%} different.".format(difference))
return True
if __name__=="__main__":
image1_path = "image1.jpg"
image2_path = "image2.jpg"
compare_images(image1_path, image2_path)
```
你可以将 `image1_path` 和 `image2_path` 换成你自己要比较的图片路径。这个脚本会输出两张图片的差异度百分比。越接近0,说明两张图片越相似。
阅读全文