opencv/samples/cpp/connected_components.cpp

62 lines
1.9 KiB
C++
Raw Normal View History

2018-08-03 02:22:58 +08:00
#include <opencv2/core/utility.hpp>
#include "opencv2/imgproc.hpp"
2014-07-04 22:48:15 +08:00
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
2010-11-24 13:51:04 +08:00
#include <iostream>
using namespace cv;
using namespace std;
Mat img;
int threshval = 100;
2012-06-08 01:21:29 +08:00
static void on_trackbar(int, void*)
{
2012-06-08 01:21:29 +08:00
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 = labelImage.at<int>(r, c);
Vec3b &pixel = dst.at<Vec3b>(r, c);
pixel = colors[label];
}
}
2012-06-08 01:21:29 +08:00
imshow( "Connected Components", dst );
}
2011-08-10 19:29:32 +08:00
int main( int argc, const char** argv )
{
2018-08-03 02:22:58 +08:00
CommandLineParser parser(argc, argv, "{@image|../data/stuff.jpg|image for converting to a grayscale}");
parser.about("\nThis program demonstrates connected components and use of the trackbar\n");
parser.printMessage();
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(inputImage, IMREAD_GRAYSCALE);
2011-08-10 19:29:32 +08:00
2012-06-08 01:21:29 +08:00
if(img.empty())
{
2011-08-10 19:49:10 +08:00
cout << "Could not read input image file: " << inputImage << endl;
2018-08-03 02:22:58 +08:00
return EXIT_FAILURE;
2012-06-08 01:21:29 +08:00
}
imshow( "Image", img );
2018-08-03 02:22:58 +08:00
namedWindow( "Connected Components", WINDOW_AUTOSIZE);
2012-06-08 01:21:29 +08:00
createTrackbar( "Threshold", "Connected Components", &threshval, 255, on_trackbar );
on_trackbar(threshval, 0);
waitKey(0);
2018-08-03 02:22:58 +08:00
return EXIT_SUCCESS;
}