python 图像比较

python 图像比较


在网上薅一个图像比较的代码,之前找到一种方法如下:

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))

这种方法可以实现图片的比较,但是效果不是太好,然后又找了一种比较好用的方法(不想用CV2)如下,分享给大家用


#图像比较
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'

猜你喜欢

转载自blog.csdn.net/weixin_45386875/article/details/113818370