Extract horizontal and vertical lines from an image

2.3k Views Asked by At

I want to extract horizontal and vertical lines in 2 masks for the attached image.

I have tried morphological operations to do this,

horizontalStructure = cv.getStructuringElement(cv.MORPH_RECT, (horizontal_size, 1))
verticalStructure = cv.getStructuringElement(cv.MORPH_RECT, (1, verticalsize))

But the problem, It detects the line as a rectangle and then draws it in a form of 2 lines representing the 2 sides of the rectangle.

Any ideas to fix that?

The image:
img

The horizontal result:

h

The vertical result:

v


EDIT: That's another image I have:

img

1

There are 1 best solutions below

2
HansHirse On

What did you do with your structuring elements? Where's the rest of your code?

I'd suggest to use morphological opening using cv2.morphologyEx, like so:

import cv2
import numpy as np
from skimage import io              # Only needed for web reading images

# Web read image; use cv2.imread(...) for local images
img = cv2.cvtColor(io.imread('https://i.stack.imgur.com/jnCvG.jpg'), cv2.COLOR_RGB2GRAY)

# Get rid of JPG artifacts
img = cv2.threshold(img, 128, 255, cv2.THRESH_BINARY)[1]

# Create structuring elements
horizontal_size = 11
vertical_size = 11
horizontalStructure = cv2.getStructuringElement(cv2.MORPH_RECT, (horizontal_size, 1))
verticalStructure = cv2.getStructuringElement(cv2.MORPH_RECT, (1, vertical_size))

# Morphological opening
mask1 = cv2.morphologyEx(img, cv2.MORPH_OPEN, horizontalStructure)
mask2 = cv2.morphologyEx(img, cv2.MORPH_OPEN, verticalStructure)

# Outputs
cv2.imshow('img', img)
cv2.imshow('mask1', mask1)
cv2.imshow('mask2', mask2)
cv2.waitKey(0)
cv2.destroyAllWindows()

I get the following two masks, which look quite good to me:

Mask 1

Mask 2

Hope that helps!

----------------------------------------
System information
----------------------------------------
Platform:    Windows-10-10.0.16299-SP0
Python:      3.8.1
NumPy:       1.18.1
OpenCV:      4.2.0
----------------------------------------