Created
April 20, 2012 15:12
-
-
Save ser1zw/2429501 to your computer and use it in GitHub Desktop.
ruby-opencvのテンプレートマッチングのサンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ruby-opencvのテンプレートマッチングのサンプル | |
# https://github.com/ruby-opencv/ruby-opencv | |
require 'opencv' | |
include OpenCV | |
# (1) 画像を読み込み | |
image = CvMat.load('image.jpg') # テンプレートと比較する画像 | |
template = CvMat.load('template.jpg') # テンプレート画像 | |
# (2) CvMat#match_template でテンプレートマッチング | |
# | |
# CvMat#match_template(template [, method = CV_TM_SQDIFF]) | |
# 引数 | |
# template (CvMat/IplImage): 探索するテンプレート画像 | |
# method (Integer/Symbol): テンプレートマッチング手法 | |
# 戻り値 | |
# 比較結果のマップ (CvMat) | |
# | |
# methodにはcvMatchTemplateと同じく、 | |
# 定数 CV_TM_SQDIFF/CV_TM_SQDIFF_NORMED/CV_TM_CCORR/CV_TM_CCORR_NORMED/CV_TM_CCOEFF/CV_TM_CCOEFF_NORMED | |
# を指定(デフォルトはCV_TM_SQDIFF) | |
# それぞれの代わりに、シンボル :sqdiff/:sqdiff_normed/:ccorr/:ccorr_normed/:ccoeff/:ccoeff_normed でも可 | |
# | |
# 参考 http://opencv.jp/opencv-2.2/c/imgproc_object_detection.html#cvMatchTemplate | |
# | |
result = image.match_template(template, CV_TM_SQDIFF) # CV_TM_SQDIFF の代わりに :sqdiff でも同じ | |
# (3) テンプレートに対応する位置に描画 | |
# | |
# CvMat#min_max_loc は画像の [最小値, 最大値, 最小値の座標, 最大値の座標] の配列を返す (cvMinMaxLocのラッパー) | |
# match_template の手法で CV_TM_SQDIFF を指定した場合は、最も相関が高い位置が result の最小値となるので、 | |
# 最小値の座標を取得する | |
pt1 = result.min_max_loc[2] | |
pt2 = CvPoint.new(pt1.x + template.width, pt1.y + template.height) | |
image.rectangle!(pt1, pt2, :color => CvColor::Black, :thickness => 3) | |
# (4) 結果を表示 | |
GUI::Window.new('Template matching').show image | |
GUI::wait_key |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment