Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Line and Square removal using getStructuringElement and morphologyEx

I would like to remove horizontal and vertical lines from image contains text. My approach is to use getStructuringElement then pass it to cv2.morphologyEx.

This Approach works fine when the ksize is correctly set. Here comes the problem how to get the correct ksize for specific image and set it dynamically.

Here are two examples :
This image works fine when ksize is set to (4,3)

cv2.getStructuringElement(cv2.MORPH_ELLIPSE , (4,3))

enter image description here



works fine when ksize is set to (5,4)
enter image description here

What is the equation controlling ksize. I checked out the documentation but not m Here the code used:

import numpy as np

import cv2



gray = cv2.imread('top.png')

edges = cv2.Canny(gray,50,150,apertureSize = 3)

minLineLength=100

lines = cv2.HoughLinesP(image=edges,rho=1,theta=np.pi/180, threshold=100,lines=np.array([]), minLineLength=minLineLength,maxLineGap=80)



a,b,c = lines.shape

for i in range(a):

    x = lines[i][0][0] - lines [i][0][2]

    y = lines[i][0][1] - lines [i][0][3]

    if x!= 0:

        if abs(y/x) <1:

            cv2.line(gray, (lines[i][0][0], lines[i][0][1]), (lines[i][0][2], lines[i][0][3]), (255, 255, 255), 1, cv2.LINE_AA)



se = cv2.getStructuringElement(cv2.MORPH_ELLIPSE , (5,4))

gray = cv2.morphologyEx(gray, cv2.MORPH_CLOSE, se)

img = cv2.fastNlMeansDenoising(gray, None, 65, 5, 21)

img = cv2.threshold(img, 128, 255, cv2.THRESH_BINARY_INV)[1]

img = cv2.bitwise_not(img)

k1 = np.zeros((3, 3), np.uint8)

img = cv2.erode(img, k1, iterations = 1)