Template matching is a technique for finding the most matching (similar) part of one image to another.
Function: Imgproc.matchTemplate(Mat image, Mat templ, Mat result, int method)
Parameter description:
image: source image
templ: template image
result: Compare the results
method: Matching algorithm
Matching algorithm:
TM_SQDIFF squared difference matching method: This method uses squared difference to match; the best match value is 0; the worse the match, the larger the match value.
TM_CCORR Correlation Matching Method: This method uses multiplication operation; the larger the value, the better the matching degree.
TM_CCOEFF correlation coefficient matching method: 1 represents a perfect match; -1 represents the worst match.
TM_SQDIFF_NORMED Normalized square difference matching method.
TM_CCORR_NORMED Normalized correlation matching method.
TM_CCOEFF_NORMED Normalized correlation coefficient matching method.
Sample code:
public static void main(String[] args) { // TODO Auto-generated method stub System.loadLibrary(Core.NATIVE_LIBRARY_NAME); Mat g_tem = Imgcodecs.imread("F://mould.jpg"); Mat g_src = Imgcodecs.imread("F://source.jpg"); int result_rows = g_src.rows() - g_tem.rows() + 1; int result_cols = g_src.cols() - g_tem.cols() + 1; Mat g_result = new Mat(result_rows, result_cols, CvType.CV_32FC1); Imgproc.matchTemplate(g_src, g_tem, g_result, Imgproc.TM_CCORR_NORMED); // Normalized square variance matching method// Imgproc.matchTemplate(g_src, g_tem, g_result, // Imgproc.TM_CCOEFF_NORMED); // Normalized correlation coefficient matching method// Imgproc.matchTemplate(g_src, g_tem, g_result, Imgproc.TM_CCOEFF); // // // // Correlation coefficient matching method: 1 represents a perfect match; -1 represents the worst match. // Imgproc.matchTemplate(g_src, g_tem, g_result, Imgproc.TM_CCORR); // // Related matching method// Imgproc.matchTemplate(g_src, g_tem, g_result, Imgproc.TM_SQDIFF); // // Square variance matching method: This method uses square variance to match; the best match value is 0; the worse the match, the larger the match value. // Imgproc.matchTemplate(g_src, g_tem,g_result,Imgproc.TM_CCORR_NORMED); // // Normalized correlation matching method Core.normalize(g_result, g_result, 0, 1, Core.NORM_MINMAX, -1, new Mat()); Point matchLocation = new Point(); MinMaxLocResult mmmlr = Core.minMaxLoc(g_result); matchLocation = mmmlr.maxLoc; // Whether to use maxLoc here depends on the matching algorithm used Imgproc.rectangle(g_src, matchLocation, new Point(matchLocation.x + g_tem.cols(), matchLocation.y + g_tem.rows()), new Scalar(0, 0, 0, 0)); Imgcodecs.imwrite("F://match.jpg", g_src); } Source image:
Template Image:
Match result:
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.