BLOG

 

235日のセブIT留学  成長日記「Pytonで類似画像の解析!③」 ( 39/235 days )

16 8月 2018, Posted by keisuke in IT留学, プログラミング

こんばんわ!Keisukeです!

 

今日は, 特徴量を用いて類似画像解析を行いたいと思います!

 

特徴量解析は画像の特徴的な部分同志を比較する解析手法になります!

 

比較したい画像の名前を

”target”とし, 比較する画像をすべてimagesというファイルに格納します!

target

 

比較画像

 

以下コード

 

import cv2

import os

 

if __name__ == ‘__main__’:

   TARGET_FILE = ‘target.png’

   IMG_DIR = os.path.abspath(os.path.dirname(__file__)) + ‘/images/’

   IMG_SIZE = (200, 200)

   target_img_path = IMG_DIR + TARGET_FILE

   target_img = cv2.imread(target_img_path, cv2.IMREAD_GRAYSCALE)

   target_img = cv2.resize(target_img, IMG_SIZE)

 

   bf = cv2.BFMatcher(cv2.NORM_HAMMING)

   detector = cv2.AKAZE_create()

   (target_kp, target_des) = detector.detectAndCompute(target_img, None)

   print(‘TARGET_FILE: %s’ % (TARGET_FILE))

   files = os.listdir(IMG_DIR)

 

   for file in files:

       if file == ‘.DS_Store’ or file == TARGET_FILE:

           continue

 

       comparing_img_path = IMG_DIR + file

       try:

           comparing_img = cv2.imread(comparing_img_path, cv2.IMREAD_GRAYSCALE)

           comparing_img = cv2.resize(comparing_img, IMG_SIZE)

           (comparing_kp, comparing_des) = detector.detectAndCompute(comparing_img, None)

           matches = bf.match(target_des, comparing_des)

           dist = [m.distance for m in matches]

           ret = sum(dist) / len(dist)

       except cv2.error:

           ret = 100000

 

       print(file, ret)

 

実行結果

 

1.png 0.0

cat1.jpg 141.2808988764045

 

1枚目の画像は同じ画像なので特徴量の距離が一致しているため0となっています

2枚目は, 全く関係ない画像で相関性がないようです。

 

前回と同様に猫の画像でも比較してみます。

target

比較

    cat.jpg                                                  cat2.jpg

 

cat.jpg 142.48543689320388

cat2.jpg 143.6601941747573

 

targetにはcat.jpgのほうが似ている

 

ん~, どうやら特徴量の距離の大きさからtargetにはこっちがのほうが似ている!ということまでわかるようですね

明確な定義を取り入れたいですね!

 

[今日の達成]

・特徴量解析を行った

 

[今日の未消化]

・何%似ているかなど, 明確な基準を定義する

 

Post a comment