# 计算图像相似度——《Python也可以》

6 def make_regalur_image(img, size = (256, 256)):

7 return img.resize(size).convert('RGB')

Sim(G,S)=，其中G,S为直方图，N 为颜色空间样点数

19 def hist_similar(lh, rh):

20 assert len(lh) == len(rh)

21 return sum(1 - (0 if l == r else float(abs(l - r))/max(l, r)) for l, r in zip(lh, rh))/len(lh)

22 def calc_similar(li, ri):

23 return hist_similar(li.histogram(), ri.histogram())

def calc_similar_by_path(lf, rf):

li, ri = make_regalur_image(Image.open(lf)), make_regalur_image(Image.open(rf))

return calc_similar(li, ri)

if __name__ == '__main__':

path = r'test/TEST%d/%d.JPG'

for i in xrange(1, 7):

print 'test_case_%d: %.3f%%'%(i, calc_similar_by_path('test/TEST%d/%d.JPG'%(i, 1), 'test/TEST%d/%d.JPG'%(i, 2))*100)

test_case_1: 63.322%

test_case_2: 66.950%

test_case_3: 51.990%

test_case_4: 70.401%

test_case_5: 32.755%

test_case_6: 42.203%

9 def split_image(img, part_size = (64, 64)):

10 w, h = img.size

11 pw, ph = part_size

12

13 assert w % pw == h % ph == 0

14

15 return [img.crop((i, j, i+pw, j+ph)).copy() /

16 for i in xrange(0, w, pw) /

17 for j in xrange(0, h, ph)]

23 def calc_similar(li, ri):

24 # return hist_similar(li.histogram(), ri.histogram())

25 return sum(hist_similar(l.histogram(), r.histogram()) for l, r in zip(split_image(li), split_image(ri))) / 16.0

test_case_1: 56.273%

test_case_2: 54.925%

test_case_3: 49.326%

test_case_4: 40.254%

test_case_5: 30.776%

test_case_6: 39.460%

• 发表于:
• 原文链接http://kuaibao.qq.com/s/20180206A0QF9U00?refer=cp_1026
• 腾讯「云+社区」是腾讯内容开放平台帐号（企鹅号）传播渠道之一，根据《腾讯内容开放平台服务协议》转载发布内容。
• 如有侵权，请联系 yunjia_community@tencent.com 删除。

2021-12-09

2021-12-09

2021-12-09

2021-12-09

2021-12-09

2021-12-09

2018-06-25

2021-12-09

2021-12-09

2021-12-09

2021-12-09

2021-12-09