OpenCV特征检测(8)检测图像中圆形的函数HoughCircles的使用-算法描述

时间:2024-09-29 21:31:41

在灰度图像中使用霍夫变换查找圆形。

该函数使用霍夫变换的一种修改版本在灰度图像中查找圆形。
例子:

#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <math.h>
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
    Mat img, gray;
    if( argc != 2 || !(img=imread(argv[1], IMREAD_COLOR)).data)
        return -1;
    cvtColor(img, gray, COLOR_BGR2GRAY);
    // smooth it, otherwise a lot of false circles may be detected
    GaussianBlur( gray, gray, Size(9, 9), 2, 2 );
    vector<Vec3f> circles;
    HoughCircles(gray, circles, HOUGH_GRADIENT,
                 2, gray.rows/4, 200, 100 );
    for( size_t i = 0; i < circles.size(); i++ )
    {
         Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
         int radius = cvRound(circles[i][2]);
         // draw the circle center
         circle( img, center, 3, Scalar(0,255,0), -1, 8, 0 );
         // draw the circle outline
         circle( img, center, radius, Scalar(0,0,255), 3, 8, 0 );
    }
    namedWindow( "circles", 1 );
    imshow( "circles", img );
    waitKey(0);
    return 0;
}

注意:

通常该函数能够很好地检测圆形的中心。然而,它可能无法正确找到半径。如果你知道半径范围,可以通过指定 minRadius 和 maxRadius 来帮助函数。或者,在使用 HOUGH_GRADIENT 方法的情况下,你可以将 maxRadius 设置为一个负数,以仅返回中心而不进行半径搜索,并使用额外的过程来找到正确的半径。
对图像进行轻微的平滑处理也有帮助,除非图像本身已经很平滑。例如,使用大小为 7x7 的高斯核和 1.5x1.5 的 sigma 进行 GaussianBlur() 或类似的模糊处理可能会有帮助。

HoughCircles 是 OpenCV 中用于检测图像中圆形的一个函数。Hough 变换是一种用于检测图像中特定形状的技术,尤其是直线和圆形。HoughCircles 实现了 Hough 变换的一个变种,专门用于检测圆形。