0

I am trying to extract the number from this image using MSER contours.

src

Using this code..

import cv2
import numpy as np

mser = cv2.MSER_create()
img = cv2.imread('C:\\Users\\Link\\Desktop\\7.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
vis = img.copy()

regions, _ = mser.detectRegions(gray)
hulls = [cv2.convexHull(p.reshape(-1, 1, 2)) for p in regions]
poly = cv2.polylines(vis, hulls, 1, (0, 255, 0))

mask = np.zeros((img.shape[0], img.shape[1], 1), dtype=np.uint8)
mask = cv2.dilate(mask, np.ones((150, 150), np.uint8))

for i,contour in enumerate(hulls):
    cv2.drawContours(mask, [contour], -1, (255, 255, 255), -1)

    text_only = cv2.bitwise_and(img, img, mask=mask)

    cv2.imwrite('poly{}.png'.format(i), text_only)

cv2.imshow('img', vis)
cv2.waitKey(0)
cv2.imshow('mask', mask)
cv2.waitKey(0)
cv2.imshow('text', text_only)
cv2.waitKey(0)

...I obtain this as image (apart from the whole image itself as result of MSER detection):

res0 res1

How can I made the background transparent ? All that I found about this procedure, which use Opencv and Python, is this other question: NumPy/OpenCV 2: how do I crop non-rectangular region?

Applying the code suggested there produce the next output, which is not what I would like to have:

res2

The goal is to have something like this:

out

If it's not possible at that level, atleast how can I turn the black area into transparent ?

Thanks

lucians
  • 2,239
  • 5
  • 36
  • 64
  • Do you need to do it with MSER? I think this can be easier with `cv2.findCountours()` – Jose A. García Jan 12 '18 at 13:36
  • I have to extract the shape of the number, so not a rectangular shape. That said, it doesn't matter. I used MSER because is the one which "worked" better for now... – lucians Jan 12 '18 at 13:38
  • Try [this](https://docs.opencv.org/2.4/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=findcontours#findcontours) I'm pretty sure it will give you better contours. It does not give a BoundingBox, you can calculate it tho. [Kinda tutorial](https://www.pyimagesearch.com/2014/04/21/building-pokedex-python-finding-game-boy-screen-step-4-6/) to get you started. – Jose A. García Jan 12 '18 at 13:43
  • Does it do a non regular shape ? – lucians Jan 12 '18 at 13:44
  • It can give you a contour which is a list of points all neighbor of the two next to them (by neighbor I mean one of the eight possible pixels). If you mean non-regular by non rectangular, circular, etc then yes. – Jose A. García Jan 12 '18 at 13:47
  • Seems to work in a way...But how can I extract only the shape of the number ? Take as example [this image](https://imgur.com/a/H0IBJ). How can I extract just the contour and not a rectangle ? – lucians Jan 12 '18 at 14:21

0 Answers0