zoukankan      html  css  js  c++  java
  • Opencv2.4.9源码分析——HoughLinesP

    http://blog.csdn.net/zhaocj/article/details/400473



    标准霍夫变换本质上是把图像映射到它的参数空间上,它需要计算所有的M个边缘点,这样它的运算量和所需内存空间都会很大。如果在输入图像中只是处理mm<M)个边缘点,则这m个边缘点的选取是具有一定概率性的,因此该方法被称为概率霍夫变换(Probabilistic Hough Transform)。该方法还有一个重要的特点就是能够检测出线端,即能够检测出图像中直线的两个端点,确切地定位图像中的直线。

    HoughLinesP函数就是利用概率霍夫变换来检测直线的。它的一般步骤为:

    1、随机抽取图像中的一个特征点,即边缘点,如果该点已经被标定为是某一条直线上的点,则继续在剩下的边缘点中随机抽取一个边缘点,直到所有边缘点都抽取完了为止;

    2、对该点进行霍夫变换,并进行累加和计算;

    3、选取在霍夫空间内值最大的点,如果该点大于阈值的,则进行步骤4,否则回到步骤1;

    4、根据霍夫变换得到的最大值,从该点出发,沿着直线的方向位移,从而找到直线的两个端点;

    5、计算直线的长度,如果大于某个阈值,则被认为是好的直线输出,回到步骤1。

    HoughLinesP函数的原型为:

    void HoughLinesP(InputArray image,OutputArray lines, double rho, double theta, int threshold, double minLineLength=0,double maxLineGap=0 )

    image为输入图像,要求是8位单通道图像

    lines为输出的直线向量,每条线用4个元素表示,即直线的两个端点的4个坐标值

    rho和theta分别为距离和角度的分辨率

    threshold为阈值,即步骤3中的阈值

    minLineLength为最小直线长度,在步骤5中要用到,即如果小于该值,则不被认为是一条直线

    maxLineGap为最大直线间隙,在步骤4中要用到,即如果有两条线段是在一条直线上,但它们之间因为有间隙,所以被认为是两个线段,如果这个间隙大于该值,则被认为是两条线段,否则是一条。

    HoughLinesP函数是在sources/modules/imgproc/src/hough.cpp文件中被定义的:

    1. void cv::HoughLinesP( InputArray _image, OutputArray _lines,  
    2.                       double rho, double theta, int threshold,  
    3.                       double minLineLength, double maxGap )  
    4. {  
    5.     Ptr<CvMemStorage> storage = cvCreateMemStorage(STORAGE_SIZE);  
    6.     Mat image = _image.getMat();  
    7.     CvMat c_image = image;  
    8.     CvSeq* seq = cvHoughLines2( &c_image, storage, CV_HOUGH_PROBABILISTIC,  
    9.                     rho, theta, threshold, minLineLength, maxGap );  
    10.     seqToMat(seq, _lines);  
    11. }  
    从HoughLinesP函数可以看出,该函数会调用cvHoughLines2函数。它通过参数CV_HOUGH_PROBABILISTIC,最终调用了icvHoughLinesProbabilistic函数:
    1. static void  
    2. icvHoughLinesProbabilistic( CvMat* image,  
    3.                             float rho, float theta, int threshold,  
    4.                             int lineLength, int lineGap,  
    5.                             CvSeq *lines, int linesMax )  
    6. {  
    7.     //accum为累加器矩阵,mask为掩码矩阵  
    8.     cv::Mat accum, mask;  
    9.     cv::vector<float> trigtab;    //用于存储事先计算好的正弦和余弦值  
    10.     //开辟一段内存空间  
    11.     cv::MemStorage storage(cvCreateMemStorage(0));  
    12.     //用于存储特征点坐标,即边缘像素的位置  
    13.     CvSeq* seq;   
    14.     CvSeqWriter writer;  
    15.     int width, height;    //图像的宽和高  
    16.     int numangle, numrho;    //角度和距离的离散数量  
    17.     float ang;  
    18.     int r, n, count;  
    19.     CvPoint pt;  
    20.     float irho = 1 / rho;    //距离分辨率的倒数  
    21.     CvRNG rng = cvRNG(-1);    //随机数  
    22.     const float* ttab;    //向量trigtab的地址指针  
    23.     uchar* mdata0;    //矩阵mask的地址指针  
    24.     //确保输入图像的正确性  
    25.     CV_Assert( CV_IS_MAT(image) && CV_MAT_TYPE(image->type) == CV_8UC1 );  
    26.   
    27.     width = image->cols;    //提取出输入图像的宽  
    28.     height = image->rows;    //提取出输入图像的高  
    29.     //由角度和距离分辨率,得到角度和距离的离散数量  
    30.     numangle = cvRound(CV_PI / theta);  
    31.     numrho = cvRound(((width + height) * 2 + 1) / rho);  
    32.     //创建累加器矩阵,即霍夫空间  
    33.     accum.create( numangle, numrho, CV_32SC1 );  
    34.     //创建掩码矩阵,大小与输入图像相同  
    35.     mask.create( height, width, CV_8UC1 );  
    36.     //定义trigtab的大小,因为要存储正弦和余弦值,所以长度为角度离散数的2倍  
    37.     trigtab.resize(numangle*2);  
    38.     //累加器矩阵清零  
    39.     accum = cv::Scalar(0);  
    40.     //避免重复计算,事先计算好所需的所有正弦和余弦值  
    41.     for( ang = 0, n = 0; n < numangle; ang += theta, n++ )  
    42.     {  
    43.         trigtab[n*2] = (float)(cos(ang) * irho);  
    44.         trigtab[n*2+1] = (float)(sin(ang) * irho);  
    45.     }  
    46.     //赋值首地址  
    47.     ttab = &trigtab[0];  
    48.     mdata0 = mask.data;  
    49.     //开始写入序列  
    50.     cvStartWriteSeq( CV_32SC2, sizeof(CvSeq), sizeof(CvPoint), storage, &writer );  
    51.   
    52.     // stage 1. collect non-zero image points  
    53.     //收集图像中的所有非零点,因为输入图像是边缘图像,所以非零点就是边缘点  
    54.     for( pt.y = 0, count = 0; pt.y < height; pt.y++ )  
    55.     {  
    56.         //提取出输入图像和掩码矩阵的每行地址指针  
    57.         const uchar* data = image->data.ptr + pt.y*image->step;  
    58.         uchar* mdata = mdata0 + pt.y*width;  
    59.         for( pt.x = 0; pt.x < width; pt.x++ )  
    60.         {  
    61.             if( data[pt.x] )    //是边缘点  
    62.             {  
    63.                 mdata[pt.x] = (uchar)1;    //掩码的相应位置置1  
    64.                 CV_WRITE_SEQ_ELEM( pt, writer );    把该坐标位置写入序列  
    65.             }  
    66.             else    //不是边缘点  
    67.                 mdata[pt.x] = 0;    //掩码的相应位置清0  
    68.         }  
    69.     }  
    70.     //终止写序列,seq为所有边缘点坐标位置的序列  
    71.     seq = cvEndWriteSeq( &writer );  
    72.     count = seq->total;    //得到边缘点的数量  
    73.   
    74.     // stage 2. process all the points in random order  
    75.     //随机处理所有的边缘点  
    76.     for( ; count > 0; count-- )  
    77.     {  
    78.         // choose random point out of the remaining ones  
    79.         //步骤1,在剩下的边缘点中随机选择一个点,idx为不大于count的随机数  
    80.         int idx = cvRandInt(&rng) % count;  
    81.         //max_val为累加器的最大值,max_n为最大值所对应的角度  
    82.         int max_val = threshold-1, max_n = 0;  
    83.         //由随机数idx在序列中提取出所对应的坐标点  
    84.         CvPoint* point = (CvPoint*)cvGetSeqElem( seq, idx );  
    85.         //定义直线的两个端点  
    86.         CvPoint line_end[2] = {{0,0}, {0,0}};  
    87.         float a, b;  
    88.         //累加器的地址指针,也就是霍夫空间的地址指针  
    89.         int* adata = (int*)accum.data;  
    90.         int i, j, k, x0, y0, dx0, dy0, xflag;  
    91.         int good_line;  
    92.         const int shift = 16;  
    93.         //提取出坐标点的横、纵坐标  
    94.         i = point->y;  
    95.         j = point->x;  
    96.   
    97.         // "remove" it by overriding it with the last element  
    98.         //用序列中的最后一个元素覆盖掉刚才提取出来的随机坐标点  
    99.         *point = *(CvPoint*)cvGetSeqElem( seq, count-1 );  
    100.   
    101.         // check if it has been excluded already (i.e. belongs to some other line)  
    102.         //检测这个坐标点是否已经计算过,也就是它已经属于其他直线  
    103.         //因为计算过的坐标点会在掩码矩阵mask的相对应位置清零  
    104.         if( !mdata0[i*width + j] )    //该坐标点被处理过  
    105.             continue;    //不做任何处理,继续主循环  
    106.   
    107.         // update accumulator, find the most probable line  
    108.         //步骤2,更新累加器矩阵,找到最有可能的直线  
    109.         for( n = 0; n < numangle; n++, adata += numrho )  
    110.         {  
    111.             //由角度计算距离  
    112.             r = cvRound( j * ttab[n*2] + i * ttab[n*2+1] );  
    113.             r += (numrho - 1) / 2;  
    114.             //在累加器矩阵的相应位置上数值加1,并赋值给val  
    115.             int val = ++adata[r];  
    116.             //更新最大值,并得到它的角度  
    117.             if( max_val < val )  
    118.             {  
    119.                 max_val = val;  
    120.                 max_n = n;  
    121.             }  
    122.         }  
    123.   
    124.         // if it is too "weak" candidate, continue with another point  
    125.         //步骤3,如果上面得到的最大值小于阈值,则放弃该点,继续下一个点的计算  
    126.         if( max_val < threshold )  
    127.             continue;  
    128.   
    129.         // from the current point walk in each direction  
    130.         // along the found line and extract the line segment  
    131.         //步骤4,从当前点出发,沿着它所在直线的方向前进,直到达到端点为止  
    132.         a = -ttab[max_n*2+1];    //a=-sinθ  
    133.         b = ttab[max_n*2];    //b=cosθ  
    134.         //当前点的横、纵坐标值  
    135.         x0 = j;  
    136.         y0 = i;  
    137.         //确定当前点所在直线的角度是在45度~135度之间,还是在0~45或135度~180度之间  
    138.         if( fabs(a) > fabs(b) )    //在45度~135度之间  
    139.         {  
    140.             xflag = 1;    //置标识位,标识直线的粗略方向  
    141.             //确定横、纵坐标的位移量  
    142.             dx0 = a > 0 ? 1 : -1;      
    143.             dy0 = cvRound( b*(1 << shift)/fabs(a) );  
    144.             //确定纵坐标  
    145.             y0 = (y0 << shift) + (1 << (shift-1));  
    146.         }  
    147.         else    //在0~45或135度~180度之间  
    148.         {  
    149.             xflag = 0;   //清标识位  
    150.             //确定横、纵坐标的位移量  
    151.             dy0 = b > 0 ? 1 : -1;  
    152.             dx0 = cvRound( a*(1 << shift)/fabs(b) );  
    153.             //确定横坐标  
    154.             x0 = (x0 << shift) + (1 << (shift-1));  
    155.         }  
    156.         //搜索直线的两个端点  
    157.         for( k = 0; k < 2; k++ )  
    158.         {  
    159.             //gap表示两条直线的间隙,x和y为搜索位置,dx和dy为位移量  
    160.             int gap = 0, x = x0, y = y0, dx = dx0, dy = dy0;  
    161.             //搜索第二个端点的时候,反方向位移  
    162.             if( k > 0 )  
    163.                 dx = -dx, dy = -dy;  
    164.   
    165.             // walk along the line using fixed-point arithmetics,  
    166.             // stop at the image border or in case of too big gap  
    167.             //沿着直线的方向位移,直到到达图像的边界或大的间隙为止  
    168.             for( ;; x += dx, y += dy )  
    169.             {  
    170.                 uchar* mdata;  
    171.                 int i1, j1;  
    172.                 //确定新的位移后的坐标位置  
    173.                 if( xflag )  
    174.                 {  
    175.                     j1 = x;  
    176.                     i1 = y >> shift;  
    177.                 }  
    178.                 else  
    179.                 {  
    180.                     j1 = x >> shift;  
    181.                     i1 = y;  
    182.                 }  
    183.                 //如果到达了图像的边界,停止位移,退出循环  
    184.                 if( j1 < 0 || j1 >= width || i1 < 0 || i1 >= height )  
    185.                     break;  
    186.                 //定位位移后掩码矩阵位置  
    187.                 mdata = mdata0 + i1*width + j1;  
    188.   
    189.                 // for each non-zero point:  
    190.                 //    update line end,  
    191.                 //    clear the mask element  
    192.                 //    reset the gap  
    193.                 //该掩码不为0,说明该点可能是在直线上  
    194.                 if( *mdata )   
    195.                 {  
    196.                     gap = 0;    //设置间隙为0  
    197.                     //更新直线的端点位置  
    198.                     line_end[k].y = i1;  
    199.                     line_end[k].x = j1;  
    200.                 }  
    201.                 //掩码为0,说明不是直线,但仍继续位移,直到间隙大于所设置的阈值为止  
    202.                 else if( ++gap > lineGap )    //间隙加1  
    203.                     break;  
    204.             }  
    205.         }  
    206.         //步骤5,由检测到的直线的两个端点粗略计算直线的长度  
    207.         //当直线长度大于所设置的阈值时,good_line为1,否则为0  
    208.         good_line = abs(line_end[1].x - line_end[0].x) >= lineLength ||  
    209.                     abs(line_end[1].y - line_end[0].y) >= lineLength;  
    210.         //再次搜索端点,目的是更新累加器矩阵和更新掩码矩阵,以备下一次循环使用  
    211.         for( k = 0; k < 2; k++ )  
    212.         {  
    213.             int x = x0, y = y0, dx = dx0, dy = dy0;  
    214.   
    215.             if( k > 0 )  
    216.                 dx = -dx, dy = -dy;  
    217.   
    218.             // walk along the line using fixed-point arithmetics,  
    219.             // stop at the image border or in case of too big gap  
    220.             for( ;; x += dx, y += dy )  
    221.             {  
    222.                 uchar* mdata;  
    223.                 int i1, j1;  
    224.   
    225.                 if( xflag )  
    226.                 {  
    227.                     j1 = x;  
    228.                     i1 = y >> shift;  
    229.                 }  
    230.                 else  
    231.                 {  
    232.                     j1 = x >> shift;  
    233.                     i1 = y;  
    234.                 }  
    235.   
    236.                 mdata = mdata0 + i1*width + j1;  
    237.   
    238.                 // for each non-zero point:  
    239.                 //    update line end,  
    240.                 //    clear the mask element  
    241.                 //    reset the gap  
    242.                 if( *mdata )  
    243.                 {  
    244.                     //if语句的作用是清除那些已经判定是好的直线上的点对应的累加器的值,避免再次利用这些累加值  
    245.                     if( good_line )    //在第一次搜索中已经确定是好的直线  
    246.                     {  
    247.                         //得到累加器矩阵地址指针  
    248.                         adata = (int*)accum.data;  
    249.                         for( n = 0; n < numangle; n++, adata += numrho )  
    250.                         {  
    251.                             r = cvRound( j1 * ttab[n*2] + i1 * ttab[n*2+1] );  
    252.                             r += (numrho - 1) / 2;  
    253.                             adata[r]--;    //相应的累加器减1  
    254.                         }  
    255.                     }  
    256.                     //搜索过的位置,不管是好的直线,还是坏的直线,掩码相应位置都清0,这样下次就不会再重复搜索这些位置了,从而达到减小计算边缘点的目的  
    257.                     *mdata = 0;  
    258.                 }  
    259.                 //如果已经到达了直线的端点,则退出循环  
    260.                 if( i1 == line_end[k].y && j1 == line_end[k].x )  
    261.                     break;  
    262.             }  
    263.         }  
    264.         //如果是好的直线  
    265.         if( good_line )  
    266.         {  
    267.             CvRect lr = { line_end[0].x, line_end[0].y, line_end[1].x, line_end[1].y };  
    268.             //把两个端点压入序列中  
    269.             cvSeqPush( lines, &lr );  
    270.             //如果检测到的直线数量大于阈值,则退出该函数  
    271.             if( lines->total >= linesMax )  
    272.                 return;  
    273.         }  
    274.     }  
    275. }  
    下面就给出应用HoughLinesP函数检测直线段的应用程序:

    1. #include "opencv2/core/core.hpp"  
    2. #include "opencv2/highgui/highgui.hpp"  
    3. #include "opencv2/imgproc/imgproc.hpp"  
    4.   
    5. #include <iostream>  
    6. using namespace cv;  
    7. using namespace std;  
    8.   
    9. int main( int argc, char** argv )  
    10. {  
    11.     Mat src, edge,color_edge;  
    12.     src=imread("building.jpg");  
    13.     if( !src.data )    
    14.         return -1;    
    15.   
    16.     Canny(src,edge,50,200,3);  
    17.     cvtColor( edge, color_edge, CV_GRAY2BGR );  
    18.     vector<Vec4i> lines;  
    19.     HoughLinesP(edge, lines, 1, CV_PI/180, 80, 30, 10 );  
    20.     forsize_t i = 0; i < lines.size(); i++ )  
    21.     {  
    22.         Vec4i l = lines[i];  
    23.         line( color_edge, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0,0,255), 2);  
    24.     }  
    25.   
    26.     namedWindow( "lines", CV_WINDOW_AUTOSIZE );  
    27.     imshow( "lines", color_edge );  
    28.     waitKey(0);  
    29.   
    30.     return 0;  
    31. }  
    下图为输出的图像:


  • 相关阅读:
    【数据分析】6 点发的文章在博客园阅读量最高?
    canvas api 速记
    leetcode 315. Count of Smaller Numbers After Self 两种思路
    一道闭包题题解
    一道经典JS题(关于this)
    HTML5 — 让拖放变的流行起来
    你应该知道的25道Javascript面试题
    关于base64编码的原理和实现
    Python中的None
    Python字符编码和转码
  • 原文地址:https://www.cnblogs.com/fag888/p/5789167.html
Copyright © 2011-2022 走看看