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

时间:2017-09-21 09:44:12

标签: java python opencv computer-vision opencv3.1

我正在编写一个检测简单几何形状的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

我知道我可以将它转换为字符串,然后提取数字,但必须有更好的方法,对吗?

感谢您的回复。

1 个答案:

答案 0 :(得分:1)

这应该可以解决问题。 (假设您已将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 ++等其他语言相比,OpenCV on Java变得有点棘手。

相关问题