OpenCV学习笔记11 OpenCV图像处理模块ImgProc Module. Image Processing(四)

来源:互联网 发布:淘宝数码宝贝大师 编辑:程序博客网 时间:2024/05/22 00:12

3.11 霍夫线性变换


使用标准霍夫线性变换 HoughLines和统计概率霍夫线性变换 HoughLinesP函数检测图像中的直线。
在对图像执行霍夫变换之前,需要先检测出边缘线,即霍夫线性变换的直接输入是带有边缘线的二值图像。
标准霍夫变换:
Mat dst, cdst;Canny(src, dst, 50, 200, 3);// 使用Canny算子检测出边缘线cvtColor(dst, cdst, CV_GRAY2BGR); vector<Vec2f> lines;// 用来存储检测到的直线的参数,每一组直线参数包括极径rho和极角theta  HoughLines(dst, lines, 1, CV_PI/180, 100, 0, 0 ); // 标准霍夫线性变换,输出 r和θfor( size_t i = 0; i < lines.size(); i++ )// 画出检测到的直线{   float rho = lines[i][0], theta = lines[i][1];   Point pt1, pt2;   double a = cos(theta), b = sin(theta);   double x0 = a*rho, y0 = b*rho;   pt1.x = cvRound(x0 + 1000*(-b));   pt1.y = cvRound(y0 + 1000*(a));   pt2.x = cvRound(x0 - 1000*(-b));   pt2.y = cvRound(y0 - 1000*(a));   line( cdst, pt1, pt2, Scalar(0,0,255), 3, CV_AA);}

统计概率霍夫变换:
 Mat dst, cdst; Canny(src, dst, 50, 200, 3); cvtColor(dst, cdst, CV_GRAY2BGR);  vector<Vec4i> lines;// 用来存储检测到的直线的参数,每一组直线参数包含直线两个端点的直角坐标x0,y0和x1,y1  HoughLinesP(dst, lines, 1, CV_PI/180, 50, 50, 10 ); // 统计概率霍夫变换,输出直线两个端点的坐标  for( size_t i = 0; i < lines.size(); i++ )<span style="white-space:pre"></span>// 画出检测到的直线  {    Vec4i l = lines[i];    line( cdst, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0,0,255), 3, CV_AA);  }


2.12 霍夫圆变换


使用 HoughCircles 函数来检测图像中的圆。
在变换之前,先将图像转换成灰度图并进行高斯平滑。执行霍夫圆变换时输出为三个参数,圆心的直角坐标x,y和圆的半径r 。
  cvtColor( src, src_gray, CV_BGR2GRAY );  /// 减少噪声以避免圆的检测失败  GaussianBlur( src_gray, src_gray, Size(9, 9), 2, 2 );  vector<Vec3f> circles;<span style="white-space:pre"></span>// 存储表示圆形的三个参数 x,y,r  /// 使用霍夫圆变换  HoughCircles( src_gray, circles, CV_HOUGH_GRADIENT, 1, src_gray.rows/8, 200, 100, 0, 0 );  /// 画出检测到的圆  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]);      // 圆心      circle( src, center, 3, Scalar(0,255,0), -1, 8, 0 );      // 圆形      circle( src, center, radius, Scalar(0,0,255), 3, 8, 0 );   }




0 0
原创粉丝点击