OpenCV+Python图像连通域

connectedComponents

ret, labels = cv2.connectedComponents(gray_img, connectivity=None)
# connectivity 4或8 临近像素: 周围4像素或8像素
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)
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]]
"""

connectedComponentsWithStats

_, labels, stats, centroids = cv2.connectedComponentsWithStats(img)
# stats 是bounding box的信息,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.        ]]
"""

你可能感兴趣的:(OpenCV+Python图像连通域)