因為有這方面的需要所以,對模板查找搜尋了相關資料,只是對於算法的東西很難看得動,特別是opencv涉及的很多的數學方法。
所以只為了實現這個功能,因為需求比較簡單,在網上也搜尋到了相關代碼,就直接拿來用了,這里也相當於轉載一下:
代碼上,親測可以用的,效果也不錯,確實將嘴巴給找出來了。
原文:http://www.itstrike.cn/Question/645ffff0-2862-46b6-a421-b76a37dfc660.html
class MatchingDemo {
public void run(String inFile, String templateFile, String outFile, int match_method) {
System.out.println("\nRunning 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());
// / 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;
}
// / Show me what you got
Core.rectangle(img, matchLoc, new Point(matchLoc.x + templ.cols(),
matchLoc.y + templ.rows()), new Scalar(0, 255, 0));
// Save the visualized detection.
System.out.println("Writing "+ outFile);
Highgui.imwrite(outFile, img);
}
}
public class TemplateMatching {
public static void main(String[] args) {
System.loadLibrary("opencv_java246");
new MatchingDemo().run(args[0], args[1], args[2], Imgproc.TM_CCOEFF);
}
}
目標圖像:

模板圖像:

查找后圖像:

