samples/cpp/connected_components.cpp#

This program demonstrates connected components and use of the trackbar

 1#include <opencv2/core/utility.hpp>
 2#include "opencv2/imgproc.hpp"
 3#include "opencv2/imgcodecs.hpp"
 4#include "opencv2/highgui.hpp"
 5#include <iostream>
 6
 7using namespace cv;
 8using namespace std;
 9
10Mat img;
11int threshval = 100;
12
13static void on_trackbar(int, void*)
14{
15    Mat bw = threshval < 128 ? (img < threshval) : (img > threshval);
16    Mat labelImage(img.size(), CV_32S);
17    int nLabels = connectedComponents(bw, labelImage, 8);
18    std::vector<Vec3b> colors(nLabels);
19    colors[0] = Vec3b(0, 0, 0);//background
20    for(int label = 1; label < nLabels; ++label){
21        colors[label] = Vec3b( (rand()&255), (rand()&255), (rand()&255) );
22    }
23    Mat dst(img.size(), CV_8UC3);
24    for(int r = 0; r < dst.rows; ++r){
25        for(int c = 0; c < dst.cols; ++c){
26            int label = labelImage.at<int>(r, c);
27            Vec3b &pixel = dst.at<Vec3b>(r, c);
28            pixel = colors[label];
29         }
30     }
31
32    imshow( "Connected Components", dst );
33}
34
35int main( int argc, const char** argv )
36{
37    CommandLineParser parser(argc, argv, "{@image|stuff.jpg|image for converting to a grayscale}");
38    parser.about("\nThis program demonstrates connected components and use of the trackbar\n");
39    parser.printMessage();
40    cout << "\nThe image is converted to grayscale and displayed, another image has a trackbar\n"
41            "that controls thresholding and thereby the extracted contours which are drawn in color\n";
42
43    String inputImage = parser.get<string>(0);
44    img = imread(samples::findFile(inputImage), IMREAD_GRAYSCALE);
45
46    if(img.empty())
47    {
48        cout << "Could not read input image file: " << inputImage << endl;
49        return EXIT_FAILURE;
50    }
51
52    imshow( "Image", img );
53
54    namedWindow( "Connected Components", WINDOW_AUTOSIZE);
55    createTrackbar( "Threshold", "Connected Components", &threshval, 255, on_trackbar );
56    on_trackbar(threshval, 0);
57
58    waitKey(0);
59    return EXIT_SUCCESS;
60}