opencv/samples/cpp/connected_components.cpp

74 lines
2.0 KiB
C++
Raw Normal View History

#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
2010-11-24 06:51:04 +01:00
#include <iostream>
using namespace cv;
using namespace std;
Mat img;
int threshval = 100;
2012-06-07 19:21:29 +02:00
static void on_trackbar(int, void*)
{
2012-06-07 19:21:29 +02:00
Mat bw = threshval < 128 ? (img < threshval) : (img > threshval);
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
2012-06-07 19:21:29 +02:00
findContours( bw, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE );
2012-06-07 19:21:29 +02:00
Mat dst = Mat::zeros(img.size(), CV_8UC3);
2011-04-29 12:34:54 +02:00
if( !contours.empty() && !hierarchy.empty() )
{
// iterate through all the top-level contours,
// draw each connected component with its own random color
int idx = 0;
for( ; idx >= 0; idx = hierarchy[idx][0] )
{
Scalar color( (rand()&255), (rand()&255), (rand()&255) );
drawContours( dst, contours, idx, color, CV_FILLED, 8, hierarchy );
}
}
2012-06-07 19:21:29 +02:00
imshow( "Connected Components", dst );
}
2012-06-07 19:21:29 +02:00
static void help()
2011-08-10 13:29:32 +02:00
{
2011-08-10 13:49:10 +02:00
cout << "\n This program demonstrates connected components and use of the trackbar\n"
2012-06-07 19:21:29 +02:00
"Usage: \n"
" ./connected_components <image(stuff.jpg as default)>\n"
"The image is converted to grayscale and displayed, another image has a trackbar\n"
2011-08-10 13:49:10 +02:00
"that controls thresholding and thereby the extracted contours which are drawn in color\n";
2011-08-10 13:29:32 +02:00
}
2012-06-07 19:21:29 +02:00
const char* keys =
{
"{@image |stuff.jpg|image for converting to a grayscale}"
2011-08-10 13:29:32 +02:00
};
int main( int argc, const char** argv )
{
2012-06-07 19:21:29 +02:00
help();
CommandLineParser parser(argc, argv, keys);
string inputImage = parser.get<string>(1);
2012-06-07 19:21:29 +02:00
img = imread(inputImage.c_str(), 0);
2011-08-10 13:29:32 +02:00
2012-06-07 19:21:29 +02:00
if(img.empty())
{
2011-08-10 13:49:10 +02:00
cout << "Could not read input image file: " << inputImage << endl;
2012-06-07 19:21:29 +02:00
return -1;
}
2012-06-07 19:21:29 +02:00
namedWindow( "Image", 1 );
imshow( "Image", img );
2012-06-07 19:21:29 +02:00
namedWindow( "Connected Components", 1 );
createTrackbar( "Threshold", "Connected Components", &threshval, 255, on_trackbar );
on_trackbar(threshval, 0);
waitKey(0);
return 0;
}