opencv-047-二值图像连通组件状态统计

知识点

OpenCV中的连通组件标记算法有两个相关的API:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
一个是不带统计信息的API
int cv::connectedComponents(
InputArray image, // 输入二值图像,黑色背景
OutputArray labels, // 输出的标记图像,背景index=0
int connectivity = 8, // 连通域,默认是8连通
int ltype = CV_32S // 输出的labels类型,默认是CV_32S
)
另外一个是会输出连通组件统计信息的相关API,
int cv::connectedComponentsWithStats(
InputArray image,
OutputArray labels,
OutputArray stats,
OutputArray centroids,
int connectivity,
int ltype,
int ccltype
)
相关的统计信息包括在输出stats的对象中,每个连通组件有一个这样的输出结构体。
CC_STAT_LEFT
Python: cv.CC_STAT_LEFT
连通组件外接矩形左上角坐标的X位置信息

CC_STAT_TOP
Python: cv.CC_STAT_TOP
连通组件外接左上角坐标的Y位置信息

CC_STAT_WIDTH
Python: cv.CC_STAT_WIDTH
连通组件外接矩形宽度

CC_STAT_HEIGHT
Python: cv.CC_STAT_HEIGHT
连通组件外接矩形高度

CC_STAT_AREA
Python: cv.CC_STAT_AREA
连通组件的面积大小,基于像素多少统计。

Centroids输出的是每个连通组件的中心位置坐标(x, y)

代码(c++,python)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

RNG rng(12345);

void componentwithstats_demo(Mat &image);

/*
* 二值图像连通组件状态统计
*/
int main() {
Mat src = imread("../images/rice.png");
if (src.empty()) {
cout << "could not load image.." << endl;
}
imshow("input", src);

componentwithstats_demo(src);

waitKey(0);
return 0;
}

void componentwithstats_demo(Mat &image) {
// extract labels
Mat gray, binary;
GaussianBlur(image, image, Size(3, 3), 0);
cvtColor(image, gray, COLOR_BGR2GRAY);
threshold(gray, binary, 0, 255, THRESH_BINARY | THRESH_OTSU);
Mat labels = Mat::zeros(image.size(), CV_32S);
Mat stats, centroids;
int num_labels = connectedComponentsWithStats(binary, labels, stats, centroids, 8, 4);
cout << "total labels : " << num_labels - 1 << endl;
vector<Vec3b> colors(num_labels);

// 背景颜色
colors[0] = Vec3b(0, 0, 0);

// 目标颜色
for (int i = 1; i < num_labels; ++i) {
colors[i] = Vec3b(rng.uniform(0, 256), rng.uniform(0, 256), rng.uniform(0, 256));
}

// 抽取统计信息
Mat dst = image.clone();
for (int i = 1; i < num_labels; ++i) {
// 中心位置
int cx = centroids.at<double>(i, 0);
int cy = centroids.at<double>(i, 1);

// 统计信息
int x = stats.at<int>(i, CC_STAT_LEFT);
int y = stats.at<int>(i, CC_STAT_TOP);
int w = stats.at<int>(i, CC_STAT_WIDTH);
int h = stats.at<int>(i, CC_STAT_HEIGHT);
int area = stats.at<int>(i, CC_STAT_AREA);

// 中心位置绘制
circle(dst, Point(cx, cy), 2, Scalar(0, 255, 0), 2);

// 外接矩形
Rect rect(x, y, w, h);
rectangle(dst, rect, colors[i]);
putText(dst, format("num:%d", i), Point(x, y), FONT_HERSHEY_SIMPLEX,
.5, Scalar(0, 0, 255), 1);
printf("num : %d, rice area : %d\n", i, area);
}

imshow("result", dst);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import cv2 as cv
import numpy as np


def connected_components_stats_demo(src):
src = cv.GaussianBlur(src, (3, 3), 0)
gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)
cv.imshow("binary", binary)

num_labels, labels, stats, centers = cv.connectedComponentsWithStats(binary, connectivity=8, ltype=cv.CV_32S)
colors = []
for i in range(num_labels):
b = np.random.randint(0, 256)
g = np.random.randint(0, 256)
r = np.random.randint(0, 256)
colors.append((b, g, r))

colors[0] = (0, 0, 0)
image = np.copy(src)
for t in range(1, num_labels, 1):
x, y, w, h, area = stats[t]
cx, cy = centers[t]
cv.circle(image, (np.int32(cx), np.int32(cy)), 2, (0, 255, 0), 2, 8, 0)
cv.rectangle(image, (x, y), (x+w, y+h), colors[t], 1, 8, 0)
cv.putText(image, "num:" + str(t), (x, y), cv.FONT_HERSHEY_SIMPLEX, .5, (0, 0, 255), 1);
print("label index %d, area of the label : %d"%(t, area))

cv.imshow("colored labels", image)
cv.imwrite("D:/labels.png", image)
print("total rice : ", num_labels - 1)


input = cv.imread("D:/images/rice.png")
connected_components_stats_demo(input)
cv.waitKey(0)
cv.destroyAllWindows()

结果

代码地址

github