pythonopencvmser

Extract detected objects and save to different images - OpenCV Python


I have this image:

enter image description here

and I want to extract all the buttons and save them in different images. Until now I have this code:

import numpy as np
import cv2

img = cv2.imread('C:\\Users\\Rita\\Desktop\\ISCTE\\2_ano\\Tese\MSER\\1_Exemplo\\botoes.PNG',1)

vis = img.copy()
mser = cv2.MSER_create()
vis = img.copy()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

regions, _ = mser.detectRegions(gray)

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



for i, contour in enumerate(hulls):
    x,y,w,h = cv2.boundingRect(contour)
    cv2.imwrite('1_exemplo_{}.png'.format(i), img[y:y+h,x:x+w])

But it's not separate in the correct way. Does anybody know what i'm missing here in the code? Or what it's the best way to do it?


Solution

  • There are different parameters that you have to try in order to extract what you need.

    Using the snippet below I extracted all but one blob:

    mser = cv2.MSER_create( _min_area = 5000, _max_variation = 1.0)
    

    enter image description here

    Try varying the other parameters from THIS LINK for better results.