2017-09-21 270 views
0

我在编写检测简单几何形状的Java应用程序。使用OpenCV检测简单的几何形状[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

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

感谢您的回复。

+0

请注意'len'只是获得'approx'数组中元素的数量。它不计算点/线或任何东西的“长度”。它就像Java中的'.length'。所以它只是说“如果三个点是三角形,五个是五角形”等等。 –

回答

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看到Java的使用total()

的OpenCV变得有点棘手与像Python或C++等语言相比较。

+0

谢谢,这解决了这个问题。 – user2426320