Reputation: 126
I'm having problems finding contours on specific columns in a table. The issue when using opencv is that I have to specify which area to draw rectangles in with an if loop on x, y and w (the 2 axes and the width) this works fine if the table lines are perfectly horizontal or vertical but if they're not then you don't get good results.
I used this code to get bounding boxes:
import numpy as np
import cv2
img = r'C:\Users\lenovo\PycharmProjects\SoftOCR_Final\Filtered_images\filtered_image1.png'
table_image_contour = cv2.imread(img, 0)
table_image = cv2.imread(img)
ret, thresh_value = cv2.threshold(table_image_contour, 180, 255, cv2.THRESH_BINARY_INV)
kernel = np.ones((5, 5), np.uint8)
dilated_value = cv2.dilate(thresh_value, kernel, iterations=1)
contours, hierarchy = cv2.findContours(dilated_value, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
x, y, w, h = cv2.boundingRect(cnt)
# bounding the
if 2271 > x > 746 and w > 300 and y > 1285:
table_image = cv2.rectangle(table_image, (x, y), (x + w, y + h), (0, 0, 255), 3)
roi = table_image[y: y + h, x: x + w]
width = int(table_image.shape[1] * 20 / 100)
height = int(table_image.shape[1] * 20 / 100)
dsize = (width, height)
table_image = cv2.resize(table_image, dsize)
cv2.imshow('1', table_image)
cv2.waitKeyEx(0)
Here's the image I'm working on:
And this is the what I'd like to draw bounding boxes on. Only that part
Now this is what I'm actually getting.
As you can see, I'm losing some lines and getting bounding boxes outside of the table.
Upvotes: 2
Views: 1549
Reputation: 3975
You have two issues here:
The first one is in fact a non-issue, as your final resizing step is making the bounding boxes disappear visually. They however are correctly detected, as you can check by removing all the code between the for loop and the lines:
cv2.imshow('1', table_image)
cv2.waitKeyEx(0)
The second issue can be solved by checking for a maximum y coordinate for the bounding boxes. Changing the condition to if 1000 < x < 2000 and w > 300 and 1285 < y < 2600 :
worked quite well on the sample image, giving the following results :
Upvotes: 3