def Two_Pass(binary_img:np.array,neighbor_hoods):
"""
两次遍历计算连通域
:param binary_img:
:param neighbor_hoods:
:return:
"""
if neighbor_hoods == NEIGHBOR_HOODS_4:
offsets = OFFSETS_4
elif neighbor_hoods == NEIGHBOR_HOODS_8:
offsets = OFFSETS_8
else:
raise ValueError
binary_img = neighbor_value(binary_img,offsets)
binary_img = neighbor_value_2(binary_img,offsets)
return binary_img
def neighbor_value(binary_img:np.array,offsets):
"""
遍历计算连通域
:param binary_img:
:param offsets:
:param reverse:
:return:
"""
Rows = binary_img.shape[0]
Cols = binary_img.shape[1]
binary_img = np.array(binary_img,dtype=np.int)
label_idx = 0
Location = np.where(binary_img>0.5)
if len(Location)>0:
for i in range(len(Location[0])):
row = Location[0][i]
col = Location[1][i]
neighbor = binary_img[max(0,row-2):min(row+2,Rows),max(0,col-2):min(col+2,Cols)]
l_d = np.where(neighbor!=0)
neighbor_ = reduce(operator.add,[neighbor[l_d[0],l_d[1]]])
set_res = sorted(set(neighbor_))
if len(set_res) == 1:
label_idx += 1
if label_idx == 255:
label_idx += 1
binary_img[row][col] = label_idx
else:
if len(set_res) == 0:
print("")
if set_res[0] == 255:
binary_img[row][col] = set_res[1]
else:
binary_img[row][col] = set_res[0]
return binary_img
def neighbor_value_2(binary_img:np.array,offsets):
Rows = binary_img.shape[0]
Cols = binary_img.shape[1]
binary_img = np.array(binary_img,dtype=np.int)
Location = np.where(binary_img > 0.5)
if len(Location[0])>0:
for i in range(len(Location[0])-1,0,-1):
row = Location[0][i]
col = Location[1][i]
neighbor = binary_img[max(0,row-2):min(row+2,Rows),max(0,col-2):min(col+2,Cols)]
l_d = np.where(neighbor != 0)
if len(l_d[0]) == 1:
binary_img[row][col] = 0
continue
neighbor_ = reduce(operator.add, [neighbor[l_d[0], l_d[1]]])
set_res = sorted(set(neighbor_))
if len(set_res)>1:
binary_img[row][col] = set_res[0]
return binary_img
说明:输入的是二值图像0和255,用的是8邻域进行分析的。