1 #include <opencv2/core/utility.hpp>
2 #include "opencv2/imgproc.hpp"
3 #include "opencv2/imgcodecs.hpp"
4 #include "opencv2/highgui.hpp"
13 static void on_trackbar(int, void*)
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) );
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];
32 imshow( "Connected Components", dst );
37 cout << "\n This program demonstrates connected components and use of the trackbar\n"
39 " ./connected_components <image(stuff.jpg as default)>\n"
40 "The 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";
46 "{@image|stuff.jpg|image for converting to a grayscale}"
49 int main( int argc, const char** argv )
52 CommandLineParser parser(argc, argv, keys);
53 string inputImage = parser.get<string>(0);
54 img = imread(inputImage.c_str(), 0);
58 cout << "Could not read input image file: " << inputImage << endl;
62 namedWindow( "Image", 1 );
63 imshow( "Image", img );
65 namedWindow( "Connected Components", 1 );
66 createTrackbar( "Threshold", "Connected Components", &threshval, 255, on_trackbar );
67 on_trackbar(threshval, 0);