Search code examples
pythonopencvimage-processingconnected-componentslabeling

How to find end points of bw connected components?


I am using the following code for labeling the connected components in a binary image:

def connected_component(img): 
output = cv2.connectedComponentsWithStats(img, 8)
num_labels = output[0]
labels = output[1]
return labels, num_labels

I am calling it in the main as follows:

labels, num_labels = connected_component(seg_f)

I wish to find the end points of each connected component (given that the connected components are lines). I have tried to do it as follows but I am getting a wrong output:

cropped_max_y_1=[]
cropped_min_y_1=[]
cropped_max_x_1=[]
cropped_min_x_1=[]
seg_f, _ = ndimage.label(seg_f)
num_instances = np.max(np.max(seg_f))
for instance_id in range(1,num_instances+1):
im_inst = seg_f == instance_id
points = np.nonzero(im_inst)
cropped_min_x_1.append(np.min(points[0]))
cropped_min_y_1.append(np.min(points[1]))
cropped_max_x_1.append(np.max(points[0])+1)
cropped_max_y_1.append(np.max(points[1])+1)

Kindly suggest changes or an alternate approach to do the same.

Here is a sample input:

enter image description here

The expected output would be, say, coordinates of the joints


Solution

  • The endpoints are the only ones to have a single neighbor. You can easily check the configurations pixel per pixel.

    If you also need to detect the "quasi adjoining" forks, you can search around the endpoints for other pixels, but ignoring those of the same connected component.