lucians
lucians

Reputation: 2269

Extract MSER detected areas (Python, OpenCV)

I can't extract the detected regions by MSER in this image:

img

What I want to do is to save the green bounded areas. My actual code is this:

import cv2
import numpy as np

mser = cv2.MSER_create()
img = cv2.imread('C:\\Users\\Link\\img.tif')
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]
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 contour in hulls:
    cv2.drawContours(mask, [contour], -1, (255, 255, 255), -1)

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


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

Expected result should be a ROI like image.

out

Source image:

src

Upvotes: 1

Views: 7982

Answers (3)

John M
John M

Reputation: 59

Hey found a cleaner way to get the bounding boxes

regions, _ = mser.detectRegions(roi_gray)

bounding_boxes = [cv2.boundingRect(p.reshape(-1, 1, 2)) for p in regions]

Upvotes: 1

Manstie
Manstie

Reputation: 465

detectRegions also returns bounding boxes:

regions, boundingBoxes = mser.detectRegions(gray)

for box in boundingBoxes:
        x, y, w, h = box;
        cv2.rectangle(vis, (x, y), (x+w, y+h), (0, 255, 0), 1)

This draws green rectangles, or save them as mentioned in GPhilo's answer.

Upvotes: 4

GPhilo
GPhilo

Reputation: 19123

Just get the bounding box for each contour, use that as a ROI to extract the area and save it out:

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

Upvotes: 2

Related Questions