Python compares the similarity of two pictures

From , 3 Years ago, written in Python, viewed 195 times.
URL https://pastebin.vip/view/6d34d468
  1. #!/usr/bin/python
  2. # Filename: histsimilar.py
  3. # -*- coding: utf-8 -*-
  4.  
  5. import Image
  6.  
  7. def make_regalur_image(img, size = (256, 256)):
  8.         return img.resize(size).convert('RGB')
  9.  
  10. def split_image(img, part_size = (64, 64)):
  11.         w, h = img.size
  12.         pw, ph = part_size
  13.        
  14.         assert w % pw == h % ph == 0
  15.        
  16.         return [img.crop((i, j, i+pw, j+ph)).copy() \
  17.                                 for i in xrange(0, w, pw) \
  18.                                 for j in xrange(0, h, ph)]
  19.  
  20. def hist_similar(lh, rh):
  21.         assert len(lh) == len(rh)
  22.         return sum(1 - (0 if l == r else float(abs(l - r))/max(l, r)) for l, r in zip(lh, rh))/len(lh)
  23.  
  24. def calc_similar(li, ri):
  25. #       return hist_similar(li.histogram(), ri.histogram())
  26.         return sum(hist_similar(l.histogram(), r.histogram()) for l, r in zip(split_image(li), split_image(ri))) / 16.0
  27.                        
  28.  
  29. def calc_similar_by_path(lf, rf):
  30.         li, ri = make_regalur_image(Image.open(lf)), make_regalur_image(Image.open(rf))
  31.         return calc_similar(li, ri)
  32.  
  33. def make_doc_data(lf, rf):
  34.         li, ri = make_regalur_image(Image.open(lf)), make_regalur_image(Image.open(rf))
  35.         li.save(lf + '_regalur.png')
  36.         ri.save(rf + '_regalur.png')
  37.         fd = open('stat.csv', 'w')
  38.         fd.write('\n'.join(l + ',' + r for l, r in zip(map(str, li.histogram()), map(str, ri.histogram()))))
  39. #       print >>fd, '\n'
  40. #       fd.write(','.join(map(str, ri.histogram())))
  41.         fd.close()
  42.         import ImageDraw
  43.         li = li.convert('RGB')
  44.         draw = ImageDraw.Draw(li)
  45.         for i in xrange(0, 256, 64):
  46.                 draw.line((0, i, 256, i), fill = '#ff0000')
  47.                 draw.line((i, 0, i, 256), fill = '#ff0000')
  48.         li.save(lf + '_lines.png')
  49.        
  50.  
  51. if __name__ == '__main__':
  52.         path = r'testpic/TEST%d/%d.JPG'
  53.         for i in xrange(1, 7):
  54.                 print 'test_case_%d: %.3f%%'%(i, \
  55.                         calc_similar_by_path('testpic/TEST%d/%d.JPG'%(i, 1), 'testpic/TEST%d/%d.JPG'%(i, 2))*100)
  56.        
  57. #       make_doc_data('test/TEST4/1.JPG', 'test/TEST4/2.JPG')
  58.  
  59. #//python/9004

Reply to "Python compares the similarity of two pictures"

Here you can reply to the paste above

captcha

https://burned.cc - Burn After Reading Website