Search code examples
androidimageopencvcounter

How to find and draw outer line of image in OpenCV?


enter image description here

As given in images when I process image (BEFORE) then I need its outer borders and draw red color line (Like AFTER image) in OpenCV android.


Solution

  • This is a classical application of cv::findContours.

    A working example is provided in the documentation.

    For your specific case you can do like this:

    #include <opencv2/core/core.hpp>
    #include <opencv2/highgui/highgui.hpp>
    #include <opencv2/imgproc/imgproc.hpp>
    #include <iostream>
    
    int main(int argc, char** argv)
    {
        using namespace cv;
        using namespace std;
    
        Mat3b image;
        image = imread(argv[1], 1);  
        imshow ("Before", image);
    
        Mat1b gray;
        cvtColor(image, gray, CV_BGR2GRAY);
        threshold(gray, gray, 250, 255, THRESH_BINARY);
        medianBlur(gray,gray, 3);
        gray = 255-gray;
    
        vector<vector<Point> > contours;
        vector<Vec4i> hierarchy;
        findContours(gray, contours, hierarchy, RETR_EXTERNAL , CHAIN_APPROX_NONE);
    
        Scalar color = Scalar( 0, 0, 255 );
        for (size_t i = 0; i < contours.size(); i++) {
            drawContours(image, contours, i, color, 2, 8, hierarchy, 0, Point());
        }     
        imshow("After", image);
        return 0;
    }
    

    Which will give you this output: Example output