How to extract the object on white paper?

asked 2016-02-25 15:47:21 -0600

updated 2020-10-06 23:02:40 -0600

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: image description

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:

image description

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

edit retag flag offensive close merge delete

Comments

sturkmen gravatar imagesturkmen ( 2016-02-26 06:51:03 -0600 )edit

hi i tried the code already. It just says my image is not quadrilateral and it ends up. Thank you

aparna91 gravatar imageaparna91 ( 2016-02-26 08:50:55 -0600 )edit