Advertisement
Guest User

Untitled

a guest
Jan 20th, 2017
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 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 networkx as nx
  10. import subprocess as sb
  11.  
  12.  
  13. # global variances
  14. THRESHOLD = 0.15
  15.  
  16.  
  17. def usage():
  18. print('Usage:\n\tpython3 {f} folder_name'.format(f=__file__))
  19. exit()
  20.  
  21. def matching():
  22.  
  23. # 画像リストの作成
  24. Pictures = glob('{folder}/*'.format(folder=FolderName))
  25.  
  26. # ヒストグラムの計算
  27. image_hists = dict()
  28. for picture in Pictures:
  29. im = cv2.imread(picture)
  30. image_hists[picture] = cv2.calcHist([im], [0], None, [256], [0, 256])
  31.  
  32. # 類似度の計算
  33. result = list()
  34. for pictA, pictB in combinations(Pictures, 2):
  35. image_histA, image_histB = image_hists[pictA], image_hists[pictB]
  36. tmp = cv2.compareHist(image_histA, image_histB, 3)
  37. if tmp < THRESHOLD:
  38. result.append((tmp, pictA, pictB))
  39.  
  40. # クラスタの計算
  41. G = nx.Graph()
  42. for _, nodeA, nodeB in result:
  43. G.add_edge(nodeA, nodeB)
  44. # print('類似度:{0:0.3f} 画像名:{1} {2}'.format(result[i][0], result[i][1], result[i][2]))
  45.  
  46. # 結果の出力
  47. # 類似画像なし
  48. if G.number_of_nodes() == 0:
  49. print('Same pictures are not found.')
  50. exit()
  51.  
  52. # 類似画像あり
  53. print('Maybe same pictures ...')
  54. for i, component in enumerate(nx.connected_components(G)):
  55. print('[{}] {}'.format(i, ' '.join(component)))
  56.  
  57. # 画像をOpenするかどうか
  58. print('Open those?(y or n)')
  59. ans = input()
  60. if ans in ['y', 'yes']:
  61. for component in nx.connected_components(G):
  62. component = list(component)
  63. print(['open'] + component)
  64. sb.run(['open'] + component)
  65.  
  66. return 1
  67.  
  68. if __name__ == '__main__':
  69. if len(argv) == 2:
  70. FolderName = argv[1] if argv[1] != '/' else argv[1][:-1]
  71. matching()
  72. else:
  73. usage()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement