简体   繁体   English

Python中方括号的含义

[英]Meaning of square brackets in Python

I'm trying to understand the following code snippet written 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)

More specifically, I don't understand the meaning of square brackets sorrounding box .更具体地说,我不明白方括号围绕box的含义。 If I remove the brackets, the script execution stucks on the following error:如果我删除括号,脚本执行会出现以下错误:

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'

What is the aim of these square brackets in this case?在这种情况下,这些方括号的目的是什么?

I believe the reason you needs brackets is because contours is meant to be a list.我相信你需要括号的原因是因为轮廓是一个列表。 Even if you have one contour, you must put brackets around it to denote that it is a list.即使你有一个轮廓,你也必须在它周围加上括号来表示它是一个列表。 Here is the entry from the docs:这是文档中的条目:

drawContours(image, contours, contourIdx, color[, thickness[, lineType[, hierarchy[, maxLevel[, offset]]]]]) -> None drawContours(图像,轮廓,contourIdx,颜色 [,厚度 [,lineType [,层次结构 [,maxLevel [,偏移量]]]]])-> 无

I think this is the reason, however, I am unfamiliar with this library so I may be incorrect.我认为这就是原因,但是,我不熟悉这个库,所以我可能不正确。

It is quite simple really.这真的很简单。 Don't let the fact that it is a parameter in a function confuse you.不要让它是函数中的参数这一事实让您感到困惑。

It is simply a list with box - variable as the only element contained within it.它只是一个带有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