毕设之Opencv批量霍夫圆检测

 毕设之Opencv批量霍夫圆检测

程序思路:编写read_csv()函数读取图片目录下txt文档,获取各BMP文件绝对路径以及对应圆的圆心坐标、半径参数。读取各BMP图像,转为灰度图,进行图像平滑,最后霍夫圆检测;并将检测结果和实际结果存入txt文档。

本程序高斯平滑和霍夫圆变换都需要调参。

功能小结:

1、read_csv()函数

void read_csv(string&csvPath, vector<String>&CirclePath, vector<int>&Circle_x, vector<int>&Circle_y, vector<int>&Circle_r)

csvPath:txt路径

CirclePath:从txt中读取的bmp路径

Circle_x:bmp图像中圆的圆心x坐标

Circle_y:bmp图像中圆的圆心y坐标

Circle_r:bmp图像中圆的半径r

2、创建txt文本,并写入数据

#include <iostream>
#include <sstream>
#include <fstream>
ofstream file("filepath",ios::out);
if (file.is_open())
{
    file <<;
}
file.close();

3、转化为灰度图

cvtColor(srcImage,midImage, COLOR_BGR2GRAY);

//转化边缘检测后的图为灰度图

@paramsrc input image: 8-bit unsigned, 16-bit unsigned ( CV_16UC... ), orsingle-precision

floating-point.

@paramdst output image of the same size and depth as src.

@paramcode color space conversion code (see cv::ColorConversionCodes).

@paramdstCn number of channels in the destination image; if the parameter is 0, thenumber of the

channelsis derived automatically from src and code.

3、高斯平滑

GaussianBlur(midImage,midImage, Size(9, 9), 2, 2);

感悟:ksize、 sigmaX、sigmaY取值大小会影响平滑效果,对霍夫圆检测有较大的影响。

CV_EXPORTS_W void GaussianBlur( InputArray src,OutputArray dst, Size ksize,

                                double sigmaX,double sigmaY = 0,

                                int borderType =BORDER_DEFAULT );

/**@brief Blurs an image using a Gaussian filter.

 

Thefunction convolves the source image with the specified Gaussian kernel.In-place filtering is

supported.

 

@paramsrc input image; the image can have any number of channels, which are processed

independently,but the depth should be CV_8U, CV_16U, CV_16S, CV_32F or CV_64F.

@paramdst output image of the same size and type as src.

@paramksize Gaussian kernel size. ksize.width and ksize.height can differ but theyboth must be

positiveand odd. Or, they can be zero's and then they are computed from sigma.

@paramsigmaX Gaussian kernel standard deviation in X direction.

@paramsigmaY Gaussian kernel standard deviation in Y direction; if sigmaY is zero, itis set to be

equalto sigmaX, if both sigmas are zeros, they are computed from ksize.width andksize.height,

respectively(see cv::getGaussianKernel for details); to fully control the result regardlessof

possiblefuture modifications of all this semantics, it is recommended to specify all ofksize,

sigmaX,and sigmaY.

@paramborderType pixel extrapolation method, see cv::BorderTypes

 

@sa  sepFilter2D, filter2D, blur, boxFilter,bilateralFilter, medianBlur

 */

4、霍夫圆变化

HoughCircles(midImage,circles, HOUGH_GRADIENT,1.5, 10, 100, 300, 100, 500);

感悟:dp取值1.5合适(圆心相关);param1表示传递给canny边缘检测的高阈值,低阈值取其一半; param2越大圆越完美数量越少;

CV_EXPORTS_W void HoughCircles( InputArray image,OutputArray circles,

                               int method,double dp, double minDist,

                               double param1 = 100,double param2 = 100,

                               int minRadius = 0,int maxRadius = 0 );

/**@example houghcircles.cpp

Anexample using the Hough circle detector

*/

 

/**@brief Finds circles in a grayscale image using the Hough transform.

 

Thefunction finds circles in a grayscale image using a modification of the Houghtransform.

 

Example::

@code

    #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],1)).data)

            return -1;

        cvtColor(img, gray, COLOR_BGR2GRAY);

        // smooth it, otherwise a lot of falsecircles 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++ )

        {

             Pointcenter(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;

    }

@endcode

 

@noteUsually the function detects the centers of circles well. However, it may failto find correct

radii.You can assist to the function by specifying the radius range ( minRadius andmaxRadius ) if

youknow it. Or, you may ignore the returned radius, use only the center, and findthe correct

radiususing an additional procedure.

 

@paramimage 8-bit, single-channel, grayscale input image.

@paramcircles Output vector of found circles. Each vector is encoded as a 3-element

floating-pointvector \f$(x, y, radius)\f$ .

@parammethod Detection method, see cv::HoughModes. Currently, the only implementedmethod is HOUGH_GRADIENT

@paramdp Inverse ratio of the accumulator resolution to the image resolution. Forexample, if

dp=1, the accumulator has the same resolution as the input image. If dp=2 , theaccumulator has

halfas big width and height.

@paramminDist Minimum distance between the centers of the detected circles. If theparameter is

toosmall, multiple neighbor circles may be falsely detected in addition to a trueone. If it is

toolarge, some circles may be missed.

@paramparam1 First method-specific parameter. In case of CV_HOUGH_GRADIENT , it isthe higher

thresholdof the two passed to the Canny edge detector (the lower one is twice smaller).

@paramparam2 Second method-specific parameter. In case of CV_HOUGH_GRADIENT , it isthe

accumulatorthreshold for the circle centers at the detection stage. The smaller it is, themore

falsecircles may be detected. Circles, corresponding to the larger accumulatorvalues, will be

returnedfirst.

@paramminRadius Minimum circle radius.

@parammaxRadius Maximum circle radius.

 

@safitEllipse, minEnclosingCircle

 */

源码:

//--------------------------------------【程序说明】-------------------------------------------
//      程序描述:  利用霍夫变换检测圆
//      开发测试所用操作系统: Windows 7 64bit
//      开发测试所用IDE版本:VisualStudio 2015
//      开发测试所用OpenCV版本:  3.1
//      2015年5月 Created by @姬波林
//      2015年5月 Revised by @姬波林
//------------------------------------------------------------------------------------------------
 
 
//---------------------------------【头文件、命名空间包含部分】----------------------------
//          描述:包含程序所使用的头文件和命名空间
//------------------------------------------------------------------------------------------------
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc/imgproc.hpp>
 
using namespace cv;
using namespace std;
 
#include <iostream>
#include <sstream>
#include <fstream>
 
//-----------------------------------【宏定义部分】--------------------------------------------
//      描述:定义一些辅助宏
//------------------------------------------------------------------------------------------------
 
 
//--------------------------------【全局函数声明部分】-------------------------------------
//      描述:全局函数声明
//-----------------------------------------------------------------------------------------------
void read_csv(string&csvPath, vector<String>&CirclePath, vector<int>&Circle_x, vector<int>&Circle_y, vector<int>&Circle_r)
{
   
    string line, path, classLabel1, classLabel2, classLabel3;
    ifstream file(csvPath.c_str(),ifstream::in);
    while (getline(file, line))
    {
        stringstream lines(line);
        getline(lines, path, '(');
 
        getline(lines, classLabel1,',');
        if (!classLabel1.empty())
        {
            Circle_x.push_back(atoi(classLabel1.c_str()));
        }
        getline(lines, classLabel2, ')');
        if (!classLabel2.empty())
        {
            Circle_y.push_back(atoi(classLabel2.c_str()));
        }
        getline(lines, classLabel3, '.');
        if (!classLabel3.empty())
        {
            Circle_r.push_back(atoi(classLabel3.c_str()));
        }
 
        if (!path.empty())
        {
            CirclePath.push_back(path+"("+ classLabel1+","+ classLabel2+")" + classLabel3+".bmp");
        }
    }
}
 
 
//-----------------------------------【ShowpText( )函数】----------------------------------
//          描述:输出一些帮助信息
//----------------------------------------------------------------------------------------------
void ShowText()
{
    //输出程序说明
    printf("绘制100个半径随机、圆心随机的圆,并保存为500X500BMP文件\n");
    printf("存储位置:D:\\圆\n");
    printf("命名规则:序号+圆心坐标+半径\n");
    printf("当前使用的OpenCV版本为:"CV_VERSION );
    printf("\n\n ----------------------------------------------------------------------------\n");
}
 
 
 
//---------------------------------------【main( )函数】--------------------------------------
//      描述:控制台应用程序的入口函数,我们的程序从这里开始执行
//-----------------------------------------------------------------------------------------------
 
const int kvalue = 15;//双边滤波邻域大小
 
int main()
{
    //批量读入圆路径
    string CircleCsvPath ="D:\\Circle\\at.txt";
    vector<String> vecCirclePath;
    vector<int> Circle_x, Circle_y, Circle_r;
    read_csv(CircleCsvPath, vecCirclePath,Circle_x, Circle_y, Circle_r);
 
    ofstream file("D:\\Circle\\检测结果.txt",ios::out);
    if (file.is_open())
    {
        file << "序号" <<"\t" <<"圆心x"<< "\t"<< "圆心y"<< "\t"<< "半径r"<< endl;
    }
    //霍夫圆检测
    for (size_t i = 0; i < 100; i++)
    {
        Mat srcImage = imread(vecCirclePath[i].c_str(), 1);//读取原彩色图
        //【1】载入原始图、Mat变量定义  
        Mat midImage, dstImage;//临时变量和目标图的定义
 
        //【2】显示原始图
        //imshow("【原始图】", srcImage);
 
        //【3】转为灰度图并进行图像平滑
        cvtColor(srcImage, midImage, COLOR_BGR2GRAY);//转化边缘检测后的图为灰度图
        GaussianBlur(midImage, midImage, Size(9, 9), 2, 2);
        //imshow("图像平滑", midImage);
        //【4】进行霍夫圆变换
        vector<Vec3f> circles;
        HoughCircles(midImage, circles, HOUGH_GRADIENT, 1.5, 10, 100, 300,100, 500);
        cout << "x=\ty=\tr=" << endl;
        //【5】依次在图中绘制出圆
        for (size_t j = 0; j < circles.size(); j++)
        {
            //参数定义
            Point center(cvRound(circles[j][0]), cvRound(circles[j][1]));
            int radius = cvRound(circles[j][2]);
            //绘制圆心
            circle(srcImage, center, 1, Scalar(0, 255, 0), -1, 8,0);
            //绘制圆轮廓
            circle(srcImage, center, radius, Scalar(155, 50, 255), 1,8, 0);
 
            if (file.is_open())
            {
                file << i << "\t" << Circle_x[i]<< "\t"<< Circle_y[i]<< "\t"
                    << Circle_r[i]<< "\t"<< "实际结果"<< endl;
                file<< i << "\t" << cvRound(circles[j][0])<< "\t"<< cvRound(circles[j][1])<< "\t"
                    << cvRound(circles[j][2])<< "\t"<< "检测结果"<< endl;//在控制台输出圆心坐标和半径   
            }
            cout << Circle_x[i]<< "\t"<< Circle_y[i]<< "\t"
                << Circle_r[i]<< endl;//原图圆心坐标和半径    
            cout << cvRound(circles[j][0])<< "\t"<< cvRound(circles[j][1])<< "\t"
                << cvRound(circles[j][2])<< endl;//在控制台输出圆心坐标和半径      
        }
    }
   
    //【6】显示效果图 
    //imshow("【效果图】", srcImage);
    file.close();
    waitKey();
    return 0;
}

效果图:



  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
import cv2 as cv import numpy as np def hough_circle(image): #因为霍夫检测对噪声很明显,所以需要先滤波一下。 dst =cv.pyrMeanShiftFiltering(image,10,100) cimage=cv.cvtColor(dst,cv.COLOR_BGR2GRAY) circles = cv.HoughCircles(cimage,cv.HOUGH_GRADIENT,1,40,param1=40,param2=29,minRadius=30,maxRadius=0) #把circles包含的圆心和半径的值变为整数 circles = np.uint16(np.around(circles)) for i in circles[0]: cv.circle(image,(i[0],i[1]),i[2],(0,255,0),3) cv.imshow("circle",image) src = cv.imread("E:/opencv/picture/coins.jpg") cv.imshow("inital_window",src) hough_circle(src) cv.waitKey(0) cv.destroyAllWindows() 霍夫圆变换的基本思路是认为图像上每一个非零像素点都有可能是一个潜在的圆上的一点, 跟霍夫线变换一样,也是通过投票,生成累积坐标平面,设置一个累积权重来定位圆。 在笛卡尔坐标系中圆的方程为: 其中(a,b)是圆心,r是半径,也可以表述为: 即 在笛卡尔的xy坐标系中经过某一点的所有圆映射到abr坐标系中就是一条三维的曲线: 经过xy坐标系中所有的非零像素点的所有圆就构成了abr坐标系中很多条三维的曲线。 在xy坐标系中同一个圆上的所有点的圆方程是一样的,它们映射到abr坐标系中的是同一个点,所以在abr坐标系中该点就应该有圆的总像素N0个曲线相交。 通过判断abr中每一点的相交(累积)数量,大于一定阈值的点就认为是圆。 以上是标准霍夫圆变换实现算法。 问题是它的累加到一个三维的空间,意味着比霍夫线变换需要更多的计算消耗。 Opencv霍夫圆变换对标准霍夫圆变换做了运算上的优化。 它采用的是“霍夫梯度法”。它的检测思路是去遍历累加所有非零点对应的圆心,对圆心进行考量。 如何定位圆心呢?圆心一定是在圆上的每个点的模向量上,即在垂直于该点并且经过该点的切线的垂直线上,这些圆上的模向量的交点就是圆心。 霍夫梯度法就是要去查找这些圆心,根据该“圆心”上模向量相交数量的多少,根据阈值进行最终的判断。 bilibili: 注意: 1.OpenCV霍夫圆变换函数原型为:HoughCircles(image, method, dp, minDist[, circles[, param1[, param2[, minRadius[, maxRadius]]]]]) -> circles image参数表示8位单通道灰度输入图像矩阵。 method参数表示圆检测方法,目前唯一实现的方法是HOUGH_GRADIENT。 dp参数表示累加器与原始图像相比的分辨率的反比参数。例如,如果dp = 1,则累加器具有与输入图像相同的分辨率。如果dp=2,累加器分辨率是元素图像的一半,宽度和高度也缩减为原来的一半。 minDist参数表示检测到的两个圆心之间的最小距离。如果参数太小,除了真实的一个圆圈之外,可能错误地检测到多个相邻的圆圈。如果太大,可能会遗漏一些圆圈。 circles参数表示检测到的圆的输出向量,向量内第一个元素是圆的横坐标,第二个是纵坐标,第三个是半径大小。 param1参数表示Canny边缘检测的高阈值,低阈值会被自动置为高阈值的一半。 param2参数表示圆心检测的累加阈值,参数值越小,可以检测越多的假圆圈,但返回的是与较大累加器值对应的圆圈。 minRadius参数表示检测到的圆的最小半径。 maxRadius参数表示检测到的圆的最大半径。 2.OpenCV画圆的circle函数原型:circle(img, center, radius, color[, thickness[, lineType[, shift]]]) -> img img参数表示源图像。 center参数表示圆心坐标。 radius参数表示圆的半径。 color参数表示设定圆的颜色。 thickness参数:如果是正数,表示圆轮廓的粗细程度。如果是负数,表示要绘制实心圆。 lineType参数表示圆线条的类型。 shift参数表示圆心坐标和半径值中的小数位数。
霍夫圆检测是一种用于检测图像中圆形的算法。在OpenCV中,霍夫圆检测是基于图像梯度的实现。具体原理如下: 1. 首先,对图像进行中值滤波,以减少噪声的影响\[1\]。 2. 接下来,通过检测边缘来发现可能的圆心。这一步使用图像梯度的方法来计算边缘\[1\]。 3. 在第一步的基础上,从候选圆心开始计算最佳半径大小。这一步使用霍夫变换的方法来确定圆的半径\[1\]。 在OpenCV中,可以使用cv::HoughCircles函数来实现霍夫圆检测。该函数的参数包括输入图像、输出结果、方法、尺度因子、最短距离、Canny边缘检测的低阈值、中心点累加器阈值、最小半径和最大半径\[3\]。 总结来说,霍夫圆检测通过对图像进行中值滤波和边缘检测,然后使用霍夫变换来确定圆的位置和半径。这种方法可以有效地检测图像中的圆形物体。 #### 引用[.reference_title] - *1* [OpenCvSharp 学习笔记21-- 霍夫变换 - 圆检测 (Hough Circle transform)](https://blog.csdn.net/weixin_41049188/article/details/92422241)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [OpenCV 霍夫圆检测](https://blog.csdn.net/qq_44989881/article/details/116135750)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [OpenCV20---霍夫圆检测](https://blog.csdn.net/qq_45646174/article/details/105086711)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值