2016-12-24 79 views
2

我有一个像下面的图像。图像的尺寸是固定的:640x480如何从图像中提取所有区域?

enter image description here

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

enter image description here

我需要知道每一种的右上和左下点矩形。

我想过循环和其他方法。但是他们都会花很长时间才能运行。什么是最有效的方式来做到这一点在Python中?

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

回答

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) 

输出图像:

The output image