我是OpenCV的新手,我想从事对象检测以帮助我的FRC机器人团队。我正在尝试使用HSV滤镜和HoughCircles在网络摄像头图像中查找网球并在其周围绘制一个圆圈。这是我的代码:

Mat currentFrame = new Mat();
Mat hsv = new Mat();
Mat threshImage = new Mat();
Mat circles = new Mat();

while (true) {
    camera.read(currentFrame);

    Imgproc.resize(currentFrame, currentFrame, new Size(WIDTH, HEIGHT));
    Imgproc.cvtColor(currentFrame, hsv, Imgproc.COLOR_RGB2HSV);

    hsvWindow.showImage(hsv);

    Core.inRange(hsv, new Scalar(50, 100, 0), new Scalar(95, 255, 255), threshImage);

    threshWindow.showImage(threshImage);

    Imgproc.HoughCircles(threshImage, circles, Imgproc.CV_HOUGH_GRADIENT, 2, 100, 100, 100, 0, 500);
    for (int i = 0; i < circles.cols(); i++) {
        double[] vCircle = circles.get(0, i);

        Point pt = new Point(Math.round(vCircle[0]), Math.round(vCircle[1]));
        int radius = (int)Math.round(vCircle[2]);

        Core.circle(currentFrame, pt, radius, new Scalar(255, 0, 0), 2);
    }

    drawWindow.showImage(currentFrame);
}

原始图像,hsv图像和过滤后的图像在此相册中:http://imgur.com/a/hO8vs

当我在此处使用参数运行HoughCircles时,它会在钢琴凳和玩具兔子上找到圆,但找不到网球,圆是一个大的白色圆圈。

最佳答案

我修好了它!经过对HoughCircles的参数进行一些摆弄,并对二进制图像进行模糊处理和阈值处理后,可以找到可靠的二进制图像,但是该圆圈抖动且不一致。因此,我用findContours替换了HoughCircles,在轮廓中循环寻找最大的轮廓,并使用minEnclosingCircle。现在是下面的代码:

Mat currentFrame = new Mat(), hsv = new Mat(), threshImage = new Mat();
List<MatOfPoint> contours = new ArrayList<MatOfPoint>();

while (true) {
    camera.read(currentFrame);

    Imgproc.resize(currentFrame, currentFrame, new Size(WIDTH, HEIGHT));
    Imgproc.cvtColor(currentFrame, hsv, Imgproc.COLOR_RGB2HSV);

    hsvWindow.showImage(hsv);

    Core.inRange(hsv, new Scalar(50, 100, 50), new Scalar(95, 255, 255), threshImage);
    Imgproc.blur(threshImage, threshImage, new Size(10, 10));
    Imgproc.threshold(threshImage, threshImage, 150, 255, Imgproc.THRESH_BINARY);

    threshWindow.showImage(threshImage);

    Imgproc.findContours(threshImage, contours, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
    double maxArea = 0;
    float[] radius = new float[1];
    Point center = new Point();
    for (int i = 0; i < contours.size(); i++) {
        MatOfPoint c = contours.get(i);
        if (Imgproc.contourArea(c) > maxArea) {
            MatOfPoint2f c2f = new MatOfPoint2f(c.toArray());
            Imgproc.minEnclosingCircle(c2f, center, radius);
        }
    }
    Core.circle(currentFrame, center, (int)radius[0], new Scalar(255, 0, 0), 2);

    drawWindow.showImage(currentFrame);
}

我知道这可能对希望专门使用HoughCircles的人没有特别帮助,但这证明了模糊二进制图像的力量。如果要在许多事物中寻找一个圆,则需要寻找轮廓并将轮廓区域与其封闭的圆形区域进行比较。

10-04 20:42