python - 通过相同大小的周围矩形提取图像中的标记区域

标签 python opencv image-processing

我想提取图像上以任意形状标记的一个或多个区域(形状边缘始终具有相同的颜色-红色)。标记的区域都具有大约相同的大小(并非完全相同),我希望切出的矩形具有相同的结果大小。

你能给我一个提示怎么做吗?我猜一个人可以在Python中使用opencv来完成这项任务,但是我对此并不熟悉,因此感谢您的帮助!

编辑:添加了一个示例图像,目标是通过相同大小的矩形提取红色区域。
example image

最佳答案

这是在Python / OpenCV中执行此操作的一种方法。

  • 读取灰色输入,并绘制红色形状
  • 形状
  • 的红色阈值
  • 紧密应用形态,以确保形状是连续的轮廓且无间隙
  • 获取外部轮廓及其边界框
  • 计算每个边界框的中心并保存在列表中,还计算所有边界框的最大宽度和高度。
  • 对于每个中心以及最大宽度和高度,裁剪输入图像并保存

  • 输入:

    enter image description here
    import cv2
    import numpy as np
    
    # read image
    img = cv2.imread('monet_shapes.png')
    
    # threshold on red regions
    lowerBound = np.array([0, 0, 150]);
    upperBound = np.array([100, 100, 255]);
    thresh = cv2.inRange(img, lowerBound, upperBound);
    
    # apply morphology to ensure regions are continuous outlines and no gaps
    kernel = np.ones((9,9), np.uint8)
    thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)    
    
    # get external contours
    contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    contours = contours[0] if len(contours) == 2 else contours[1]
    wmax = 0
    hmax = 0
    # get bounding boxes and max width and max height from all boxes and centers
    centers = []
    for cntr in contours:
        # get bounding boxes
        x,y,w,h = cv2.boundingRect(cntr)
        cx = x + w // 2
        cy = y + h // 2
        cent = [cx,cy]
        centers.append(cent)
        if w > wmax:
            wmax = w
        if h > hmax:
            hmax = h
    
    print(wmax,hmax)
    
    # show thresh and result    
    cv2.imshow("thresh", thresh)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    
    # save threshold
    cv2.imwrite("monet_shapes_thresh.png",thresh)
    
    # crop bounding boxes of size maxw, maxh about centers and save
    i = 1
    for cent in centers:
        cx = cent[0]
        cy = cent[1]    
        box = img[cy-hmax//2:cy+hmax//2, cx-wmax//2:cx+wmax//2]
        cv2.imwrite("blackbox_result_{0}.png".format(i),box)
        i = i + 1
    

    阈值图片:

    enter image description here

    结果出现了5个裁剪区域:

    enter image description here

    enter image description here

    enter image description here

    enter image description here

    enter image description here

    关于python - 通过相同大小的周围矩形提取图像中的标记区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60967038/

    相关文章:

    python - 在 Windows 上获取本地时区名称(Python 3.9 zoneinfo)

    python - 二维箭袋图 - matplotlib 和 MATLAB 输出不匹配

    opencv - Kinect - 物体识别和计算物体的3D坐标

    c++ - OpenCV 从单应性估计距离和法 vector

    python - 从一列字符串中提取整数

    c# - EmguCV - 匹配模板

    django - sorl-thumbnail:在保存前调整原始图像的大小?

    python - 如何获得图像中单个蒙版细胞强度的直方图?

    algorithm - 计算图像的动态范围?

    python - PyGame:处理游戏循环的经济方式