-
Notifications
You must be signed in to change notification settings - Fork 903
/
example_14-03.cpp
55 lines (45 loc) · 1.63 KB
/
example_14-03.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Example 14-3. Drawing labeled connected components
#include <algorithm>
#include <iostream>
#include<opencv2/opencv.hpp>
using namespace std;
int main(int argc, char* argv[]) {
cv::Mat img, img_edge, labels, centroids, img_color, stats;
// load image or show help if no image was provided
if( (argc != 2)
|| (img = cv::imread( argv[1], cv::IMREAD_GRAYSCALE )).empty()
) {
cout << "\nERROR: You need 2 parameters, you had " << argc << "\n" << endl;
cout << "\nExample 14-3: Drawing labeled connected componnents\n"
<< "Call is:\n" <<argv[0] <<" <path/image>\n"
<< "\nExample:\n" << argv[0] << " ../HandIndoorColor.jpg\n" << endl;
return -1;
}
cv::threshold(img, img_edge, 128, 255, cv::THRESH_BINARY);
cv::imshow("Image after threshold", img_edge);
int i, nccomps = cv::connectedComponentsWithStats (
img_edge,
labels,
stats,
centroids
);
cout << "Total Connected Components Detected: " << nccomps << endl;
vector<cv::Vec3b> colors(nccomps+1);
colors[0] = cv::Vec3b(0,0,0); // background pixels remain black.
for( i = 1; i <= nccomps; i++ ) {
colors[i] = cv::Vec3b(rand()%256, rand()%256, rand()%256);
if( stats.at<int>(i-1, cv::CC_STAT_AREA) < 100 )
colors[i] = cv::Vec3b(0,0,0); // small regions are painted with black too.
}
img_color = cv::Mat::zeros(img.size(), CV_8UC3);
for( int y = 0; y < img_color.rows; y++ )
for( int x = 0; x < img_color.cols; x++ )
{
int label = labels.at<int>(y, x);
CV_Assert(0 <= label && label <= nccomps);
img_color.at<cv::Vec3b>(y, x) = colors[label];
}
cv::imshow("Labeled map", img_color);
cv::waitKey();
return 0;
}