5

I have the following Image result.png with Countours drawn at every rectangle:

enter image description here

In the next step I am trying to extract only the inner portion of these rectangles to get the images which has centralised digits(2, 0, 1, 8). The code I am using is as follows:

import cv2

BLACK_THRESHOLD = 200
THIN_THRESHOLD = 10

im = cv2.imread('result.png', 0)
ret, thresh = cv2.threshold(im, 127, 255, 0)
contours, hierarchy = cv2.findContours(thresh, 1, 3)
idx = 0
for cnt in contours:
    idx += 1
    x, y, w, h = cv2.boundingRect(cnt)
    roi = im[y:y + h, x:x + w]
    if h < THIN_THRESHOLD or w < THIN_THRESHOLD:
        continue
    cv2.imwrite(str(idx) + '.png', roi)
    cv2.rectangle(im, (x, y), (x + w, y + h), (200, 0, 0), 2)
cv2.imshow('img', im)
cv2.waitKey(0)

It is working but it is giving every possible cropped image on the basis of the Countours created as shown below(different image at each row):

enter image description here

It is extracting 18 Images whereas I only want Images which has digits in its center without any kind of noise. Can anyone help me how to narrow this extraction process?

7
  • Use the hierarchy to stop when you've gone too deep.
    – Dan Mašek
    Commented Apr 4, 2018 at 17:54
  • Yes I read about that, but how to get the first innermost hierarchy level(index) of the contour while traversing different contours? @DanMašek
    – Aadit
    Commented Apr 4, 2018 at 18:26
  • 1
    try using the flag CV_RETR_EXTERNAL in the findContours function
    – api55
    Commented Apr 4, 2018 at 19:45
  • contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, 3) I changed the function to this as you said and I read that it returns only extreme outer flags but it is extracting only one image(i.e the original one on which contours are drawn) As I am kind of new to OpenCv can you just run this on your machine and guide me? PS: should I share the code through which contours are drawn? Thank You @api55
    – Aadit
    Commented Apr 4, 2018 at 20:34
  • I'd think more using the RETR_TREE method, since those digits are nested in the boxes. The hierarchy you get out is a tree structure, so you can do depth first search and keep track of the current depth (or something along those lines). Then you'd just keep the contours at the appropriate level, and ignore the rest.
    – Dan Mašek
    Commented Apr 4, 2018 at 21:04

0