import cv2
import numpy as np
from skimage.morphology import skeletonize
from skimage.filters import threshold_otsu
from skimage.util import invert
import sknw
def split_skeleton_into_segments(img_path, out_path="segments.png"):
# 1) LOAD & THRESHOLD
img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
if img is None:
raise FileNotFoundError(f"cannot load {img_path!r}")
# Binarize (invert so lines → 1, bg → 0):
th = threshold_otsu(img)
bw = img > th
bw = invert(bw) # now curves/lines are True, background False
# 2) SKELETONIZE
skeleton = skeletonize(bw).astype(np.uint8)
# 3) BUILD A GRAPH FROM THE SKELETON
# nodes = junctions/endpoints; edges = the branches between them
graph = sknw.build_sknw(skeleton, multi=True)
# 4) PREPARE A BLANK COLOR CANVAS TO DRAW EACH SEGMENT IN A UNIQUE COLOR
h, w = skeleton.shape
canvas = np.zeros((h, w, 3), dtype=np.uint8)
# 5) ITERATE OVER EDGES (u,v,key,data) AND DRAW
for (u, v, key, data) in graph.edges(keys=True, data=True):
pts = data['pts'] # N×2 array of (row, col) along this branch
# convert to (x,y) for OpenCV and int32
pts_xy = np.fliplr(pts).reshape(-1, 1, 2).astype(np.int32)
# random color
color = tuple(int(c) for c in np.random.randint(50, 255, size=3))
# draw polyline
cv2.polylines(canvas, [pts_xy], isClosed=False, color=color, thickness=1)
# 6) SAVE RESULT
cv2.imwrite(out_path, canvas)
print(f"-> segments saved to {out_path}")
if __name__ == "__main__":
import sys
if len(sys.argv) != 2:
print("Usage: python split_segments.py input_image.png")
sys.exit(1)
split_skeleton_into_segments(sys.argv[1])
How it works step-by-step:
Binarize & invert so that your lines/curves become “True” pixels.
Skeletonize to thin everything to single‐pixel width.
sknw.build_sknw(…) builds a graph where:
nodes are endpoints or junction points
edges are the pixel‐lists (branches) connecting those nodes
For each edge, we fetch its data['pts'] (an N×2 array of skeleton coordinates), convert them to OpenCV-style (x,y) and draw a colored polyline.
We end up with a new image where each individual segment between intersections is drawn a unique color.