0%

二值图像的连通分量提取

把二值图像中的较小的连通分量去掉, 只保留最大的前两个分量, 将结果保存成文件.

参考自https://www.cnblogs.com/er-gou-zi/p/11985633.html

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
import cv2
import numpy as np

img = cv2.imread('./img_24bit.bmp', 0)
thresh = cv2.threshold(img, 25, 255, cv2.THRESH_BINARY)[1]
cv2.imwrite('./thresh.bmp', thresh)

thresh_copy = thresh.copy()

kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))

# 最大的前两个分量
max_2_count = []
max_2_thresh = []

# 检测到的第几个连通分量
index = 0

while thresh_copy.any():
# 准备检测连通分量, 使用全黑的二值图像
print('第{}个连通分量'.format(index))
thresh_black = np.zeros(img.shape, np.uint8)

X_copy, Y_copy = np.where(thresh_copy > 0)
thresh_black[X_copy[0]][Y_copy[0]] = 255

# 连通分量算法, 设置迭代次数, 次数越多检测越充分
for i in range(2000):
dilation_black = cv2.dilate(thresh_black, kernel, iterations=1)
thresh_black = cv2.bitwise_and(thresh, dilation_black)

X_black, Y_black = np.where(thresh_black > 0)
thresh_copy[X_black, Y_black] = 0

if index > 1:
if len(X_black) > min(max_2_count):
min_index = max_2_count.index(min(max_2_count))
max_2_count[min_index] = len(X_black)
max_2_thresh[min_index] = thresh_black
else:
max_2_count.append(len(X_black))
max_2_thresh.append(thresh_black)
index += 1

# 将最后的得到的两个最大的连通分量合并
thresh_res = cv2.bitwise_or(max_2_thresh[0], max_2_thresh[1])
cv2.imwrite('./max_2_thresh.bmp', thresh_res)
Thank you for your reward !