Fitting a line to a set of points
In some applications, it could be important to not only detect lines in an image, but also to obtain an accurate estimate of the line's position and orientation. This recipe will show you how to find the line that best fits a given set of points.
How to do it...
The first thing to do is to identify points in an image that seem to be aligned along a straight line. Let's use one of the lines we detected in the preceding recipe. The lines detected using cv::HoughLinesP
are contained in std::vector<cv::Vec4i>
called lines
. To extract the set of points that seem to belong to, let's say, the first of these lines, we can proceed as follows. We draw a white line on a black image and intersect it with the Canny image of contours used to detect our lines. This is simply achieved by the following statements:
int n=0; // we select line 0 // black image cv::Mat oneline(contours.size(),CV_8U,cv::Scalar(0)); // white line cv::line(oneline, ...