Advertisement
Guest User

Untitled

a guest
Jan 20th, 2017
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.83 KB | None | 0 0
  1. # ---- memo -----------------------
  2. # フォルダの中にある画像の中で
  3. # 類似したものを見つける
  4. # ---------------------------------
  5. import cv2
  6. from sys import argv
  7. from glob import glob
  8. from itertools import combinations
  9. import subprocess as sb
  10. from os import environ
  11.  
  12. METHOD_NAME = ['Correlation', 'Chi-square', 'Intersection', 'Bhattacharyya distance']
  13. THRESHOLD_DEF = [0.9, 100000, 1600000, 0.15]
  14.  
  15. # environment variable
  16. METHOD = int(environ.get('METHOD', 3))
  17. THRESHOLD = float(environ.get('THRESHOLD', THRESHOLD_DEF[METHOD]))
  18.  
  19.  
  20. __doc__="""
  21. Usage:
  22. [METHOD=(int)] [THRESHOLD=(float)] python3 {f} folder_name
  23.  
  24. environment variable
  25. METHOD:
  26. 0: Correlation
  27. 1: Chi-square
  28. 2: Intersection
  29. 3: Bhattacharyya distance <- Default
  30.  
  31. THRESHOLD:
  32. estimated THRESHOLD
  33. METHOD = 0 -> 0.88 ~ 1 (Default is 0.9)
  34. METHOD = 1 -> 80000 ~ 120000 (Default is 100000)
  35. METHOD = 2 -> 1200000 ~ 2000000 (Default is 1600000)
  36. METHOD = 3 -> 0.05 ~ 0.2 (Default is 0.15)
  37.  
  38. exsample)
  39. METHOD=0 python3 {f} folder_name
  40. METHOD=3 THRESHOLD=0.2 python3 {f} folder_name
  41. """.format(f=__file__)
  42.  
  43. def usage():
  44. # print('Usage:\n\t[THRESHOLD=(float)] [METHOD=(int)] python3 {f} folder_name'.format(f=__file__))
  45. print(__doc__)
  46. exit()
  47.  
  48. def matching():
  49. print('METHOD: {}'.format(METHOD_NAME[METHOD]))
  50. print('THRESHOLD: {}'.format(THRESHOLD))
  51.  
  52. # 画像リストの作成(gifは除外)
  53. Pictures = glob('{folder}/*'.format(folder=FolderName))
  54. Pictures[:] = [pict for pict in Pictures if pict.split('.')[-1] != 'gif']
  55.  
  56. # ヒストグラムの計算
  57. image_hists = dict()
  58. for picture in Pictures:
  59. im = cv2.imread(picture)
  60. image_hists[picture] = cv2.calcHist([im], [0], None, [256], [0, 256])
  61.  
  62. # 類似度の計算
  63. result = list()
  64. for pictA, pictB in combinations(Pictures, 2):
  65. image_histA, image_histB = image_hists[pictA], image_hists[pictB]
  66. tmp = cv2.compareHist(image_histA, image_histB, METHOD)
  67. if METHOD in [1, 3]:
  68. if tmp < THRESHOLD:
  69. result.append((tmp, pictA, pictB))
  70. else:
  71. if tmp > THRESHOLD:
  72. result.append((tmp, pictA, pictB))
  73.  
  74.  
  75. # 連結成分の計算
  76. repr_dict = dict()
  77. pict2repr = dict()
  78. for _, nodeA, nodeB in result:
  79. is_A, is_B = nodeA in pict2repr, nodeB in pict2repr
  80. if not is_A and not is_B:
  81. repr_dict[nodeA] = [nodeA, nodeB]
  82. pict2repr[nodeA] = nodeA
  83. pict2repr[nodeB] = nodeA
  84. if is_A and not is_B:
  85. repr_dict[pict2repr[nodeA]].append(nodeB)
  86. pict2repr[nodeB] = pict2repr[nodeA]
  87. if not is_A and is_B:
  88. repr_dict[pict2repr[nodeB]].append(nodeA)
  89. pict2repr[nodeA] = pict2repr[nodeB]
  90. if is_A and is_B:
  91. if pict2repr[nodeA] == pict2repr[nodeB]:
  92. continue
  93. repr_dict[pict2repr[nodeA]] += repr_dict[pict2repr[nodeB]]
  94. for pict in repr_dict[pict2repr[nodeB]]:
  95. pict2repr[pict] = pict2repr[nodeA]
  96.  
  97. # 結果の出力
  98. # 類似画像なし
  99. if len(result) == 0:
  100. print('Same pictures are not found.')
  101. exit()
  102.  
  103. # 類似画像あり
  104. print('Maybe same pictures ...')
  105. for i, _repr in enumerate(set(pict2repr.values())):
  106. print('[{}] {}'.format(i, ' '.join(repr_dict[_repr])))
  107.  
  108. # 画像をOpenするかどうか
  109. print('Open those?(y or n)')
  110. ans = input()
  111. if ans in ['y', 'yes']:
  112. for _repr in set(pict2repr.values()):
  113. component = repr_dict[_repr]
  114. sb.run(['open'] + component)
  115.  
  116. return 1
  117.  
  118. if __name__ == '__main__':
  119. if len(argv) == 2 and argv[1] not in ['-h', '--help']:
  120. FolderName = argv[1] if argv[1] != '/' else argv[1][:-1]
  121. matching()
  122. else:
  123. usage()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement