OpenCV_連通區域分析2 代碼實現


參考博客: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. ]]
"""

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM