使用 OpenCV 检测简单的几何形状 [Java]

Detecting simple geometric shapes using OpenCV [Java]

我正在编写一个 Java 应用程序来检测简单的几何形状。

以下Python代码作为参考:How to detect simple geometric shapes using OpenCV

这是部分代码 [Python]:

contours,h = cv2.findContours(thresholdedImage,1,2)

for cnt in contours:
    approx = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
    print len(approx)
    if len(approx)==5:
        print "pentagon"
        cv2.drawContours(img,[cnt],0,255,-1)
    elif len(approx)==3:
        print "triangle"
        cv2.drawContours(img,[cnt],0,(0,255,0),-1)
    elif len(approx)==4:
        print "square"
        cv2.drawContours(img,[cnt],0,(0,0,255),-1)
    elif len(approx) == 9:
        print "half-circle"
        cv2.drawContours(img,[cnt],0,(255,255,0),-1)
    elif len(approx) > 15:
        print "circle"
        cv2.drawContours(img,[cnt],0,(0,255,255),-1)

使用 Java 的 OpenCV 方法,我无法提取 "len"(长度)属性(以便确定检测到什么形状)的近似轮廓。

打印出几个等高线会产生 [Java]:

[ 4*1*CV_32SC2, isCont=true, isSubmat=false, nativeObj=0x23ac75f0, dataAddr=0x1c7c66c0 ]
[ 5*1*CV_32SC2, isCont=true, isSubmat=false, nativeObj=0x23ac7200, dataAddr=0x1c0e5fc0 ]
etc.

我想获取特定轮廓对象的点数 -- 来自上面代码的 45

我知道我可以将其转换为字符串然后提取数字,但一定有更好的方法,对吧?

感谢您的回复。

这应该可以解决问题。 (假设您已经 yourImage 存储在 MatOfPoint2f 对象中)。

MatOfPoint2f approx = new MatOfPoint2f();
Imgproc.approxPolyDP(yourImage, approx, Imgproc.arcLength(yourImage, true) * 0.02, true);
long count = approx.total();
if (count == 5) { 
    // this is a pentagon
}

检查this以查看total()

的使用

与 Python 或 C++ 等其他语言相比,Java 上的 OpenCV 变得有点棘手。