[英]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.