# Approximating a set of points from a binary image

My task is to plot a line that reppresents the approximation (linerar I guess) to a set of points. Example: -draw a line that best fits the white points from this image. I am aware of functions such as fitLine but how can I use them when I represent images as Mat?

edit retag close merge delete

Thank you so much :)! for someone following your example and being as bad as me don't forget to change the the depth to fulfill fitline() assertions.

( 2015-04-06 11:50:39 -0500 )edit

Sort by ยป oldest newest most voted

a sample without cheking (b, depth...):

int main(int ac, char** av)
{
Mat m,mc;

cvtColor(mc, m, CV_BGR2GRAY);
vector<cv::Point2d> p;
Mat line_fit;
for (int i=0;i<m.rows;i++)
for (int j=0;j<m.cols;j++)
if (m.at<unsigned char>(i,j)!=0)
p.push_back(Point2d(j,i));
cout<<"Coordinates : \n";
cout<<p;
fitLine(p, line_fit, CV_DIST_L2, 0, 0.01, 0.01);
double a,b,c;
b = -line_fit.at<float>(0, 0);
a = line_fit.at<float>(1, 0);
c = -(a*line_fit.at<float>(2, 0) + b*line_fit.at<float>(3, 0));
line(mc,Point2d(0,-c/b),Point2d(m.cols,(-a*m.cols-c)/b),Scalar(0,255,0),2);

imshow("Fit", mc);
waitKey();
}

more

Official site

GitHub

Wiki

Documentation