天天看点

openCV实现图像的直线检测

上一篇博文介绍了图像的Canny边缘检测,本文主要介绍图像的直线检测部分,主要使用概率霍夫变换来检测直线,调用的函数为HoughLinesP(),下面给出代码部分以及直线检测效果图:

1、代码部分:

// Detect_Lines.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <cv.h>
#include "highgui.h"
using namespace std;
using namespace cv;
void drawDetectLines(Mat& image,const vector<Vec4i>& lines,Scalar & color)
{     
	// 将检测到的直线在图上画出来    
	vector<Vec4i>::const_iterator it=lines.begin();    
	while(it!=lines.end())    
	{        
		Point pt1((*it)[0],(*it)[1]);       
		Point pt2((*it)[2],(*it)[3]);        
		line(image,pt1,pt2,color,2); //线条宽度设置为2    
		++it;   
	}
} 
int _tmain(int argc, _TCHAR* argv[])
{
	Mat src_img=imread("..\\image_norm\\71253.jpg");
	imshow("src_img",src_img);
	Mat I;    
	cvtColor(src_img,I,CV_BGR2GRAY);                            
	Mat contours;    
	Canny(I,contours,125,350);   
	threshold(contours,contours,128,255,THRESH_BINARY);    
	vector<Vec4i> lines;       
	HoughLinesP(contours,lines,1,CV_PI/180,80,50,10);   
	drawDetectLines(src_img,lines,Scalar(0,255,0));     
	imshow("Detect_Lines",src_img);  
	cvWaitKey(0);
	return 0;
}

           

2、原图以及直线检测效果图:

openCV实现图像的直线检测

至此,已经实现了图像的直线检测部分,将检测出来的直线在原图中画了出来,也可以将检测出来的直线在上一篇博文中的边缘图像中画出来,效果如下:

openCV实现图像的直线检测

特别说明,HoughLinesP()函数的一般步骤请参考博文:http://blog.csdn.net/zhaocj/article/details/40047397

继续阅读