Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

You could simply use contour analysis to decide whether the line is straight or not.

If the line is perfectly straight then you will get only two end points on contour list after find contour, but make sure that the thickness of the input line is 1, otherwise make it 1 using thinning algorithm as explained here.

In case if the input image is not straight while looking pixel-wise but it appeared straight then apply approxPolyDP on found contours and adjust epsilon till you get satisfactory result.

Here is some code snippets which will show how to implement above method, here I manually create a black image and draw a string line on it.

    //Create an empty Mat and draw a straight line, here make sure that thickness=1
    Mat tmp(480,640,CV_8UC1,Scalar(0));
    line(tmp,Point(150,150),Point(300,300),Scalar(255),2);
    imshow("line",tmp);

    //find contours and store points to vactor
    vector< vector <Point> > contours;
    vector< Vec4i > hierarchy;
    findContours( tmp.clone(), contours, hierarchy,CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE ); //Find contour

    //here consider only the first contour in the src image
    if(contours.size()){
      cout<<"No of Contour Points : "<<contours[0].size()<<endl; //here two means perfect line

      for( int i = 0; i< contours[0].size(); i++ )
      circle(tmp,Point(contours[0][i]),3,Scalar(255),1,CV_AA); // draw each points find in the line

    }
    imshow("dst",tmp);
    waitKey();