'Join broken lines in image using OpenCV for python

I am working on a project in which I have to complete the broken lines in the image below and then calculate the area. Is there any way to complete the broken lines in the image below using python?

Image with broken lines



Solution 1:[1]

Do you mean something like this?

result image

This can be done with simple morphology; however, it is subject to two conditions:

  1. You only have horizontal and vertical lines
  2. The gaps you want to fill are strictly smaller than gaps you want to preserve (empty space in the image)
import matplotlib.pyplot as plt
import numpy as numpy

from skimage import io
from skimage import morphology

img = io.imread("test.png", as_gray=True)

# fill horizontal gaps
selem_horizontal = morphology.rectangle(1,50)
img_filtered = morphology.closing(img, selem_horizontal)

# fill vertical gaps
selem_vertical = morphology.rectangle(80,1)
img_filtered = morphology.closing(img_filtered, selem_vertical)

plt.imshow(img_filtered, cmap="gray")
plt.gca().axis("off")
plt.show()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 FirefoxMetzger