用java写opencv模板匹配,并返回匹配图片所在的位置坐标
时间: 2024-04-12 09:31:58 浏览: 120
当然可以!下面是一个用Java写的OpenCV模板匹配的示例代码:
```java
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfFloat;
import org.opencv.core.MatOfInt;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.core.CvType;
import org.opencv.core.CvType.CV_32F;
import org.opencv.core.CvType.CV_8UC1;
import org.opencv.core.CvType.CV_8U;
import org.opencv.core.MatOfPoint;
import org.opencv.core.MatOfPoint2f;
import org.opencv.core.RotatedRect;
import org.opencv.core.TermCriteria;
import org.opencv.core.CvType;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class TemplateMatchingExample {
public static void main(String[] args) {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
// 读取源图像和模板图像
Mat sourceImage = Imgcodecs.imread("source_image.jpg", Imgcodecs.IMREAD_COLOR);
Mat templateImage = Imgcodecs.imread("template_image.jpg", Imgcodecs.IMREAD_COLOR);
// 创建结果矩阵,用于存储模板匹配结果
int resultWidth = sourceImage.cols() - templateImage.cols() + 1;
int resultHeight = sourceImage.rows() - templateImage.rows() + 1;
Mat result = new Mat(resultHeight, resultWidth, CvType.CV_32FC1);
// 进行模板匹配
Imgproc.matchTemplate(sourceImage, templateImage, result, Imgproc.TM_CCOEFF);
// 标记匹配结果
Core.normalize(result, result, 0, 1, Core.NORM_MINMAX, -1, new Mat());
Core.MinMaxLocResult minMaxLocResult = Core.minMaxLoc(result);
Point matchLoc = minMaxLocResult.maxLoc;
// 绘制匹配结果矩形框
Rect matchRect = new Rect(matchLoc, new Size(templateImage.cols(), templateImage.rows()));
Imgproc.rectangle(sourceImage, matchRect.tl(), matchRect.br(), new Scalar(0, 255, 0), 2);
// 显示匹配结果
HighGui.imshow("Source Image", sourceImage);
HighGui.waitKey();
// 输出匹配结果的位置坐标
System.out.println("匹配结果位置:(" + matchLoc.x + ", " + matchLoc.y + ")");
}
}
```
请确保你已经安装了OpenCV库,并将源图像和模板图像替换为你的实际图像路径。这段代码将显示源图像,并在找到的匹配位置绘制矩形框,并输出匹配结果的位置坐标。
希望对你有帮助!如果你有任何问题,请随时问我!
阅读全文