Monday, June 15, 2015

OpenCV Extract Contour for Using with The Desired Image

Posted by Md.Hanif Ali on Monday, June 15, 2015 in , | No comments
Find biggest contour using Opencv:

An example to find largest contour from the input image. A contour can be considered as a sequence of points that define a specific object in an image. To get the contours from image we have to convert it to gray scale and then apply the findContours() funcion. After finding the required contours extra coding is required to get the largest contour. The code given below will do the job.

Code:

/*
 * extract the largest contour and use a background
 */

#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <opencv2/imgproc/imgproc.hpp>
#include "iostream"
using namespace cv;

int main()
{
    Mat img1;
    namedWindow("Detected");
    double largest_area=0;
    int contour_index=0;
    Rect bounding_rect;
    Mat img = imread("c:/open/ok.jpg");

    if ( img.empty() )
    {
       return -1;
    }
    cvtColor(img,img1,CV_RGB2GRAY);
    Canny(img1,img1,200,255);
    namedWindow("Canny");
    imshow("Canny",img1);


    std::vector< std::vector<cv::Point> > contours;
    std::vector<cv::Vec4i>hierarcy;

    findContours(img1,contours,CV_RETR_CCOMP,CV_CHAIN_APPROX_SIMPLE);

    //  Mat mask=Mat::zeros(img.cols,img.rows,CV_8UC1);  //alternative way: below line
    Mat mask(img.cols,img.rows,CV_8UC1,Scalar::all(0));

    for(int i=0;i<contours.size();i++)
    {
        double area=contourArea(contours[i],false);

        //finding out the largest area
        if(area>largest_area)
        {
            largest_area=area;
            contour_index=i;
           bounding_rect= boundingRect(contours[i]); //the largest contour rectangle
        }
    }
    drawContours(mask,contours,contour_index,Scalar(255),CV_FILLED);

    namedWindow("Mask");
    imshow("Mask",mask);

   //Mat newimg( img.cols,img.rows,CV_8UC3,Scalar(30,29,140));
   Mat newimg=imread("c:/open/me2.jpg"); //use your own pic of the same size as the source image
    img.copyTo(newimg,mask);
     normalize(mask.clone(), mask, 0.0, 255.0, CV_MINMAX, CV_8UC1);

    rectangle(img,bounding_rect,Scalar(244,33,54),2);
    imshow("Detected",img);
    namedWindow("Output");
    imshow("Output",newimg);
    waitKey(0);
    return 0;
}

Output: 

 

0 comments:

Post a Comment