opencv-046-二值图像的联通组件寻找

知识点

连通组件标记算法介绍
连接组件标记算法(connected component labeling algorithm)是图像分析中最常用的算法之一,算法的实质是扫描二值图像的每个像素点,对于像素值相同的而且相互连通分为相同的组(group),最终得到图像中所有的像素连通组件。扫描的方式可以是从上到下,从左到右,对于一幅有N个像素的图像来说,最大连通组件个数为N/2。扫描是基于每个像素单位,OpenCV中进行连通组件扫码调用的时候必须保证背景像素是黑色、前景像素是白色。最常见的连通组件扫码有如下两类算法:

  1. 一步法,基于图的搜索算法
  2. 两步法、基于扫描与等价类合并算法

API

1
2
3
4
5
6
int cv::connectedComponents(
InputArray image, // 输入二值图像,黑色背景
OutputArray labels, // 输出的标记图像,背景index=0
int connectivity = 8, // 连通域,默认是8连通
int ltype = CV_32S // 输出的labels类型,默认是CV_32S
)

代码(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
#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

RNG rng(12345);

void connected_component_demo(Mat &image);

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

connected_component_demo(src);

waitKey(0);
return 0;
}

void connected_component_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);
int num_labels = connectedComponents(binary, labels, 8, CV_32S);
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 = Mat::zeros(image.size(), image.type());
for (int row = 0; row < image.rows; ++row) {
for (int col = 0; col < image.cols; ++col) {
int label = labels.at<int>(row, col);
if (label == 0) continue;
dst.at<Vec3b>(row, col) = colors[label];
}
}

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_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)

output = cv.connectedComponents(binary, connectivity=8, ltype=cv.CV_32S)
num_labels = output[0]
labels = output[1]
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)
h, w = gray.shape
image = np.zeros((h, w, 3), dtype=np.uint8)
for row in range(h):
for col in range(w):
image[row, col] = colors[labels[row, col]]

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


src = cv.imread("D:/images/rice.png")
h, w = src.shape[:2]
connected_components_demo(src)
cv.waitKey(0)
cv.destroyAllWindows()

结果

代码地址

github