介绍OpenCV里的寻找连通器的api——
connectedComponents(src,connectivity=8,ltype=cv.CV_32S)
他会返回连通的数量和连通的标签数组:
def connected_components_demo():
src = cv.imread("D:/pythonTest/img/2.jpg")
cv.imshow("input",src)
src = cv.GaussianBlur(src,(3,3),0)
grey = cv.cvtColor(src,cv.COLOR_BGR2GRAY)
src = cv.adaptiveThreshold(grey, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 25, 5)
cv.imshow("output",src)
conn = cv.connectedComponents(src,connectivity=8,ltype=cv.CV_32S)
num_labels = conn[0]
labels = conn[1]
color = []
for i in range(num_labels):
b = np.random.randint(0,256)
g = np.random.randint(0, 256)
r = np.random.randint(0, 256)
color.append((b,g,r))
color[0] = (0,0,0)
h,w = src.shape
image = np.zeros((h,w,3),dtype=np.uint8)
for row in range (h):
for col in range(w):
image[row,col] = color[labels[row,col]]
cv.imshow("colored label",image)
这里,我们先将一个彩色图片进行高斯模糊、转成灰度图、进行二值化。然后用连通组件对新图像进行上色。运行结果如下:
下面介绍一个能返回更多信息的api
connectedComponentsWithStats()
他需要输入一个二值图,然后会返回这个图中的连通器的标签数量、标签、中点、左上起点、宽高以及面积,代码如下:
#下面的这个api会返回的信息更多
output_more = cv.connectedComponentsWithStats(src,connectivity=8,ltype=cv.CV_32S)
num_labels = output_more[0]
labels = output_more[1]
states = output_more[2]
centers = output_more[3]
image_states = cv.cvtColor(src,cv.COLOR_GRAY2BGR)
for i in range(num_labels):
if i==0:
continue
cx,cy = centers[i]
x,y,width,height,area = states[i]
print(area)
cv.rectangle(image_states,(x,y),(x+width,y+height),(0,0,255),2,8,0)
cv.circle(image_states,(np.int(cx),np.int(cy)),2,(255,0,0),-1,8,0)
cv.imshow("statistic",image_states)
于是我们就在图像上可以把每个连通器标出来: