1.源码实现
#include <iostream>
#include <ctime>
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace std;
using namespace cv;
int main()
{
Mat srcImage;
srcImage = imread("2.jpg");
//判断图像是否加载成功
if(srcImage.empty())
{
cout << "图像加载失败" << endl;
return -1;
}
//对图像进行边缘检测
Mat midImage, dstImage;
Canny(srcImage, midImage, 50, 200, 3);
cvtColor(midImage, dstImage, COLOR_GRAY2BGR);
//进行霍夫变换
vector<Vec2f> lines;
HoughLines(midImage, lines, 1, CV_PI/180, 260, 0, 0);
//在图像中绘出线段
for(size_t i=0; i<lines.size(); i++)
{
float rho = lines[i][0];
float 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(dstImage, pt1, pt2, Scalar(0,0,255), 1, 4);
}
imwrite("houghlines.jpg", dstImage);
return 0;
}
2.编译源码
$ g++ -o test test.cpp -std=c++11 -I/usr/local/include -L/usr/local/lib -lopencv_core -lopencv_highgui -lopencv_imgproc -Wl,-rpath=/usr/local/lib
3.运行结果
2.jpghoughlines.jpg
网友评论