我正在尝试仅使用一个模板匹配多个对象。 但问题是我的程序在输入图像中匹配evrey对象的多次出现。 如何在输入图像中只匹配多个对象和evrey对象?
这是我的代码
public void run(String inFile, String templateFile, String outFile, int match_method) {
System.out.println("\nRunning Template Matching");
Mat img = Imgcodecs.imread(inFile);
Mat templ = Imgcodecs.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());
while(true)
{
// / 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;
}
if(mmr.maxVal >=0.97)
{
// / Show me what you got
Imgproc.rectangle(img, matchLoc,
new Point(matchLoc.x + templ.cols(),matchLoc.y + templ.rows()),
new Scalar(0,255,0),2);
//Imgproc.putText(img, "Edited by me",
// new Point(matchLoc.x + templ.cols(),matchLoc.y + templ.rows()),
//Core.FONT_HERSHEY_PLAIN, 1.0 ,new Scalar(0,255,255));
Imgproc.rectangle(result, matchLoc,
new Point(matchLoc.x + templ.cols(),matchLoc.y + templ.rows()),
new Scalar(0,255,0),-1);
}
else
{
break; //No more results within tolerance, break search
}
}
// / Show me what you got
//Imgproc.rectangle(img, matchLoc, new Point(matchLoc.x + templ.cols(),
//matchLoc.y + templ.rows()), new Scalar(0, 255, 0),2);
// Save the visualized detection.
System.out.println("Writing "+ outFile);
Imgcodecs.imwrite(outFile, img);
}
public static void main(String[] args) {
System.loadLibrary("opencv_java310");
run("test.jpg", "temp.png", "output.png", Imgproc.TM_CCOEFF_NORMED);
}
test.jpg放在