Search code examples
pythonopencvimage-processinglinecontour

Python OpenCV how to remove space between lines


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


Solution

  • 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()