Home > Enterprise >  Meaning of square brackets in Python
Meaning of square brackets in Python

Time:09-17

I'm trying to understand the following code snippet written in Python (bear in mind I'm new to this programming language):

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. 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'

Could anyone explain the aim of these square brackets in this case ?

Many thanks

CodePudding user response:

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

I think this is the reason, however, I am unfamiliar with this library so I may be incorrect.

CodePudding user response:

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.

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

I hope this helped you understand it

  • Related