Merge pull request #3038 from yury-gorbachev:core_arithm_neon
[profile/ivi/opencv.git] / samples / cpp / connected_components.cpp
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
7 using namespace cv;
8 using namespace std;
9
10 Mat img;
11 int threshval = 100;
12
13 static 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
35 static void help()
36 {
37     cout << "\n This program demonstrates connected components and use of the trackbar\n"
38              "Usage: \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";
42 }
43
44 const char* keys =
45 {
46     "{@image|stuff.jpg|image for converting to a grayscale}"
47 };
48
49 int main( int argc, const char** argv )
50 {
51     help();
52     CommandLineParser parser(argc, argv, keys);
53     string inputImage = parser.get<string>(0);
54     img = imread(inputImage.c_str(), 0);
55
56     if(img.empty())
57     {
58         cout << "Could not read input image file: " << inputImage << endl;
59         return -1;
60     }
61
62     namedWindow( "Image", 1 );
63     imshow( "Image", img );
64
65     namedWindow( "Connected Components", 1 );
66     createTrackbar( "Threshold", "Connected Components", &threshval, 255, on_trackbar );
67     on_trackbar(threshval, 0);
68
69     waitKey(0);
70     return 0;
71 }