java - OpenCV HoughCircles 未检测到圆圈

标签 java opencv geometry detection hough-transform

我正在实现一个函数来检测图像中的圆圈。我正在使用 Java 的 OpenCV 来识别圆圈。灰度图像确实显示了一个圆圈。

这是我的代码:

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);

知道为什么会这样吗?

最佳答案

首先,正如 Miki 指出的那样,HughCircles 应该直接应用于灰度,它有自己的内部 Canny 边缘检测器。

其次,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,它将是。

关于java - OpenCV HoughCircles 未检测到圆圈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40514258/

相关文章:

math - 霍夫变换过滤线

reactjs - React-Leaflet 在 map 上绘制圆形标记

iphone - 在iPhone ios 4上显示来自opencv的关键点

java - 如何读取/写入大于200MB的文件

java - SpringBoot 2 - 监控数据库连接

java - 如何将spannablestring添加到android中的列表中?

python - 如何将第一帧与视频opencv python的其他帧进行比较

c++ - 用于运动检测的opencv代码中的错误

math - 计算点到线段和线段到线段的平均距离

java - 如何使用 Spring 的 RestTemplate 来 POST 一个字符串数组