方法1
cv::Mat backMask2;
cv::Mat stats2;
cv::Mat centroids2;
cv::connectedComponentsWithStats(backMask, backMask2, stats2, centroids2, 8, CV_32S);
int maxArea = 0;
int maxIndex = 0;
for (int i = 1; i < stats2.rows; ++i)
{int area = stats2.at<int>(i, cv::CC_STAT_AREA);if (area > maxArea){maxArea = area;maxIndex = i;}
}
backMask = backMask2 == maxIndex;
cv::imshow("backMask2", backMask);
cv::waitKey();
方法2
bool cvGetMaxConnectedComponents(const cv::Mat& input_img, cv::Mat& out_img)
{cv::Mat temp;cv::Mat labels;input_img.copyTo(temp);int n_comps = connectedComponents(temp, labels, 4, CV_16U);std::vector<int> histogram_of_labels;for (int i = 0; i < n_comps; i++){histogram_of_labels.push_back(0);}int rows = labels.rows;int cols = labels.cols;for (int row = 0; row < rows; row++) {for (int col = 0; col < cols; col++){histogram_of_labels.at(labels.at<unsigned short>(row, col)) += 1;}}histogram_of_labels.at(0) = 0; int maximum = 0;int max_idx = 0;for (int i = 0; i < n_comps; i++){if (histogram_of_labels.at(i) > maximum){maximum = histogram_of_labels.at(i);max_idx = i;}}for (int row = 0; row < rows; row++){for (int col = 0; col < cols; col++){if (labels.at<unsigned short>(row, col) == max_idx){labels.at<unsigned short>(row, col) = 255;}else{labels.at<unsigned short>(row, col) = 0;}}}labels.convertTo(out_img, CV_8U);return true;
}