OpenCV 4.5.0 Android Java环境下获取轮廓点数量的方法咨询
OpenCV 4.5.0 Java 版获取单轮廓点数量的正确方式
问题根源
Java端的MatOfPoint和C++端vector<Point>的定位一致,但它本质是继承自Mat的矩阵容器,不是原生Java集合:
- 你之前调用的
contours.get(i).size()是从父类Mat继承来的方法,返回的是矩阵本身的尺寸Size对象,根本不是点的计数,和C++里vector的size()语义完全不对应 - 对存储轮廓的
MatOfPoint来说,每个轮廓点会占矩阵的1行,矩阵列数固定为1,因此直接调用rows()方法返回的整数,就是当前轮廓包含的总点数量,完全等价于C++版里contours[i].size()的效果
修正后的迁移代码
对照你原来的C++逻辑,Java端的完整可运行实现如下:
// 注意contours必须初始化空集合,不能赋值为null,否则findContours会抛空指针 List<MatOfPoint> contours = new ArrayList<>(); Mat hierarchy = new Mat(); Imgproc.findContours(grayImage, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE); // 等价于C++版找点数最多的轮廓的逻辑 int maxPointCount = 0; int targetContourIndex = -1; for (int i = 0; i < contours.size(); i++) { // 用rows()取当前轮廓的总点数 int currentCount = contours.get(i).rows(); if (currentCount > maxPointCount) { maxPointCount = currentCount; targetContourIndex = i; } } // 等价于C++版遍历轮廓找四个极值角点的逻辑 MatOfPoint targetContour = contours.get(targetContourIndex); Point[] contourPoints = targetContour.toArray(); Point ul = contourPoints[0]; Point ur = contourPoints[0]; Point lr = contourPoints[0]; Point ll = contourPoints[0]; for (int i = 1; i < contourPoints.length; i++) { Point p = contourPoints[i]; // 对应原C++的四个极值判断逻辑 if ((p.x + p.y) < (ul.x + ul.y)) ul = p; if ((p.x + p.y) > (lr.x + lr.y)) lr = p; if ((p.x - p.y) > (ur.x - ur.y)) ur = p; if ((p.x - p.y) < (ll.x - ll.y)) ll = p; }
补充说明
- 如果非要用
size()的返回值计算,MatOfPoint的size().height也等于点数量,但rows()的语义更直白,迁移代码的时候不容易出现语义偏差 - 调用
toArray()可以直接拿到Java侧的Point数组,不需要手动解析Mat的像素数据,和C++里直接按下标遍历轮廓点的体验完全一致
内容的提问来源于stack exchange,提问作者user1807717
相关产品推荐
相关产品推荐

