connected_components.cpp 1.98 KB
Newer Older
1 2
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
Gary Bradski's avatar
Gary Bradski committed
3
#include <iostream>
4 5

using namespace cv;
6 7
using namespace std;

8 9 10
Mat img;
int threshval = 100;

11
static void on_trackbar(int, void*)
12
{
13 14
    Mat bw = threshval < 128 ? (img < threshval) : (img > threshval);

15 16
    vector<vector<Point> > contours;
    vector<Vec4i> hierarchy;
17

18
    findContours( bw, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE );
19 20

    Mat dst = Mat::zeros(img.size(), CV_8UC3);
21

22
    if( !contours.empty() && !hierarchy.empty() )
23 24 25 26 27 28 29 30 31 32 33
    {
        // iterate through all the top-level contours,
        // draw each connected component with its own random color
        int idx = 0;
        for( ; idx >= 0; idx = hierarchy[idx][0] )
        {
            Scalar color( (rand()&255), (rand()&255), (rand()&255) );
            drawContours( dst, contours, idx, color, CV_FILLED, 8, hierarchy );
        }
    }

34
    imshow( "Connected Components", dst );
35 36
}

37
static void help()
38
{
39
    cout << "\n This program demonstrates connected components and use of the trackbar\n"
40 41 42
             "Usage: \n"
             "  ./connected_components <image(stuff.jpg as default)>\n"
             "The image is converted to grayscale and displayed, another image has a trackbar\n"
43
             "that controls thresholding and thereby the extracted contours which are drawn in color\n";
44 45
}

46
const char* keys =
47
{
48
    "{1| |stuff.jpg|image for converting to a grayscale}"
49 50 51 52
};

int main( int argc, const char** argv )
{
53 54 55 56
    help();
    CommandLineParser parser(argc, argv, keys);
    string inputImage = parser.get<string>("1");
    img = imread(inputImage.c_str(), 0);
57

58 59
    if(img.empty())
    {
60
        cout << "Could not read input image file: " << inputImage << endl;
61 62
        return -1;
    }
63

64
    namedWindow( "Image", 1 );
65 66
    imshow( "Image", img );

67 68 69
    namedWindow( "Connected Components", 1 );
    createTrackbar( "Threshold", "Connected Components", &threshval, 255, on_trackbar );
    on_trackbar(threshval, 0);
70 71 72 73

    waitKey(0);
    return 0;
}