void LargestConnecttedComponent(Mat srcImage, Mat &dstImage) {
Mat temp;
Mat labels;
srcImage.copyTo(temp);
//1. 标记连通域
int n_comps = connectedComponents(temp, labels, 4, CV_16U);
vector<int> histogram_of_labels;
for(int i = 0; i < n_comps; i++) { //初始化labels的个数为0
histogram_of_labels.push_back(0);
}
int rows = labels.rows;
int cols = labels.cols;
for(int row = 0; row < rows; row++) { //计算每个labels的个数
for(int col = 0; col < cols; col++) {
histogram_of_labels.at(labels.at<unsigned short>(row, col)) += 1;
}
}
histogram_of_labels.at(0) = 0; //将背景的labels个数设置为0
//2. 计算最大的连通域labels索引
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;
}
}
//3. 将最大连通域标记为1
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;
}
}
}
//4. 将图像更改为CV_8U格式
labels.convertTo(dstImage, CV_8U);
}
opencv-最大连通域
猜你喜欢
转载自blog.csdn.net/weixin_44723106/article/details/105405523
今日推荐
周排行