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.        ]]
"""
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容