python image comparison
I found an image comparison code on the Internet, and found a method as follows:
from PIL import Image
from PIL import ImageChops
def compare_images(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对应的宽度不一致")
print("【{0}】{1}".format(e,text))
This method can achieve the comparison of pictures, but the effect is not very good, and then I found a more useful method (I don’t want to use CV2) as follows, share it with you
#图像比较
from PIL import Image
import math
import operator
from functools import reduce
def compare_images(pic1,pic2):
image1 = Image.open(pic1)
image2 = Image.open(pic2)
histogram1 = image1.histogram()
histogram2 = image2.histogram()
differ = math.sqrt(reduce(operator.add, list(map(lambda a,b: (a-b)**2,histogram1, histogram2)))/len(histogram1))
print('differ:',differ)
if differ == 0:
return 'same'
else:
return 'diff'