# 【转载】计算图像相似度——《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

23 def calc_similar(li, ri):

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

28 def calc_similar_by_path(lf, rf):

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

30     return calc_similar(li, ri)

31

32 if __name__ == '__main__':

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

34     for i in xrange(1, 7):

35        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%

图像的相似度计算是图像检索、识别的基础,本文只是浅尝辄止地介绍了其中最基本的计算方法,如果你要学习和研究更好的算法,也请记住 Python 也能帮助你哦~

posted @ 2021-05-16 22:47  JarvisLau  阅读(633)  评论(0编辑  收藏  举报