簡體   English   中英

Python中方括號的含義

[英]Meaning of square brackets in Python

我試圖理解以下用 Python 編寫的代碼片段:

from imutils import perspective
from imutils import contours
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-bottom")
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):   File "C:\script.py", line 222, in <module>
    cv2.drawContours(image, box, 0, (0,255,0), 3)
cv2.error: OpenCV(4.5.1) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-wvn_it83\opencv\modules\imgproc\src\drawing.cpp:2501: error: (-215:Assertion failed) npoints > 0 in function 'cv::drawContours'

在這種情況下,這些方括號的目的是什么?

我相信你需要括號的原因是因為輪廓是一個列表。 即使你有一個輪廓,你也必須在它周圍加上括號來表示它是一個列表。 這是文檔中的條目:

drawContours(圖像,輪廓,contourIdx,顏色 [,厚度 [,lineType [,層次結構 [,maxLevel [,偏移量]]]]])-> 無

我認為這就是原因,但是,我不熟悉這個庫,所以我可能不正確。

這真的很簡單。 不要讓它是函數中的參數這一事實讓您感到困惑。

它只是一個帶有box的列表 - 變量是其中包含的唯一元素。

empty_list = [] # Square brackets signify a list
contained_list = ['item', random_variable, 21, True] # Lists (also known as arrays in other langs) can hold anything, including, variables

暫無
暫無

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

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