[英]Template matching in openCV [JAVA]
我正在使用OpenCV(opencv_java248) 。 我有一个模板图像。 该模板图像具有徽标的一些公司。 我想知道此徽标是否包含在其他图像中。 我在某处遵循了代码。
public void run(String inFile, String templateFile, String outFile,
int match_method) {
System.out.println("Running Template Matching");
Mat img = Highgui.imread(inFile);
Mat templ = Highgui.imread(templateFile);
// / Create the result matrix
int result_cols = img.cols() - templ.cols() + 1;
int result_rows = img.rows() - templ.rows() + 1;
Mat result = new Mat(result_rows, result_cols, CvType.CV_32FC1);
// / Do the Matching and Normalize
Imgproc.matchTemplate(img, templ, result, match_method);
// Core.normalize(result, result, 0, 1, Core.NORM_MINMAX, -1, new
// Mat());
Imgproc.threshold(result, result, 0.5, 1.0, Imgproc.THRESH_TOZERO);
// / Localizing the best match with minMaxLoc
MinMaxLocResult mmr = Core.minMaxLoc(result);
Point matchLoc;
if (match_method == Imgproc.TM_SQDIFF
|| match_method == Imgproc.TM_SQDIFF_NORMED) {
matchLoc = mmr.minLoc;
} else {
matchLoc = mmr.maxLoc;
}
double threashhold = 0.40;
if (mmr.maxVal > threashhold) {
Core.rectangle(img, matchLoc, new Point(matchLoc.x + templ.cols(),
matchLoc.y + templ.rows()), new Scalar(0, 255, 0));
}
// Save the visualized detection.
Highgui.imwrite(outFile, img);
}
您想要匹配的图像或一些代码将非常有用。
我不知道Java API,但最近确实研究了用C ++编写的类似内容。 转换应该相当简单,因为两种语言的处理过程都是相同的。
首先,像往常一样执行模板匹配,读入图像并创建垫以保存结果。
cv::Mat drawing = cv::imread(_drawing); //Read drawing
cv::Mat tmp = cv::imread(_tmp); //Read template
cv::Mat res(drawing.rows - tmp.rows + 1, drawing.cols - tmp.cols + 1, CV_32FC1); //Create result matrix
//Perform template matching, normalise results 0 -> 1
cv::matchTemplate(tmp, drawing, res, CV_TM_CCOEFF_NORMED);
cv::threshold(res, res, 0.8, 1.0, CV_THRESH_TOZERO); //Can thresh to filter results if needed
现在已经填充了结果,创建变量以保存最小/最大分数及其在结果矩阵中的位置。
容差值用于过滤可接受的结果,其中1.0可以看作是100%匹配,而0.25可以看作是25%。
//min/max values and acceptable tolerance
double min, max, tolerance = 0.90;
cv::Point minloc, maxloc; //min/max value locations
现在从结果中提取值,并根据容差检查最大值,如果在容差范围之内。
您还可以循环执行此过程,并检查所有结果以查看图像是否包含模板的多次出现。
//Loop through all results
while (true){
//Pull out min/max values from results matrix
cv::minMaxLoc(res, &min, &max, &minloc, &maxloc);
//Is max within tolerance
if (max >= tolerance){
//Yes - Match found, do stuff //
//Blank out that result in matrix so next highest can be extracted
cv::floodFill(res, maxloc, cv::Scalar(0), 0, cv::Scalar(0.1), cv::Scalar(1.0));
}
else
break; //No more results within tolerance, break search
}
您可能需要尝试公差/图像质量以及什么才算合格。 但是对于简单的匹配来说,效果很好。
编辑-模板匹配和比例
标准模板匹配仅由于其工作原理而在缩放方面的表现非常差-搜索窗口只能与提供的模板一样小,因此要查找任何较小(或较大)的对象将很困难。
精简模板匹配以实现尺度不变性不是一件容易的事,您可以尝试的一种简单方法是创建模板的尺度变化(请看一下OpenCVs图像金字塔)。
如果感兴趣的话,还有很多论文涉及更高级的模板匹配变体(Google搜索将带来最多的收获)。
您可能需要研究不变于缩放和旋转的特征检测 。
同样,如果您可以贴上徽标图片和搜索图片来帮助您,则可能有一个简单的选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.