天天看點

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

繼續閱讀