Complete missing lines in table opencv

Question:

I am trying to detect cells in bill image:

I have this image enter image description here

Removed the stamp with this code:

import cv2
import numpy as np

# read image
img = cv2.imread('dummy1.PNG')

# threshold on yellow
lower = (0, 200, 200)
upper = (100, 255, 255)
thresh = cv2.inRange(img, lower, upper)

# apply dilate morphology
kernel = np.ones((9, 9), np.uint8)
mask = cv2.morphologyEx(thresh, cv2.MORPH_DILATE, kernel)

# get largest contour
contours = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
big_contour = max(contours, key=cv2.contourArea)
x, y, w, h = cv2.boundingRect(big_contour)

# draw filled white contour on input
result = img.copy()
cv2.drawContours(result, [big_contour], 0, (255, 255, 255), -1)


cv2.imwrite('removed.png', result)

# show the images
cv2.imshow("RESULT", result)
cv2.waitKey(0)
cv2.destroyAllWindows()

And obtained this image:
enter image description here

Then applied grayscale, inverted, detected vertical and horizontal kernel and merged through this main.py :

# Imports
import cv2
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import csv

try:
    from PIL import Image
except ImportError:
    import Image
import pytesseract

pytesseract.pytesseract.tesseract_cmd = r'C:Program FilesTesseract-OCRtesseract.exe'
#################################################################################################


# Read your file
file = 'removed.png'
img = cv2.imread(file, 0)
img.shape


# thresholding the image to a binary image
thresh, img_bin = cv2.threshold(img, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)

# inverting the image
img_bin = 255 - img_bin
cv2.imwrite(r'C:UsersmarouDesktopcv_inverted.png', img_bin)

# Plotting the image to see the output
plotting = plt.imshow(img_bin, cmap='gray')
plt.show()

# Define a kernel to detect rectangular boxes

# Length(width) of kernel as 100th of total width
kernel_len = np.array(img).shape[1] // 100
# Defining a vertical kernel to detect all vertical lines of image
ver_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, kernel_len))
# Defining a horizontal kernel to detect all horizontal lines of image
hor_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (kernel_len, 1))
# A kernel of 2x2
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 2))

#### Vertical LINES ####
# Use vertical kernel to detect and save the vertical lines in a jpg
image_1 = cv2.erode(img_bin, ver_kernel, iterations=5)
vertical_lines = cv2.dilate(image_1, ver_kernel, iterations=5)
cv2.imwrite(r'C:UsersmarouDesktopvertical.jpg', vertical_lines)
# Plot the generated image
plotting = plt.imshow(image_1, cmap='gray')
plt.show()

#### HORTIZONAL LINES ####
# Use horizontal kernel to detect and save the horizontal lines in a jpg
image_2 = cv2.erode(img_bin, hor_kernel, iterations=5)
horizontal_lines = cv2.dilate(image_2, hor_kernel, iterations=5)
cv2.imwrite(r'C:UsersmarouDesktophorizontal.jpg', horizontal_lines)
# Plot the generated image
plotting = plt.imshow(image_2, cmap='gray')
plt.show()



# Combining both H and V
# Combine horizontal and vertical lines in a new third image, with both having same weight.
img_vh = cv2.addWeighted(vertical_lines, 0.5, horizontal_lines, 0.5, 0.0)
# Eroding and thesholding the image
img_vh = cv2.erode(~img_vh, kernel, iterations=2)
thresh, img_vh = cv2.threshold(img_vh, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
cv2.imwrite(r'C:UsersmarouDesktopimg_vh.jpg', img_vh)
plotting = plt.imshow(img_vh, cmap='gray')
plt.show()

To get this :
enter image description here

Now I am trying to fill the voids in my lines that happened due to the watermark removal, to be able to apply correct OCR.
I tried following the steps in this thread but I can’t seem to get it right.
When I try to fill the grid holes :

# Fill individual grid holes
cnts = cv2.findContours(result, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    x,y,w,h = cv2.boundingRect(c)
    cv2.rectangle(result, (x, y), (x + w, y + h), 255, -1)
cv2.imshow('result', result)
cv2.waitKey()

I get blank image:
enter image description here

Asked By: Mar1941

||

Answers:

I have outlined an approach to fill the missing lines in the table using the second image as input.

image = cv2.imread(image_path)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

enter image description here

Now to create a separate mask for the horizontal lines:

h_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (50,1))
# contains only the horizontal lines
h_mask = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, h_kernel, iterations=1)

# performing repeated iterations to join lines
h_mask = cv2.dilate(h_mask, h_kernel, iterations=7)

enter image description here

And a separate mask for the vertical lines:

v_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1,50))
v_mask = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, v_kernel, iterations=1)

enter image description here

Upon combining the above results we get the following:

joined_lines = cv2.bitwise_or(v_mask, h_mask)

enter image description here

The result above is not what you expected, the lines have extended beyond the boundaries of the table. In order to avoid this, I created a separate mask bounding the table region.

kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))
dilate = cv2.dilate(thresh, kernel, iterations=1)

enter image description here

Now find the largest contour in the above image and draw it on another binary image to create the mask.

contours, hierarchy = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
c = max(contours, key = cv2.contourArea)           # contour with largest area
black = np.zeros((image.shape[0], image.shape[1]), np.uint8)
mask = cv2.drawContours(black, [c], 0, 255, -1)    # --> -1 to fill the contour

enter image description here

Using the above image as mask over the joined_lines created further above

fin = cv2.bitwise_and(joined_lines, joined_lines, mask = mask)

enter image description here

Note:

You can perform more iterations over the morphological operations to better join the discontinuous lines

Answered By: Jeru Luke