我是 OpenCV 的新手,我一直在看教程和这里的问题,但我无法理解和设置模板匹配的阈值。
这是我目前使用的代码。 选择图片时触发的函数
BitmapDrawable drawable = (BitmapDrawable) imgView.getDrawable();
Bitmap viewBitmap = drawable.getBitmap();
Bitmap bitmapMatch = BitmapFactory.decodeResource(getResources(), R.drawable.template_1);
run(viewBitmap, bitmapMatch, "result.png", Imgproc.TM_CCOEFF_NORMED);
运行函数
public void run(Bitmap inFile, Bitmap templateFile, String outFile, int match_method) {
System.out.println("\nRunning Template Matching");
Mat img = new Mat();
Utils.bitmapToMat(inFile, img);
Mat templ = new Mat();
Utils.bitmapToMat(templateFile, templ);
// / 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());
// / Localizing the best match with minMaxLoc
Core.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;
}
Log.d(TAG, "point: " + mmr.maxVal);
// / Show me what you got
// Core.rectangle(img, matchLoc, new Point(matchLoc.x + templ.cols(),
// matchLoc.y + templ.rows()), new Scalar(255, 255, 255));
// Save the visualized detection.
System.out.println("Writing "+ outFile);
if (match >= 0.8)
SaveImage(img,outFile);
else
Log.d(TAG, "No Match Found");
}
我想在 if 语句 if (match >= 0.8)
中添加一个阈值,以便在匹配等于或超过阈值 (0.8) 时保存图像。否则,图像将不会被保存。
请帮忙,谢谢。
最佳答案
Core.MinMaxLocResult
包含maxLoc
、maxVal
、minLoc
和minVal
值。只需根据上下文分配 match=mmr.maxVal
或 match=mmr.minVal
。
或者,您可以在 result
Mat 中建立索引以获取您的值,然后测试它是否超过 0.8:
double[] resultVal = result.get(matchLoc.y, matchLoc.x);
if (resultVal[0] >= 0.8) ...
关于java - Android - OpenCV 模板与阈值匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47702953/