Search code examples
c++opencvedge-detection

Removing border lines in opencv and c++


enter image description here

I have many images with and without text similar to the image above. I want to remove the lines at the edges and also remove noise if any present in the image.

These lines are present only at edges as I have cropped these images from a table.


Solution

  • You can try following approach. But i cant guarantee that all lines in your image file can be removed.

    First detect all lines present in the image by applying Hough Transform

    vector<Vec2f> lines;
    HoughLines(img, lines, 1, CV_PI/180, 100, 0, 0 ); 
    

    Then iterate through each line detected,

    Get size of the image

    #you may have laoded image to some file
    #such as 
    #  Mat img=imread("some_file.jpg");
    int rows=img.rows;
    int colms=img.cols;
    Point pt3;
    

    now you know the size of matrix, next get the centre point of the line, you can do so as below,

    for( size_t i = 0; i < lines.size(); i++ )
    
    {
      float rho = lines[i][0], 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));
      pt3.x=(pt1.x+pt2.x)/2;
      pt3.y=(pt1.y+pt2.y)/2;
    
      *** 
      //decide whether you want to remove the line,i.e change line color to 
      // white or not
    
        line( img, pt1, pt2, Scalar(255,255,255), 3, CV_AA); // if you want to change
    }
    

    ***once you have both centre point and size of the image, you can compare the position of the centre point is in left,right,top, bottom. You can do so by comparing with as follows. Don't use (==) allow some difference.
    1. (0, cols/2) -- top of the image, 2. (rows/2,0) -- left of the image, 3. (rows, cols/2) -- bottom of the image 4. (rows/2, cols) -- right of the image

    (since your image is already blurred, smoothing , erosion and dilation may not do well)