代码之家  ›  专栏  ›  技术社区  ›  lucians

提取MSER检测区域(Python、OpenCV)

  •  1
  • lucians  · 技术社区  · 7 年前

    我无法在此图像中通过MSER提取检测到的区域:

    img

    我的实际代码是:

    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)
    

    预期结果应该是类似ROI的图像。

    out

    源图像:

    src

    3 回复  |  直到 7 年前
        1
  •  4
  •   Manstie    5 年前

    detectRegions还返回边界框:

    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)
    

    这会绘制绿色矩形,或者按照GPhilo的回答保存它们。

        2
  •  2
  •   GPhilo satyendra    7 年前

    只需获取每个轮廓的边界框,将其用作ROI来提取区域并保存:

    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])
    
        3
  •  1
  •   John M    4 年前

    他们找到了一个更干净的方法来获取边界框

    regions, _ = mser.detectRegions(roi_gray)
    
    bounding_boxes = [cv2.boundingRect(p.reshape(-1, 1, 2)) for p in regions]
    
    推荐文章