检测圆形,矩形和三角形,并使用opencv通过相机在Android中进行计数

时间:2014-09-14 15:56:52

标签: java android c++ opencv image-processing

我想用Android中的OpenCv从图像中检测圆形,矩形和三角形,然后计数。我从C ++教程(本网站http://opencv-code.com/tutorials/detecting-simple-shapes-in-an-image)转换了代码。问题是它不能计算任何圆和矩形(结果为0),但可以检测三角形(不完全是全部)。如果我错了,请检查我的代码并纠正我。这是我的代码

int circle = 0;
    int rec = 0;
    int tri = 0;
    int totalCircle = 0;
    int totalRec = 0;
    int totalTri = 0;
    Mat gray = new Mat();
    Mat imgSource = new Mat();
    Mat bw = new Mat();
    Utils.bitmapToMat(bmpOriginal , imgSource);
    //Imgproc.resize(imgSource, imgSource,new Size(310,175));
    Imgproc.cvtColor(imgSource, gray, Imgproc.COLOR_BGR2GRAY);
    Imgproc.Canny(gray, bw,  0, 50, 5,true);
    List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
    Imgproc.findContours(bw.clone(), contours,bw.clone(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
    MatOfPoint2f approx =  new MatOfPoint2f();
    Mat dst = imgSource.clone();

    for (int i = 0; i < contours.size(); i++){
        MatOfPoint tempContour=contours.get(i);
        MatOfPoint2f newMat = new MatOfPoint2f( tempContour.toArray() );
        int contourSize = (int)tempContour.total();
        Imgproc.approxPolyDP(newMat, approx, contourSize*0.02, true);
        MatOfPoint points=new MatOfPoint(approx.toArray());
        if((Math.abs(Imgproc.contourArea(tempContour))<100) || !Imgproc.isContourConvex(points)){
            Log.i(TAG, "::onCameraFrame:" + " too small");
            continue;
        }
        if(approx.toArray().length == 3){
            tri++;
        }
        else if(approx.toArray().length >= 4 && approx.toArray().length <= 6){
            int vtc = points.toArray().length;
            Vector<Double> cosList = new Vector<Double>();
            for (int j = 2; j < vtc+1; j++){
                cosList.add(angle(points.toArray()[j%vtc], points.toArray()[j-2], points.toArray()[j-1]));

            }   

            double mincos = Collections.min(cosList);
            double maxcos = Collections.max(cosList);
            if (vtc == 4 && mincos >= -0.1 && maxcos <= 0.3)
            {
                rec++;
            }

        }
        else{

            double area = Imgproc.contourArea(newMat);
            Rect r = Imgproc.boundingRect(contours.get(i));
            int radius = r.width/2;
            if((Math.abs((1 - ((double)r.width / r.height)) )<= 0.2) && 
                    Math.abs(area / (Math.PI * Math.pow(radius, 2)))<=0){
            }
            circle++;

        }
        totalCircle = circle;
        totalRec = rec;
        totalTri = tri;

这是我的图片测试Click this

谢谢;)

0 个答案:

没有答案