2013-07-13 38 views
4

我試圖使用OpenCV從Nike圖像中提取標籤。這是取自教程代碼:OpenCV TypeError:輪廓不是一個numpy數組,既不是標量也不是標量

http://opencv-code.com/tutorials/ocr-ing-nikes-new-rsvp-program/

我修改幾行代碼,但並沒有在該部分沒有錯誤(不知道它的工作,因爲我一直沒能成功完全運行它。)

當我運行命令'python a.py'。顯示此錯誤: -

Traceback (most recent call last): 
    File "a.py", line 42, in <module> 
    otcnt = [c for c in cnt if cv2.contourArea(c) < 100] 
TypeError: contour is not a numpy array, neither a scalar 

a.py:-

#!/usr/bin/env python 
import numpy as np 
import cv2 
import cv2.cv as cv 

def do_ocr(img0): 
    pass 

if __name__ == "__main__": 
    img0 = cv2.imread('nike-1.jpg') 
    if img0 == None: 
    import sys 
    sys.exit() 
    do_ocr(img0) 
img1 = cv2.cvtColor(img0, cv2.COLOR_BGR2GRAY) 
img2 = cv2.adaptiveThreshold(img1, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 45, 0) 
size = np.size(img2) 
skel = np.zeros(img2.shape,np.uint8) 

ret,img2 = cv2.threshold(img2,127,255,0) 
element = cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3)) 
done = False 
while(not done): 
    eroded = cv2.erode(img2,element) 
    temp = cv2.dilate(eroded,element) 
    temp = cv2.subtract(img2,temp) 
    skel = cv2.bitwise_or(skel,temp) 
    img2 = eroded.copy() 

    zeros = size - cv2.countNonZero(img2) 
    if zeros==size: 
     done = True 
img3 = img2 
img4 = cv2.copyMakeBorder(img3, 1, 1, 1, 1, cv2.BORDER_CONSTANT, value=0) 
cv2.floodFill(img4, None, (0,0), 255) 
img5 = cv2.erode(255-img4, np.ones((3,3), np.uint8), iterations=2) 
cnt = cv2.findContours(img5, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[0] 
cnt = [c for c in cnt if cv2.contourArea(c) > 5000] 
mask = np.zeros(img0.shape[:2], np.uint8) 
cv2.drawContours(mask, cnt, -1, 255, -1) 
dst = img2 & mask 
cnt = cv2.findContours(dst.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) 
otcnt = [c for c in cnt if cv2.contourArea(c) < 100] 
cv2.drawContours(dst, otcnt, -1, 0, -1) 
api = tesseract.TessBaseAPI() 
api.Init(".", "eng", tesseract.OEM_DEFAULT) 
api.SetVariable("tessedit_char_whitelist", "#ABCDEFGHIJKLMNOPQRSTUVWXYZ") 
api.SetPageSegMode(tesseract.PSM_SINGLE_LINE) 

image = cv.CreateImageHeader(dst.shape[:2], cv.IPL_DEPTH_8U, 1) 
cv.SetData(image, dst.tostring(), dst.dtype.itemsize * dst.shape[1]) 
tesseract.SetCvImage(image, api) 
print api.GetUTF8Text().string() 

我很新的Python編程(和Python語法),我已經做到這一點在Python反正。如果您可以發佈完整的正確版本或手指點,哪一行代碼應該替換爲哪一行,我將非常感謝您。

謝謝

p.s.我在stackoverflow的第一個問題,如果不遵循任何約定,所以道歉。

回答

4

此運行時錯誤的事實,當你重新定義cnt上線42

cnt = cv2.findContours(dst.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) 

要設置這是造成的cv2.findContours兩個返回值的元組。看看你先前對第37行功能的調用。所有你需要做的是改變42行

cnt = cv2.findContours(dst.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[0] 

你的下一個問題是,你有沒有進口tesseract

+0

謝謝修復了上述問題。我感謝您的幫助。我在導入tesseract時面臨另一個問題,但我相信應該有一個新的問題。感謝您指出。 –

相關問題