使用OpenCV检测简单的几何形状[Java] [英] Detecting simple geometric shapes using OpenCV [Java]

查看:512
本文介绍了使用OpenCV检测简单的几何形状[Java]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm programming a Java application that detects simple geometric shapes.

以下Python代码用作参考:如何使用OpenCV检测简单的几何形状

The following Python code is used as a reference: How to detect simple geometric shapes using OpenCV

这是[Python]的一些代码:

This is some of the code [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"(长度)属性(以便确定已检测到的形状).

Using Java's OpenCV methods, I'm unable to extract the "len" (length) property (in order to determine what shape has been detected) of an approximated contour.

打印出两个轮廓会产生[Java]:

Printing out a couple of contours produces [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.

I'd like to get the number of points of a specific contour object -- the 4 and 5 from the code above.

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

I know I could convert it to a String and then extract the numbers, but there must be a better way, right?

感谢您的答复.

推荐答案

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

This should do the trick. (Assuming you already have yourImagestored in a MatOfPoint2fobject).

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
}

检查查看total()

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

OpenCV on Java becomes a bit tricky compared with other languages like Python or C++.

这篇关于使用OpenCV检测简单的几何形状[Java]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆