其他分享
首页 > 其他分享> > 精确比较两张图片

精确比较两张图片

作者:互联网

方式1:pillow 库

方式2:scipy 库

 

方式1:pillow 库

需安装:pip install pillow

 1 from PIL import Image
 2 from selenium import webdriver
 3 
 4 
 5 class ImageCompare(object):
 6     '''
 7     本类实现了对两张图片通过像素比对的算法,获取文件的像素个数大小,
 8     然后使用循环的方式将两张图片的所有项目进行一一对比,并计算比对结果的相似度
 9     '''
10 
11     def make_regular_image(self, img, size=(256, 256)):
12         return img.resize(size).convert("RGB")
13 
14     def split_image(self, img, part_size=(64, 64)):
15         # 将图片按给定大小切分
16         w, h = img.size
17         pw, ph = part_size
18         assert w % pw == h % ph == 0
19         return [img.crop((i, j, i + pw, j + ph)).copy() for i in range(0, w, pw) for j in range(0, h, ph)]
20             
21     def hist_similar(self, lh, rh):
22         # 统计切分后每部分图片的相似度频率曲线
23         assert len(lh) == len(rh)
24         return sum(1 - (0 if l == r else float(abs(l - r)) / max(l, r)) for l, r in zip(lh, rh)) / len(lh)
25                 
26     def calc_similar(self, li, ri):
27         # 计算两张图片的相似度
28         return sum(self.hist_similar(l.histogram(), r.histogram()) for l, r in zip(self.split_image(li), self.split_image(ri))) / 16.0
29                 
30     def calc_similar_by_path(self, lf, rf):
31         li, ri = self.make_regular_image(Image.open(lf)), self.make_regular_image(Image.open(rf))
32         return self.calc_similar(li, ri)
33 
34 
35 if __name__ == "__main__":
36     IC = ImageCompare()
37     driver = webdriver.Chrome()
38     url = "http://www.sogou.com"
39     driver.get(url)
40     driver.save_screenshot("e:\\sogou1.png")
41     driver.get(url)
42     driver.save_screenshot("e:\\sogou2.png")
43     print ("%.2f%%" % (IC.calc_similar_by_path('e:\\sogou1.png','e:\\sogou2.png')*100))  # 99.84%
44     driver.quit()

 

方式2:scipy 库

 1 from scipy.misc import imread, imsave, imresize
 2 
 3 
 4 a = imread("E:\\sogou1.png")
 5 b = imread("E:\\sogou2.png")
 6 
 7 # 像素的差异数量
 8 diff = sum((a == b).reshape(-1)) - sum((a != b).reshape(-1))
 9 total = a.shape[0] * a.shape[1] * a.shape[2]
10 close = diff / total
11 
12 print("相似度 = {:.2%}".format(close))

 

标签:img,image,driver,两张,精确,similar,self,png,图片
来源: https://www.cnblogs.com/juno3550/p/14261543.html