cv::connectedComponents()
int nccomps=connectedComponents (
cv::InputArrayn image,
cv::OutputArray labels,
int connectivity = 8,
int ltype = CV_32S );
函数返回值nccomps为int型,表示连通域个数;
- image: 输入图像(8-bit,单通道图像)
- lables: 生成的标记图,部分截图如下图所示,labelsde 尺寸和输入图像大小相等
- connetivity: 表示4或8邻域连接(int型)
- ltype: 表示输出标记图的类型(CV_32S,CV_16U)
cv::connectedComponentsWithStats()函数
int nccomps=connectedComponentsWithStats (
cv::InputArrayn image,
cv::OutputArray labels,
cv::OutputArray stats,
cv::OutputArray centroids,
int connectivity = 8,
int ltype= CV_32S
);
相比connectedComponents()
函数增加了一下重要信息,包围框(bounding box)、面积和质心。
- image: 输入图像(8-bit,单通道图像)
- lables: 生成的标记图,部分截图如下图所示,labelsde 尺寸和输入图像大小相等
- star:一个5*nccomps的矩阵,分别对应各个轮廓的x,y,width,height和面积
- centroids:一个2*nccomps的矩阵,表示每个连通域的质心
- connetivity: 表示4或8邻域连接(int型)
- ltype: 表示输出标记图的类型(CV_32S,CV_16U)
label示意图:
state示意图:
功能源码:
int main()
{
Mat img, img_edge, labels, centroids, img_color, stats;
img = imread("图片路径", 0);
threshold(img, img_edge, 0, 255, THRESH_OTSU); // 大津法二值化图像
int nccomps = connectedComponentsWithStats(img_edge, labels, stats, centroids);
cout << "连通域个数: " << nccomps << endl;
vector<Vec3b>colors (nccomps + 1);;
colors[0] = Vec3b(0, 0, 0);
for (int i = 1; i <= nccomps; i++)
{
colors[i] = Vec3b(rand() % 256, rand() % 256, rand() % 256);
if (stats.at<int>(i, CC_STAT_AREA) < 2500) // 连通区域面积小于2500被设为黑色(填充)
/*
关于CC_STAT_AREA:
是ConnectedComponentsTypes的结构体属性,除AREA还有:
CC_STAT_LEFT = 0, 表示连通区域边界x坐标
CC_STAT_TOP = 1, 表示连通区域边界y坐标
CC_STAT_WIDTH = 2, 表示连通区域的宽
CC_STAT_HEIGHT = 3, 表示连通区域的高
CC_STAT_AREA = 4, 表示连通区域的面积
CC_STAT_MAX = 5
*/
colors[i] = Vec3b(0, 0, 0);
cout << stats.at<int>(i - 1, CC_STAT_AREA) << endl;//连通域的面积
}
img_color = Mat::zeros(img.size(), CV_8UC3);
for (int y = 0; y < img_color.rows; y++)
for (int x = 0; x < img_color.cols; x++)
{
int label = labels.at<int>(y, x);
CV_Assert(0 <= label && label <= nccomps);
img_color.at<Vec3b>(y, x) = colors[label];
}
imshow("Labeled map", img_color);
imshow("img", img);
waitKey();
return 0;
}
效果图