参考博客:https://www.jianshu.com/p/a9cc11af270c
1.connectedComponents
用法:
ret, labels = cv2.connectedComponents(gray_img, connectivity=None)
# connectivity 4或8 临近像素: 周围4像素或8像素
案例import cvimport numpy as np
img = np.array([
[0, 255, 0, 0],
[0, 0, 0, 255],
[0, 0, 0, 255],
[255, 0, 0, 0]
], np.uint8)
_, labels = cv2.connectedComponents(img)
print(labels)
res = cv2.equalizeHist(cv2.convertScaleAbs(labels))
print(res)
结果:
"""
[[0 1 0 0]
[0 0 0 2]
[0 0 0 2]
[3 0 0 0]]
[[ 0 64 0 0]
[ 0 0 0 191]
[ 0 0 0 191]
[255 0 0 0]]
"""
2.connectedComponentsWithStats
用法:
_, labels, stats, centroids = cv2.connectedComponentsWithStats(img)
# stats N*5的矩阵,行对应每个label,五列分别为[x0, y0, width, height, area] # centroids 是每个域的质心坐标
样例:
import cv2
import numpy as np
img = np.array([
[0, 255, 0, 0],
[0, 0, 0, 255],
[0, 0, 0, 255],
[255, 0, 0, 0]
], np.uint8)
_, labels = cv2.connectedComponents(img)
# print(labels)
_, labels, stats, centroids = cv2.connectedComponentsWithStats(img)
print(labels)
print(stats)
print(centroids)
结果:
"""
[[0 1 0 0]
[0 0 0 2]
[0 0 0 2]
[3 0 0 0]]
[[ 0 0 4 4 12]
[ 1 0 1 1 1]
[ 3 1 1 2 2]
[ 0 3 1 1 1]]
[[1.41666667 1.5 ]
[1. 0. ]
[3. 1.5 ]
[0. 3. ]]
"""