霍夫變換檢測直線實現
#include “opencv2/opencv.hpp”
using namespace cv;
using namespace std;
int main()
{
Mat image = imread(“D:\\亂\\1.jpg”);
Mat result;
cvtColor(image,result,CV_BGR2GRAY);
Mat contours;
Canny(result, contours, 125, 350);
vector《Vec2f》 lines;
HoughLines(contours, lines, 1, CV_PI / 180, 100);
vector《Vec2f》::const_iterator it = lines.begin();
cout 《《 lines.size() 《《 endl;
printf(“OK”);
while (it != lines.end())
{
printf(“OK”);
float r = (*it)[0];
float theta = (*it)[1];
double a = cos(theta), b = sin(theta);
double x0 = a*r, y0 = b*r;
Point pt1(cvRound(x0 + 1000 * (-b)),
cvRound(y0 + 1000 * (a)));
Point pt2(cvRound(x0 - 1000 * (-b)),
cvRound(y0 - 1000 * (a)));
line(image, pt1, pt2, Scalar(0, 0, 255), 3, 8);
it++;
}
printf(“OK”);
namedWindow(“houghline”);
imshow(“houghline”, image);
waitKey(0);
Opencv實現直線檢測:
1、Opencv1.0版本:
[cpp] view plain copy print?
#include《cv.h》
#include《highgui.h》
int main()
{
IplImage* pImgSrc = NULL; //源圖像
IplImage* pImg8u = NULL; //灰度圖
IplImage* pImgCanny = NULL; //邊緣檢測后的圖
IplImage* pImgDst = NULL; //在圖像上畫上檢測到的直線后的圖像
CvSeq* lines = NULL;
CvMemStorage* storage = NULL;
/*邊緣檢測*/
pImgSrc = cvLoadImage(“。\\res\\street.jpg”, 1);
pImg8u = cvCreateImage(cvGetSize(pImgSrc), IPL_DEPTH_8U, 1);
pImgCanny = cvCreateImage(cvGetSize(pImgSrc), IPL_DEPTH_8U, 1);
pImgDst = cvCreateImage(cvGetSize(pImgSrc), IPL_DEPTH_8U, 1);
cvCvtColor(pImgSrc, pImg8u, CV_BGR2GRAY);
cvCanny(pImg8u, pImgCanny, 20, 200, 3);
/*檢測直線*/
storage = cvCreateMemStorage(0);
lines = cvHoughLines2(pImgCanny, storage, CV_HOUGH_PROBABILISTIC, 1, CV_PI / 180, 80, 200, 10);
pImgDst = cvCreateImage(cvGetSize(pImgSrc), IPL_DEPTH_8U, 3);
cvCvtColor(pImg8u, pImgDst, CV_GRAY2BGR);
/*在pImgDst上畫出檢測到的直線*/
for (int i = 0; i 《 lines-》total; i++)
{
CvPoint* line = (CvPoint*)cvGetSeqElem(lines, i);
cvLine(pImgDst, line[0], line[1], CV_RGB(255, 0, 0), 3, 8);
}
cvNamedWindow(“src”, 1);
cvNamedWindow(“canny”, 1);
cvNamedWindow(“hough”, 1);
cvShowImage(“src”, pImgSrc);
cvShowImage(“canny”, pImgCanny);
cvShowImage(“hough”, pImgDst);
cvWaitKey(0);
cvReleaseImage(&pImgSrc);
cvReleaseImage(&pImg8u);
cvReleaseImage(&pImgCanny);
cvReleaseImage(&pImgDst);
cvReleaseMemStorage(&storage);
return 0;
}
2、Opencv2.4.9版本:
[cpp] view plain copy print?
#include《opencv2\imgproc\imgproc.hpp》
#include《opencv2\opencv.hpp》
#include《opencv2\highgui\highgui.hpp》
using namespace std;
using namespace cv;
int main()
{
Mat Image = imread(“。//res//street.jpg”, 0);
Mat CannyImg;
Canny(Image, CannyImg, 140, 250, 3);
imshow(“CannyImg”, CannyImg);
Mat DstImg;
cvtColor(Image, DstImg, CV_GRAY2BGR);
vector《Vec4i》 Lines;
HoughLinesP(CannyImg, Lines, 1, CV_PI / 360, 170,30,15);
for (size_t i = 0; i 《 Lines.size(); i++)
{
line(DstImg, Point(Lines[i][0], Lines[i][1]), Point(Lines[i][2], Lines[i][3]), Scalar(0, 0, 255), 2, 8);
}
imshow(“HoughLines_Detect”, DstImg);
imwrite(“。//res//HoughLines_Detect.jpg”, DstImg);
waitKey(0);
return 0;
}
評論
查看更多