java opencv 模板匹配
时间: 2023-07-07 19:40:13 浏览: 44
Java OpenCV中的模板匹配可以使用`TemplateMatching`类来实现。以下是一个简单的示例代码:
```java
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.core.Core.MinMaxLocResult;
public class TemplateMatchingExample {
public static void main(String[] args) {
// Load the input image and template
Mat img = Imgcodecs.imread("input.jpg");
Mat templ = Imgcodecs.imread("template.jpg");
// Create the result matrix
Mat result = new Mat();
int result_cols = img.cols() - templ.cols() + 1;
int result_rows = img.rows() - templ.rows() + 1;
result.create(result_rows, result_cols, CvType.CV_32FC1);
// Perform template matching
Imgproc.matchTemplate(img, templ, result, Imgproc.TM_CCOEFF_NORMED);
// Find the minimum and maximum values and their locations
MinMaxLocResult mmr = Core.minMaxLoc(result);
Point maxLoc = mmr.maxLoc;
// Draw a rectangle around the matched area
Imgproc.rectangle(img, maxLoc, new Point(maxLoc.x + templ.cols(), maxLoc.y + templ.rows()), new Scalar(0, 0, 255), 2);
// Save the output image
Imgcodecs.imwrite("output.jpg", img);
}
}
```
在这个示例中,我们首先加载输入图像和模板,然后创建一个用于存储匹配结果的矩阵。我们使用`Imgproc.matchTemplate`函数对输入图像和模板进行匹配,并将结果存储在结果矩阵中。然后,我们使用`Core.minMaxLoc`函数查找结果矩阵中的最小值和最大值及其位置。最后,我们在输入图像中绘制一个矩形框来标记匹配的区域,并将输出图像保存到磁盘上。