Ask Your Question

Revision history [back]

for a starting point you can try the code below.

it finds the biggest contour and cut bounding rectangle.

you will get result images like:

image description image description

after that you can do some other improvements if you need

#include "opencv2/opencv.hpp"

using namespace cv;
using namespace std;

int main( int argc, char** argv )
{
    int largest_area=0;
    int largest_contour_index=0;
    cv::Rect bounding_rect;

    Mat img=imread(argv[1],1);
    Mat thr,dst;

    cvtColor(img,thr,COLOR_BGR2GRAY); //Convert to gray
    threshold(thr, thr,125, 255,THRESH_BINARY); //Threshold the gray

    vector<vector<cv::Point> > contours; // Vector for storing contour

    findContours( thr, contours,CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE ); // Find the contours in the image

    for( int i = 0; i< contours.size(); i++ ) // iterate through each contour.
    {
        double a=contourArea( contours[i],false);  //  Find the area of contour
        if(a>largest_area)
        {
            largest_area=a;
            largest_contour_index=i;                //Store the index of largest contour
            bounding_rect=boundingRect(contours[i]); // Find the bounding rectangle for biggest contour
        }
    }

    Mat biggest_contour_rect = img( bounding_rect ).clone();
    imshow("biggest_contour_rect", biggest_contour_rect );
    waitKey(0);
    return 0;
}