2016-07-13 638 views
1

我使用Python2.7.12和OpenCV 3.0.0-RC1OpenCV的Python中:找到輪廓/邊緣/矩形圖像

我在文本識別項目的工作英寸

這就是我現在得到的。 Original iamge after findContour, line 34

正如您所看到的,圖像中包含很多「框」,其中有文本。

我的方法是找到這些框,將它們剪切成單獨的圖像,然後將它們送到TesseractOCR。

該程序將整個圖像視爲一個輪廓。 我怎樣才能找到裏面的小一個?

或者,如果你有另一種方法,歡迎

代碼:

import cv2 


def threshold(im, method): 
    # make it grayscale 
    im_gray = cv2.cvtColor(im, cv2.COLOR_RGB2GRAY) 

    if method == 'fixed': 
     threshed_im = cv2.threshold(im_gray, 128, 255, cv2.THRESH_BINARY) 

    elif method == 'mean': 
     threshed_im = cv2.adaptiveThreshold(im_gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 5, 10) 

    elif method == 'gaussian': 
     threshed_im = cv2.adaptiveThreshold(im_gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 5, 7) 

    else: 
     return None 

    return threshed_im 


image = cv2.imread('demo4.jpg') 

# threshold it 
thresh = threshold(image, 'mean') 

# find contours 
_, cnts, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) 

print len(cnts) 

cv2.drawContours(image, cnts, -1, (0, 255, 0), 20) 
cv2.imshow('contours', image) 
cv2.waitKey() 

cv2.drawContours(thresh, cnts, -1, (0, 255, 0), 20) 
cv2.imshow('contours', thresh) 

cv2.waitKey() 

`

回答

2

因爲你指定cv2.RETR_EXTERNAL你只得到了最外面的輪廓。爲了獲得圖像的所有輪廓,你應該調用的方法是這樣的:

cv2.findContours(thresh.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) 

OpenCV documentation看看,看看功能如何工作的。