2017-04-16 110 views
2

我想從Kaggle運行一些代碼,但我無法。cv2.findContours問題,opencv

該代碼是here

的錯誤信息是:

--------------------------------------------------------------------------- 
IndexError        Traceback (most recent call last) 
<ipython-input-6-2a3e36c2605f> in <module>() 
    59   _, contours_mask, _ = cv2.findContours(thresh_mask.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE) 
    60 
---> 61   main_contour = sorted(contours_mask, key = cv2.contourArea, reverse = True)[0] 
    62 
    63   x,y,w,h = cv2.boundingRect(main_contour) 

IndexError: list index out of range 

這可能是Python或相關的軟件包的版本,因爲其他人都沒有經歷過的代碼。

我試過打開一些輸出,但我是新的cv2。

我的理解是:

cv2.findContours() -> image, contours, hierarchy 

我能得到什麼:

cv2.findContours(thresh_mask.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE) -> (array([[0, 0, 0, ..., 0, 0, 0], 
    [0, 0, 0, ..., 0, 0, 0], 
    [0, 0, 0, ..., 0, 0, 0], 
    ..., 
    [0, 0, 0, ..., 0, 0, 0], 
    [0, 0, 0, ..., 0, 0, 0], 
    [0, 0, 0, ..., 0, 0, 0]], dtype=uint8), [], None) 

因此,countours是空的,這可能是問題。 thresh_mask對於這種情況是一個全零矩陣,這可能是原因。雖然不確定。

任何提示/建議?

+0

是的,你是正確的'計數器是空的,這可能是問題',你可能需要調整生成二進制圖像的方法的參數 – ZdaR

+0

文章中的評論讀取:*發佈在Kernels部分的代碼可以幫助你開始你的項目,你可以把它們作爲一個起點,但它們不是最終的解決方案。祝你好運!* – ZdaR

+0

我可以看到'len(sorted(contours_mask,key = cv2.contourArea,reverse = True))' – stovfl

回答

2

這是因爲你的輸入圖像(thresh_mask)是空的,即全黑。沒有檢測到輪廓。 請檢查thresh_mask的內容或使用cv2.imshow顯示它。

+0

如果'thresh_mask'完全是白色的,我認爲'cv2.findContours()'會至少找到** 1輪廓**。 –

+1

感謝盧克,你是對的。我編輯了我的答案。 –