Once considering detect a line from image, Hough Line Detection algorithm must be the first choice, it's classic and easily to understand, but in this blog I would like to share another useful algorithm: Line Segment Detection, it's faster and more accurate than Hough, here is a small example about LSD for reference:http://download.csdn.net/download/cutelily2014/10034091
Next is the script to perform LSD's magic, lsd.cpp.
Reference from: http://blog.csdn.net/mollylee1011/article/details/47292783
/*
This is a simple example to display LSD algorithm in Line Detection
Notes: It read image flow from a video named video.mp4.
*/
#include <iostream>
#include <string>
#include "opencv2/core.hpp"
#include "opencv2/core/utility.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui/highgui.hpp"
using namespace std;
using namespace cv;
int main(int argc, char **argv)
{
// Step 1: read image and convert the origin color image to a binary
VideoCapture capture(argv[1]);
Mat image;
namedWindow("video", WINDOW_NORMAL);
if(!capture.isOpened())
throw "Error: Reading video failed !";
while(capture.read(image))
{
Mat img_hsv(image);
cvtColor(image, img_hsv, CV_BGR2HSV);
//lower red mask
Mat mask0;
inRange(img_hsv, Scalar(0, 50, 50), Scalar(10, 255, 255), mask0);
//upper red mask
Mat mask1;
inRange(img_hsv, Scalar(100, 50, 50), Scalar(180, 255, 255), mask1);
Mat img_filt = mask0 + mask1;
//imshow("video", img_filt);
// Step 2: detect line by LSD algorithm
Canny(image, image, 50, 200, 3);
Ptr<LineSegmentDetector> ls = createLineSegmentDetector(LSD_REFINE_STD);
//Ptr<LineSegmentDetector> ls = createLineSegmentDetector(LSD_REFINE_NONE);
double start = double(getTickCount());
vector<Vec4f> lines_std;
ls->detect(img_filt, lines_std);
// Step 3: display detected lines
double duration_ms = (double(getTickCount()) - start) * 1000 / getTickFrequency();
std::cout << "It took " << duration_ms << " ms." << std::endl;
//Mat drawnLines(image);
ls->drawSegments(image, lines_std);
imshow("video", image);
waitKey(20);
}
waitKey();
return 0;
}