毕设之Opencv批量霍夫圆检测

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Cracent/article/details/51419293

 毕设之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;
}

效果图:



猜你喜欢

转载自blog.csdn.net/Cracent/article/details/51419293