本文旨在优化道路连通性算法,gt为影像通过语义分割或者其他算法得到的道路直接测试结果,但这类结果往往效果较差,道路断断续续,所以有必要对道路进行连通性增强,算法如下:
from sknw import build_sknw
from skimage.morphology import skeletonize
import cv2
def patch_regular(gt,tau,thickness):
#gt=tifffile.imread(img_path)
ske = skeletonize(gt).astype(np.uint16)
graph = build_sknw(ske)
points=[]
nodes=set()
# draw edges by pts
for (s,e) in graph.edges():
ps = graph[s][e]['pts']
p1=[float(ps[0,0]),float(ps[0,1])]
p2=[float(ps[-1,0]),float(ps[-1,1])]
nodes.add(str(p1))
nodes.add(str(p2))
points.append({str(p1),str(p2)})
for i in range(0,len(ps)-1):
cv2.line(gt,(int(ps[i,1]),int(ps[i,0])), (int(ps[i+1,1]),int(ps[i+1,0])), 1,thickness=thickness)
ps=[eval(i) for i in list(nodes)]
for num in range(len(ps)):
mindis=float("inf")
for other in range(len(ps)):
if other!=num and {str(ps[num]),str(ps[other])} not in points:
dis= distance(ps[num],ps[other])
if dis<mindis:
mindis=dis
mindis_point=other
if mindis<tau:
cv2.line(gt,(int(ps[num][1]),int(ps[num][0])), (int(ps[mindis_point][1]),int(ps[mindis_point][0])), 1,thickness=thickness)
return gt
其中sknw库来自于https://github.com/Image-Py/sknw。
效果图(上:原图,下:连通性增强后):