Skip to content

Instantly share code, notes, and snippets.

@atinfinity
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atinfinity/e725e659b4bd68fb3fb4 to your computer and use it in GitHub Desktop.
Save atinfinity/e725e659b4bd68fb3fb4 to your computer and use it in GitHub Desktop.
ラベリングのサンプルプログラム
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>
#include <vector>
int main( int argc, const char** argv )
{
// source image
cv::Mat src = cv::imread("input.bmp", cv::IMREAD_GRAYSCALE);
// image thresholding
cv::Mat bin;
cv::threshold(src, bin, 0, 255, cv::THRESH_BINARY|cv::THRESH_OTSU);
// image for labeling
cv::Mat labelImage(src.size(), CV_32S);
int nLabels = cv::connectedComponents(bin, labelImage, 8);
// generate the color of label
std::vector<cv::Vec3b> colors(nLabels);
colors[0] = cv::Vec3b(0, 0, 0);
for(int label = 1; label < nLabels; ++label)
{
colors[label] = cv::Vec3b((rand()&255), (rand()&255), (rand()&255));
}
// draw labeled area
cv::Mat dst(src.size(), CV_8UC3);
for(int y = 0; y < dst.rows; ++y)
{
for(int x = 0; x < dst.cols; ++x)
{
int label = labelImage.at<int>(y, x);
cv::Vec3b &pixel = dst.at<cv::Vec3b>(y, x);
pixel = colors[label];
}
}
cv::namedWindow("Source", cv::WINDOW_AUTOSIZE );
cv::imshow("Source", src );
cv::namedWindow( "Connected Components", cv::WINDOW_AUTOSIZE );
cv::imshow( "Connected Components", dst );
cv::waitKey(0);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment