这篇文章给大家介绍使用python怎么对比两张图片的不同点,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
from PIL import Image
from PIL import ImageChops
def compare_images(path_one, path_two, diff_save_location):
"""
比较图片,如果有不同则生成展示不同的图片
@参数一: path_one: 第一张图片的路径
@参数二: path_two: 第二张图片的路径
@参数三: diff_save_location: 不同图的保存路径
"""
image_one = Image.open(path_one)
image_two = Image.open(path_two)
try:
diff = ImageChops.difference(image_one, image_two)
if diff.getbbox() is None:
# 图片间没有任何不同则直接退出
print("【+】We are the same!")
else:
diff.save(diff_save_location)
except ValueError as e:
text = ("表示图片大小和box对应的宽度不一致,参考API说明:Pastes another image into this image."
"The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, "
"right, and lower pixel coordinate, or None (same as (0, 0)). If a 4-tuple is given, the size of the pasted "
"image must match the size of the region.使用2纬的box避免上述问题")
print("【{0}】{1}".format(e,text))
if __name__ == '__main__':
compare_images('1.png',
'2.png',
'我们不一样.png')
第二种方法:
from PIL import Image
import math
import operator
from functools import reduce
def image_contrast(img1, img2):
image1 = Image.open(img1)
image2 = Image.open(img2)
h2 = image1.histogram()
h3 = image2.histogram()
result = math.sqrt(reduce(operator.add, list(map(lambda a,b: (a-b)**2, h2, h3)))/len(h2) )
return result
if __name__ == '__main__':
img1 = "./1.png" # 指定图片路径
img2 = "./2.png"
result = image_contrast(img1,img2)
print(result)
如果两张图片完全相等,则返回结果为浮点类型“0.0”,如果不相同则返回结果值越大。
同样用上面两张图片,执行结果为38,还是比较小的:
关于使用python怎么对比两张图片的不同点就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。