0
点赞
收藏
分享

微信扫一扫

java opecv 如何寻找矩形

颜路在路上 2024-05-16 阅读 13

寻找矩形的方法

在Java中使用OpenCV库可以实现矩形的查找,通过OpenCV提供的函数和方法来处理图像,检测其中的矩形区域。下面将介绍如何使用Java和OpenCV来寻找矩形。

步骤一:导入OpenCV库

首先,需要在项目中导入OpenCV库,可以通过Maven或手动导入方式添加以下依赖:

<dependency>
    <groupId>org.openpnp</groupId>
    <artifactId>opencv</artifactId>
    <version>4.5.3-1</version>
</dependency>

步骤二:加载图像并进行处理

在Java中使用OpenCV,首先需要加载图像并进行处理。可以使用以下代码加载图像:

Mat image = Imgcodecs.imread("path/to/image.jpg");

步骤三:灰度化和边缘检测

接下来,将加载的彩色图像转换为灰度图像,并进行边缘检测,可以使用以下代码:

Mat grayImage = new Mat();
Imgproc.cvtColor(image, grayImage, Imgproc.COLOR_BGR2GRAY);

Mat edges = new Mat();
Imgproc.Canny(grayImage, edges, 100, 200);

步骤四:寻找轮廓

使用边缘检测后的图像找到轮廓,可以使用以下代码:

List<MatOfPoint> contours = new ArrayList<>();
Imgproc.findContours(edges, contours, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);

步骤五:筛选矩形

遍历找到的轮廓,筛选出矩形的轮廓,可以使用以下代码:

List<MatOfPoint> rectangles = new ArrayList<>();
for (MatOfPoint contour : contours) {
    MatOfPoint2f curve = new MatOfPoint2f(contour.toArray());
    double epsilon = 0.02 * Imgproc.arcLength(curve, true);
    MatOfPoint2f approx = new MatOfPoint2f();
    Imgproc.approxPolyDP(curve, approx, epsilon, true);
    
    if (approx.rows() == 4) {
        rectangles.add(contour);
    }
}

步骤六:绘制矩形

最后,可以将找到的矩形绘制到原始图像上,可以使用以下代码:

for (MatOfPoint rectangle : rectangles) {
    Rect rect = Imgproc.boundingRect(rectangle);
    Imgproc.rectangle(image, rect.tl(), rect.br(), new Scalar(0, 255, 0), 2);
}

完整代码示例

下面是整个过程的完整代码示例:

Mat image = Imgcodecs.imread("path/to/image.jpg");

Mat grayImage = new Mat();
Imgproc.cvtColor(image, grayImage, Imgproc.COLOR_BGR2GRAY);

Mat edges = new Mat();
Imgproc.Canny(grayImage, edges, 100, 200);

List<MatOfPoint> contours = new ArrayList<>();
Imgproc.findContours(edges, contours, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);

List<MatOfPoint> rectangles = new ArrayList<>();
for (MatOfPoint contour : contours) {
    MatOfPoint2f curve = new MatOfPoint2f(contour.toArray());
    double epsilon = 0.02 * Imgproc.arcLength(curve, true);
    MatOfPoint2f approx = new MatOfPoint2f();
    Imgproc.approxPolyDP(curve, approx, epsilon, true);
    
    if (approx.rows() == 4) {
        rectangles.add(contour);
    }
}

for (MatOfPoint rectangle : rectangles) {
    Rect rect = Imgproc.boundingRect(rectangle);
    Imgproc.rectangle(image, rect.tl(), rect.br(), new Scalar(0, 255, 0), 2);
}

Imgcodecs.imwrite("path/to/output.jpg", image);

通过以上步骤,可以使用Java和OpenCV库来寻找矩形并将其绘制在图像上。希望对你有所帮助!

举报

相关推荐

0 条评论