Karthik Sampath
Karthik Sampath

Reputation: 11

OpenCV draw contour and crop

I am new to OpenCV. Firstly, an object is placed on a white paper and then a photo is taken using a robot camera. At the next step, I am trying to extract the object placed on a white paper using OpenCV (find contour and draw contour). I would like to use this object then for my robot project.

Example image:

example image

This is the code I tried:

int main(int argc, char* argv[]){

    int largest_area=0;
    int largest_contour_index=0;
    Rect bounding_rect;

    // read the file from console
    Mat img0 = imread(argv[1], 1);

    Mat img1;
    cvtColor(img0, img1, CV_RGB2GRAY);

    // Canny filter
    Canny(img1, img1, 100, 200);

    // find the contours
    vector< vector<Point> > contours;
    findContours(img1, contours, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);

    printf("%ld\n", contours.size());

    for( size_t i = 0; i< contours.size(); i++ ) // iterate through each contour.
    {
        double area = contourArea(contours[i]);  //  Find the area of contour

        if(area > largest_area)
        {
            largest_area = area;
            largest_contour_index = i;               //Store the index of largest contour
            bounding_rect = boundingRect(contours[i]); // Find the bounding rectangle for biggest contour
        }
    }

    cout << "contour " << contours.size() << endl;
    cout << "largest contour " << largest_contour_index << endl;

    Scalar color = Scalar(0,0,255);
    drawContours(img0, contours, -1, color);

    Mat roi = Mat(img0, bounding_rect);

    // show the images
    imshow("result", img0);
    imshow("roi",roi);

    imwrite("result.png",roi);

    waitKey();
    return 0;
}

This draws the contour for all the objects in the photo. But how can I extract just the object on the white paper? For instance in this image:

this image

I want just to crop the card from the image but I have no idea how to proceed. Can anyone help me out?

Upvotes: 1

Views: 2197

Answers (1)

Saransh Kejriwal
Saransh Kejriwal

Reputation: 2533

Apply an ROI on the source image as shown:

Rect r=Rect(200,210,350,300)
/*create a rectangle of width 350 and height 300 with x=200 and y=210 as top-left vertex*/
Mat img_roi=src(r);

Selecting the appropriate dimensions of the rectangle should remove the area outside the white sheet from the image

Upvotes: 1

Related Questions