我試圖理解以下用Python撰寫的代碼片段(請記住,我是這種編程語言的新手):
from imutils import perspective
from imutils import輪廓線
import numpy as np
import imutils
import cv2
...
cnts = cv2.findContours(eroded, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
cnts = imutils.grab_contours(cnts)
cnts, _ = contours.sort_contours(cnts, method="top to bottomom")
for c in cnts:
box = cv2.minAreaRect(c)
box = cv2.boxPoints(box)
box = np.array(box, dtype="int")
cv2.drawContours(image, [box], 0, (0,255,0), 3)
更具體地說,我不明白包圍box的方括號的含義。如果我去掉這些方括號,腳本的執行就會出現如下錯誤:
Traceback (most recent call last): 檔案 "C:script.py", line 222, in <module>
cv2.drawContours(image, box, 0, (0,255, 0), 3)
cv2.錯誤。OpenCV(4.5. 1) C:UserappveyorAppDataLocalTemp1pip-req-build-wvn_it83opencvmodulesimgprocsrcdrawing.cpp:2501:錯誤。(-215:Assertion failed) npoints > 0 in function 'cv::drawContours'
誰能解釋一下在這種情況下這些方括號的目的是什么?
多謝
CodePudding我相信你需要方括號的原因是因為輪廓線是要成為一個串列。即使你只有一個輪廓,你也必須在它周圍加上括號以表示它是一個串列。以下是檔案中的條目:
drawContours()
drawContours(image, contours, contourIdx, color[, thickness[, lineType[, hierarchy[, maxLevel[, offset]]]]]) -> 無
我認為這就是原因,但是,我對這個庫不熟悉,所以我可能不正確。
uj5u.com熱心網友回復:
這其實很簡單。不要讓它是一個函式中的引數這一事實迷惑你。
它只是一個串列,其中包含box - 變數是其中唯一的元素。
empty_list = [] # 方括號表示一個串列。
contained_list = ['item', random_variable, 21, True] # 串列(在其他語言中也被稱為陣列)可以容納任何東西,包括,變數。
我希望這能幫助你理解它
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/311677.html
標籤:
