【画像認識】Pythonで画像認識とか(テンプレートマッチング:正規化相互相関)
はじめに
最近はDeep Learningを使った画像認識ばかりでしたので、
画像認識の初歩に立ち返ってテンプレートマッチング処理をpythonとOpenCVで実装しました。
楽しみながらやりたかったので、
今回テンプレートマッチには麻雀牌を選びました。
また、いくつかあるテンプレートマッチングの中で正規化相互相関を使っています。
この正規化相互相関は画像の全体的な輝度変化に頑健なアルゴリズムです。
※各牌の画像は天鳳さんでお借りしてます。
オンライン対戦麻雀 天鳳 / 牌画
テンプレート画像一覧
ターゲット画像
出力結果
同じ画像に対してマッチング処理しているので当然スコアは1.0ですね。
ソースコード
各テンプレート画像に対してターゲット画像とテンプレートマッチングを行っています。
ちょっと無駄が多いですが、一番簡単に実装するならこの方法かと...
今後いろいろ改良を加えていきたいと思います。
# -*- coding:utf-8 -*- import os import os.path import cv2 import argparse # 引数指定 parser = argparse.ArgumentParser(description='Train Sample') parser.add_argument('--target', '-t', default='', type=str, help='Target Image') parser.add_argument('--template', '-temp', default='unit', type=str, help='Template Folder') parser.add_argument('--out', '-o', type=str, default='out', help='Output File') args = parser.parse_args() template_list = os.listdir(args.template) template_images = [] # テンプレート一覧画像取得 for template_name in template_list: image = cv2.imread(args.template+"/"+template_name) template_images.append(image) # マッチング対象 target_image = cv2.imread(args.target) # 出力用 target_out_image = cv2.imread(args.target) # 各テンプレート画像でマッチング for template_image in template_images: # TM_CCOEFF_NORMED ゼロ正規化相互相関 res = cv2.matchTemplate(target_image, template_image, cv2.TM_CCOEFF_NORMED) # 一番小さいスコアとその座標、一番高いスコアとその座標を取得する min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) top_left = max_loc print max_val if max_val > 0.9: h, w = template_image.shape[:2] bottom_right = (top_left[0] + w, top_left[1] + h) # cv2.rectangle(out, pt1, pt2, color, thickness) cv2.rectangle(target_out_image, top_left, bottom_right, 255, 2) # image[y,x] = roi target_out_image[top_left[1]-h:top_left[1], top_left[0]:top_left[0]+w,:] = template_image # スコアを出力 cv2.putText(target_out_image, "%0.2lf"%max_val, (top_left[0],top_left[1]-h), cv2.FONT_HERSHEY_PLAIN, 1, (0,0,255), thickness=2) cv2.imshow("out", target_out_image) cv2.imshow("template", template_image) cv2.waitKey(100) # 出力 cv2.imwrite(args.out, target_out_image)