簡體   English   中英

openCV 3中contourArea的兼容性問題

[英]compatibility issue with contourArea in openCV 3

我正在嘗試對從 findContours 獲得的輪廓進行簡單的面積計算。 我的 openCv 版本是 3.1.0

我的代碼是:

cc = cv2.findContours(im_bw.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.contourArea(cc[0])

error: 'C:\\builds\\master_PackSlaveAddon-win32-vc12-static\\opencv\\modules\\imgproc\\src\\shapedescr.cp...: error: (-215) npoints >= 0 && (depth == CV_32F || depth == CV_32S) in function cv::contourArea\n'

似乎無法解決它,我有一種感覺它只是類型轉換,盡管我希望 findContours 結果與 contourArea 的類型相匹配

謝謝 :)

編輯:原來我需要采用 findContours 的第二個參數

 im2, cc, hierarchy = cv2.findContours(im_bw.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

cv2.findContours() 3 API 版本中cv2.findContours()返回 3 個對象

  • 圖片
  • 輪廓
  • 等級制度

因此,您需要將語句重寫為:

image, contours, hierarchy = cv2.findContours(im_bw.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

根據 OpenCV 版本, cv2.findContours()具有不同的返回簽名。

在 OpenCV 3.4.X 中, cv2.findContours()返回 3 個項目

image, contours, hierarchy = cv.findContours(image, mode, method[, contours[, hierarchy[, offset]]])

在 OpenCV 2.X 和 4.1.X 中, cv2.findContours()返回 2 個項目

contours, hierarchy = cv.findContours(image, mode, method[, contours[, hierarchy[, offset]]])

無論版本如何,您都可以輕松獲得輪廓:

cnts = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]

這個問題是由於不同OpenCV版本中cv2.findContours的返回值不同造成的。

在 OpenCV 4.0.0 中,此錯誤可能類似於cv2.error: OpenCV(4.0.0) C:\\projects\\opencv-python\\opencv\\modules\\imgproc\\src\\convhull.cpp:137: error: (-215:Assertion failed) total >= 0 && (depth == CV_32F || depth == CV_32S) in function 'cv::convexHull'

你可以在這里找到詳細的解釋和解決方案: 如何在不同的 OpenCV 版本中使用 `cv2.findContours`?

感謝@ZdaR; 順便說一句,您可以在 OpenCV 4.1 中執行以下操作:

contours, hierarchy = cv2.findContours(im_bw.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM