Ruby OpenCv模板匹配阈值

时间:2017-01-27 11:28:44

标签: ruby opencv template-matching

我正在尝试在图片上进行模板匹配,以便找到所有匹配项。为此,我想使用介于0和1之间的阈值来终止进程。我使用以下代码:

require 'opencv'
include OpenCV

template_filename = (ARGV.size == 2) ? ARGV[0] : File.expand_path(File.dirname(__FILE__) + '/lena-eyes.jpg')
match_image_filename = (ARGV.size == 2) ? ARGV[1] : File.expand_path(File.dirname(__FILE__) + '/lena-256x256.jpg')

template = CvMat.load(template_filename)
match_image = CvMat.load(match_image_filename)

10.times.each do |t|
  result = match_image.match_template(template, :sqdiff_normed)
  #result = result.normalize(0, 1, CV_NORM_MINMAX, -1, nil)

  pt1 = result.min_max_loc[2]
  pt2 = CvPoint.new(pt1.x + template.width, pt1.y + template.height)
  match_image.rectangle!(pt1, pt2, :color => CvColor::Black, :thickness => 3)
end

window = GUI::Window.new('Display window')
window.show(match_image)

问题是我使用match_template获得的最小值和最大值不在0和1之间,因此我无法使用阈值。第一个结果具有以下最小值和最大值:[0.00011,0.4955]。其他结果无效,具有以下最小值和最大值:[0.1190,0.5369],[0.1296,0.5369] ...

我试图将normalize方法与结果一起使用,但它总是给我0和1作为最小值和最大值。

我一直在网上冲浪,我在代码上找不到错误。有没有办法将结果最小值和最大值归一化到0和1之间?

1 个答案:

答案 0 :(得分:1)

最后我找到了解决方案。在深入阅读官方OpenCV文档中的template matching article之后,我已将match_image转换为灰度,并且我已更改了使用CCOEFF_NORMED方法的模板匹配方法。使用此方法,匹配点由max loc(result.min_max_loc [3])给出。

现在,当一个完全匹配时,最大值几乎等于1,当匹配相似但不相等时,最大值下降。

require 'opencv'
include OpenCV

template_filename = (ARGV.size == 2) ? ARGV[0] : File.expand_path(File.dirname(__FILE__) + '/lena-eyes.jpg')
match_image_filename = (ARGV.size == 2) ? ARGV[1] : File.expand_path(File.dirname(__FILE__) + '/lena-256x256.jpg')

template = CvMat.load(template_filename)
match_image = CvMat.load(match_image_filename)
match_image.BGR2GRAY

10.times.each do |t|
  result = match_image.match_template(template, :ccoeff_normed)
  pt1 = result.min_max_loc[3]
  pt2 = CvPoint.new(pt1.x + template.width, pt1.y + template.height)
  match_image.rectangle!(pt1, pt2, :color => CvColor::Black, :thickness => 3)
end

window = GUI::Window.new('Display window')
window.show(match_image)