我正在尝试使用 OpenCV (java) 进行模板匹配,并使用最大最小值来确定是否找到对象。
我正在使用以下 java/opencv 代码,但问题是它为最佳匹配以及未找到匹配的场景的最小值返回 0.0。
所以这个模板匹配对于判断对象是否找到似乎是不可靠的。我在这段代码中做错了什么,还是我需要寻求任何其他技术?
提前致谢。
int templateMatchMethod = Imgproc.TM_SQDIFF_NORMED;
Mat largeImage = Highgui.imread(largeUrl);
Mat smallImage = Highgui.imread(smallUrl);
boolean isMaxTypleMethod = true;
double TEMPLATE_MATCH_THRESHOLD = 0.8;
int result_cols = largeImage.cols() - smallImage.cols() + 1;
int result_rows = largeImage.rows() - smallImage.rows() + 1;
Mat result = new Mat(result_rows, result_cols, CvType.CV_8U);
Imgproc.matchTemplate(largeImage, smallImage, result, templateMatchMethod);
Core.normalize(result, result, 0, 1, Core.NORM_MINMAX, -1, new Mat());
MinMaxLocResult mmr = Core.minMaxLoc(result);
Point matchLoc;
double minMaxValue = 1;
if (templateMatchMethod == Imgproc.TM_SQDIFF || templateMatchMethod == Imgproc.TM_SQDIFF_NORMED)
{
matchLoc = mmr.minLoc;
isMaxTypleMethod = false;
TEMPLATE_MATCH_THRESHOLD = 0.4;
minMaxValue = mmr.minVal;
}
else
{
matchLoc = mmr.maxLoc;
minMaxValue = mmr.maxVal;
}
Core.rectangle(largeImage, matchLoc, new Point(matchLoc.x + smallImage.cols(),
matchLoc.y + smallImage.rows()), new Scalar(0, 255, 0));
System.out.println("minMaxValue : "+minMaxValue);
if(isMaxTypleMethod && TEMPLATE_MATCH_THRESHOLD < minMaxValue)
{
System.out.println("Match found");
}
else if (!isMaxTypleMethod && TEMPLATE_MATCH_THRESHOLD > minMaxValue)
{
System.out.println("Match found");
}
最佳答案
这看起来很可疑:
Mat result = new Mat(result_rows, result_cols, CvType.CV_8U); // better use CvType.CV_32F here
Imgproc.matchTemplate(largeImage, smallImage, result, templateMatchMethod);
Core.normalize(result, result, 0, 1, Core.NORM_MINMAX, -1, new Mat()); // normalizing a uchar mat into [0..1] can only result in garbage.
同样,如果您使用浮点类型作为结果并跳过规范化,它会工作得更好
关于OpenCV 模板匹配最大最小值返回错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17894753/