【问题标题】:How can I extract all regions from an image?如何从图像中提取所有区域?
【发布时间】:2016-12-25 23:21:55
【问题描述】:

我有一张像下面这样的图片。图片尺寸固定:640x480

我想用这样的矩形来绑定所有非零区域:

我需要知道每个矩形的右上角和左下角。

我考虑过循环和其他方法。但是所有这些都需要很长时间才能运行。在 python 中最有效的方法是什么?

PS:我是图像处理的初学者。这可能是一个显而易见的问题,我不知道。所以给我一个示例代码会有很大帮助。谢谢。

【问题讨论】:

    标签: python-2.7 numpy opencv3.0


    【解决方案1】:

    查找图像中的所有子组件称为connected component analysis。在 OpenCV 中,您可以使用其 contour analysis 库的 findCountour() 函数来完成。

    这是一个示例代码:

    import cv2
    import numpy as np
    from scipy import signal
    
    #=========================================================================
    # Locate all components 
    #=========================================================================
    def locateComponents(img):
        """Extracts all components from an image"""
    
        out = img.copy()     
        res = cv2.findContours(np.uint8(out.copy()),\
                     cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)    
        contours = res[1]
    
        ret = []
        row, col = out.shape
        minSiz = 8
    
        for cnt in contours:
            # get bounding box
            y, x, n, m = cv2.boundingRect(cnt)
            # check area 
            if m < minSiz or n < minSiz:
                continue
            #end if       
    
            ret.append(np.int32([x, x+m, y, y+n]))
            out = cv2.rectangle(out, (y,x), (y+n,x+m), (255,255,255), 2)
    
        #end for
    
        return ret, out
    
    # end function
    
    #=========================================================================
    # TESTING 
    #=========================================================================
    
    img = cv2.imread('input.jpg', 0)
    
    regions, out = locateComponents(img)
    cv2.imwrite('output.jpg', out)
    print regions
    
    cv2.imshow('Given image', img)
    cv2.imshow('Located regions', out)
    cv2.waitKey(0)
    

    输出图像:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-15
      • 2019-10-06
      • 2016-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多