Path: blob/master/samples/cpp/connected_components.cpp
16337 views
1#include <opencv2/core/utility.hpp>2#include "opencv2/imgproc.hpp"3#include "opencv2/imgcodecs.hpp"4#include "opencv2/highgui.hpp"5#include <iostream>67using namespace cv;8using namespace std;910Mat img;11int threshval = 100;1213static void on_trackbar(int, void*)14{15Mat bw = threshval < 128 ? (img < threshval) : (img > threshval);16Mat labelImage(img.size(), CV_32S);17int nLabels = connectedComponents(bw, labelImage, 8);18std::vector<Vec3b> colors(nLabels);19colors[0] = Vec3b(0, 0, 0);//background20for(int label = 1; label < nLabels; ++label){21colors[label] = Vec3b( (rand()&255), (rand()&255), (rand()&255) );22}23Mat dst(img.size(), CV_8UC3);24for(int r = 0; r < dst.rows; ++r){25for(int c = 0; c < dst.cols; ++c){26int label = labelImage.at<int>(r, c);27Vec3b &pixel = dst.at<Vec3b>(r, c);28pixel = colors[label];29}30}3132imshow( "Connected Components", dst );33}3435int main( int argc, const char** argv )36{37CommandLineParser parser(argc, argv, "{@image|../data/stuff.jpg|image for converting to a grayscale}");38parser.about("\nThis program demonstrates connected components and use of the trackbar\n");39parser.printMessage();40cout << "\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";4243String inputImage = parser.get<string>(0);44img = imread(inputImage, IMREAD_GRAYSCALE);4546if(img.empty())47{48cout << "Could not read input image file: " << inputImage << endl;49return EXIT_FAILURE;50}5152imshow( "Image", img );5354namedWindow( "Connected Components", WINDOW_AUTOSIZE);55createTrackbar( "Threshold", "Connected Components", &threshval, 255, on_trackbar );56on_trackbar(threshval, 0);5758waitKey(0);59return EXIT_SUCCESS;60}616263