Water's Home

Just another Life Style

0%

Segmenting image(The connected components & The findContours function)

Connected Components

void ConnectedComponents(Mat img)
{
// Use connected components to divide our possibles parts of images
Mat labels;
int num_objects= connectedComponents(img, labels);
// Check the number of objects detected
if(num_objects < 2 ){
cout << “No objects detected” << endl;
return;
}else{
cout << “Number of objects detected: “ << num_objects - 1 << endl;
}
// Create output image coloring the objects
Mat output= Mat::zeros(img.rows,img.cols, CV_8UC3);
RNG rng( 0xFFFFFFFF );
for(int i=1; iaddImage(“Result”, output);
}

void ConnectedComponentsStats(Mat img)
{
// Use connected components with stats
Mat labels, stats, centroids;
int num_objects= connectedComponentsWithStats(img, labels, stats, centroids);
// Check the number of objects detected
if(num_objects < 2 ){
cout << “No objects detected” << endl;
return;
}else{
cout << “Number of objects detected: “ << num_objects - 1 << endl;
}
// Create output image coloring the objects and show area
Mat output= Mat::zeros(img.rows,img.cols, CV_8UC3);
RNG rng( 0xFFFFFFFF );
for(int i=1; i(i) << “ with area “ << stats.at(i, CC_STAT_AREA) << endl;
Mat mask= labels==i;
output.setTo(randomColor(rng), mask);
// draw text with area
stringstream ss;
ss << “area: “ << stats.at(i, CC_STAT_AREA);

putText(output, 
  ss.str(), 
  centroids.at(i), 
  FONT\_HERSHEY\_SIMPLEX, 
  0.4, 
  Scalar(255,255,255));

}
imshow(“Result”, output);
miw->addImage(“Result”, output);
}

Find Contours Basic

void FindContoursBasic(Mat img)
{
vector > contours;
findContours(img, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
Mat output= Mat::zeros(img.rows,img.cols, CV_8UC3);
// Check the number of objects detected
if(contours.size() == 0 ){
cout << “No objects detected” << endl;
return;
}else{
cout << “Number of objects detected: “ << contours.size() << endl;
}
RNG rng( 0xFFFFFFFF );
for(int i=0; iaddImage(“Result”, output);
}