Python OpenCV how to remove space between lines

Viewed 808

I have this image:

enter image description here

And my goal is to separate the L-Shape as two different rectangles (the two who together make the L-Shape). With the long rectangle there is no problem because it is being detected as a contour. But with the wider rectangle it is a problem, because there is a space between two lines. Is there a solution for this matter?

I didn't write any code for it yet, so I cant post anything

Thanks in advance

2 Answers

Whenever performing image-processing with OpenCV, you want to have the desired manipulated objects in white with the background in black. In this case, since you want to modify the lines, the image first needs to be inverted so the lines are in white and the background in black. From here, we can construct a horizontal kernel and perform morphological closing to connect the lines together. Similarly, if you wanted to close spaces between vertical lines, you could perform the same steps with a vertical kernel.

Result

enter image description here

Code

import cv2

image = 255 - cv2.imread('1.png', 0)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (60,1))
result = 255 - cv2.morphologyEx(image, cv2.MORPH_CLOSE, kernel, iterations=1)

cv2.imshow('result', result)
cv2.waitKey()

If you want to use contour-based methods only, then you can try with erosion. Apply erosion to the image and with appropriate parameters, you can close the spacing at the cost of increasing the thickness of the lines, but I think that's ok for your case, since you are relying on contour extraction only. Try this:

kernel = np.ones((7,7), np.uint8)
eroded_im = cv2.erode(im, kernel, iterations=5 or 6)
Related