2016-12-24 78 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