OpenCV HoughCircles没有检测到圆圈

时间:2016-11-09 19:08:24

标签: java opencv geometry detection hough-transform

我正在实现一个功能,以便检测图像中的圆圈。我正在使用OpenCV来识别Java。灰度图像显示圆圈。

这是我的代码:

Mat gray = new Mat();
Imgproc.cvtColor(img, gray, Imgproc.COLOR_BGR2GRAY);
Imgproc.blur(gray, gray, new Size(3, 3));

Mat edges = new Mat();
int lowThreshold = 100;
int ratio = 3;
Imgproc.Canny(gray, edges, lowThreshold, lowThreshold * ratio);

Mat circles = new Mat();
Vector<Mat> circlesList = new Vector<Mat>();

Imgproc.HoughCircles(edges, circles, Imgproc.CV_HOUGH_GRADIENT, 1, 60, 200, 20, 30, 0);

Imshow grayIM = new Imshow("grayscale");
grayIM.showImage(edges);

知道为什么会这样吗?

1 个答案:

答案 0 :(得分:1)

首先,由于Miki指出HughCircles应该直接应用于灰度,它有一个内部的Canny Edge探测器。

其次,HughCircles的参数应该调整到您特定类型的图像。没有一个设置符合所有公式。

根据您的代码,这对我在某些生成的圈子中起作用:

public static void main(String[] args) {
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    Mat img = Highgui.imread("circle-in.jpg", Highgui.CV_LOAD_IMAGE_ANYCOLOR);

    Mat gray = new Mat();
    Imgproc.cvtColor(img, gray, Imgproc.COLOR_BGR2GRAY);
    Imgproc.blur(gray, gray, new Size(3, 3));

    Mat circles = new Mat();
    double minDist = 60;
    // higher threshold of Canny Edge detector, lower threshold is twice smaller
    double p1UpperThreshold = 200;
    // the smaller it is, the more false circles may be detected
    double p2AccumulatorThreshold = 20;
    int minRadius = 30;
    int maxRadius = 0;
    // use gray image, not edge detected
    Imgproc.HoughCircles(gray, circles, Imgproc.CV_HOUGH_GRADIENT, 1, minDist, p1UpperThreshold, p2AccumulatorThreshold, minRadius, maxRadius);

    // draw the detected circles
    Mat detected = img.clone();
    for (int x = 0; x < circles.cols(); x++) {
        double[] c1xyr = circles.get(0, x);
        Point xy = new Point(Math.round(c1xyr[0]), Math.round(c1xyr[1]));
        int radius = (int) Math.round(c1xyr[2]);
        Core.circle(detected, xy, radius, new Scalar(0, 0, 255), 3);
    }

    Highgui.imwrite("circle-out.jpg", detected);
}

用圆圈输入图片:

Input image with circles

检测到的圆圈为红色:

Detected circles are colored red

请注意,在输出图像中,未检测到左侧的白色圆圈非常接近白色。如果您设置p1UpperThreshold=20