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