我会尝试从一张非常清晰的图像中检测一个圆形。我知道部分圆形的形状可能会失真,但是根据我对霍夫变换的了解,这不应该导致我遇到的问题。
输入:
输出:
代码:
输入:
![Output image](https://istack.dev59.com/yLwG4.webp)
![enter image description here](https://istack.dev59.com/Nbg6U.webp)
// Read the image
Mat src = Highgui.imread("input.png");
// Convert it to gray
Mat src_gray = new Mat();
Imgproc.cvtColor(src, src_gray, Imgproc.COLOR_BGR2GRAY);
// Reduce the noise so we avoid false circle detection
//Imgproc.GaussianBlur( src_gray, src_gray, new Size(9, 9), 2, 2 );
Mat circles = new Mat();
/// Apply the Hough Transform to find the circles
Imgproc.HoughCircles(src_gray, circles, Imgproc.CV_HOUGH_GRADIENT, 1, 1, 160, 25, 0, 0);
// Draw the circles detected
for( int i = 0; i < circles.cols(); i++ ) {
double[] vCircle = circles.get(0, i);
Point center = new Point(vCircle[0], vCircle[1]);
int radius = (int) Math.round(vCircle[2]);
// circle center
Core.circle(src, center, 3, new Scalar(0, 255, 0), -1, 8, 0);
// circle outline
Core.circle(src, center, radius, new Scalar(0, 0, 255), 3, 8, 0);
}
// Save the visualized detection.
String filename = "output.png";
System.out.println(String.format("Writing %s", filename));
Highgui.imwrite(filename, src);
我将高斯模糊注释掉了,因为(直觉上)它会大大增加找到的同样不准确的圆的数量。
我的输入图像有什么问题会导致霍夫变换的效果不如我预期吗?我的参数是否严重偏离?
编辑:第一个答案提出了关于Hough最小/最大半径的提示。我抵制添加这些参数,因为本帖子中的示例图像只是成千上万个具有不同半径的图像之一,范围从约20到无限大。
Imgproc.HoughCircles
内部使用了梯度过滤器,并且不假定输入是线数据。因此,在梯度计算之后,您的某些线条可能会消失或重复出现。 - Micka