OpenCV  4.10.0-dev
Open Source Computer Vision
No Matches

This program demonstrates connected components and use of the trackbar

#include <iostream>
using namespace cv;
using namespace std;
Mat img;
int threshval = 100;
static void on_trackbar(int, void*)
Mat bw = threshval < 128 ? (img < threshval) : (img > threshval);
Mat labelImage(img.size(), CV_32S);
int nLabels = connectedComponents(bw, labelImage, 8);
std::vector<Vec3b> colors(nLabels);
colors[0] = Vec3b(0, 0, 0);//background
for(int label = 1; label < nLabels; ++label){
colors[label] = Vec3b( (rand()&255), (rand()&255), (rand()&255) );
Mat dst(img.size(), CV_8UC3);
for(int r = 0; r < dst.rows; ++r){
for(int c = 0; c < dst.cols; ++c){
int label =<int>(r, c);
Vec3b &pixel =<Vec3b>(r, c);
pixel = colors[label];
imshow( "Connected Components", dst );
int main( int argc, const char** argv )
CommandLineParser parser(argc, argv, "{@image|stuff.jpg|image for converting to a grayscale}");
parser.about("\nThis program demonstrates connected components and use of the trackbar\n");
cout << "\nThe image is converted to grayscale and displayed, another image has a trackbar\n"
"that controls thresholding and thereby the extracted contours which are drawn in color\n";
String inputImage = parser.get<string>(0);
img = imread(samples::findFile(inputImage), IMREAD_GRAYSCALE);
cout << "Could not read input image file: " << inputImage << endl;
imshow( "Image", img );
namedWindow( "Connected Components", WINDOW_AUTOSIZE);
createTrackbar( "Threshold", "Connected Components", &threshval, 255, on_trackbar );
on_trackbar(threshval, 0);
Designed for command line parsing.
Definition utility.hpp:820
n-dimensional dense array class
Definition mat.hpp:812
MatSize size
Definition mat.hpp:2160
_Tp & at(int i0=0)
Returns a reference to the specified array element.
int cols
Definition mat.hpp:2138
int rows
the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions
Definition mat.hpp:2138
Template class for short numerical vectors, a partial case of Matx.
Definition matx.hpp:369
std::string String
Definition cvstd.hpp:151
#define CV_32S
Definition interface.h:77
#define CV_8UC3
Definition interface.h:90
void imshow(const String &winname, InputArray mat)
Displays an image in the specified window.
int waitKey(int delay=0)
Waits for a pressed key.
void namedWindow(const String &winname, int flags=WINDOW_AUTOSIZE)
Creates a window.
int createTrackbar(const String &trackbarname, const String &winname, int *value, int count, TrackbarCallback onChange=0, void *userdata=0)
Creates a trackbar and attaches it to the specified window.
int main(int argc, char *argv[])
Definition highgui_qt.cpp:3
"black box" representation of the file storage associated with a file on disk.
Definition core.hpp:102
STL namespace.