What I need to do is go from a binary image like this:

to a segmented structure like this:

because I have a program that operates on those separated line contours after. As you see, those contours are not perfect, they might be slightly bent but where they meet it's always pretty much orthogonal, there are no 45 degree lines. The lines are between 3 and 20 pixels wide. The whole image is sometimes slightly rotated (less that 10 degrees) but if you find a solution that only works without rotation I could look into de-rotating stuff before. The inserted gap may be of any width (preferably 1px or 2px) as long as it entirely separates one line from another.

I thought one could do something like on page 15 of this paper (the description of what they do is on page 13). Essentially this would come down to finding one marker per line segment and then watershed, but I have no idea how to find that marker.

Just to be clear:

On any point of line intersection, this

is good, as well as this:

If easier to achieve,


is acceptable too, although not preferred.

What's not ok is this:

This is not only true for three-line t-sections but also two-line corner connections (= it doesn't matter which of the two lines meeting gets shortened).

Sorry for the huge pictures, didn't know how to prevent them from turning out this big.

I am working with python and cv2 so it would be a plus if you use that. On the other hand, even a link to a re-implementable algorithm or an idea how to find markers would be fine. Also, I'm looking for a fast and easy algorithm that works on binary (0 or 255) images, not any crazy machine-learning stuff (if avoidable). I have really time but lack the right idea. Thanks in advance.


2 Answers 2


A morphological closing with an horizontal structuring element of sufficient width will erase the vertical segments.

enter image description here

The you can erode them to make them thicker and erase them in white to obtain non-touching vertical segments.

enter image description here

enter image description here

enter image description here


Well, you could use convolutions to filter the crossings, the horizontal and the vertical lines separately. With these, you could choose the connectivity of which ones to preserve (without jumps).

Let's say you want to preserve the vertical lines. What you would need to do then is just erase the expanded crossings from the horizonal lines and finally add the vertical lines.

Don't got any code of this, but maybe this video will help you a bit: https://campus.datacamp.com/courses/biomedical-image-analysis-in-python/masks-and-filters?ex=8


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.