gpt4 book ai didi

python - python初学者错误中的变量增量

转载 作者:行者123 更新时间:2023-12-01 05:14:40 26 4
gpt4 key购买 nike

我试图在每次检测到对象时增加计数器。

count=0

def detect_and_draw(img, cascade):
# allocate temporary images
gray = cv.CreateImage((img.width,img.height), 8, 1)
small_img = cv.CreateImage((cv.Round(img.width / image_scale),
cv.Round (img.height / image_scale)), 8, 1)

# convert color input image to grayscale
cv.CvtColor(img, gray, cv.CV_BGR2GRAY)

# scale input image for faster processing
cv.Resize(gray, small_img, cv.CV_INTER_LINEAR)
cv.EqualizeHist(small_img, small_img)

if(cascade):
t = cv.GetTickCount()
faces = cv.HaarDetectObjects(small_img, cascade, cv.CreateMemStorage(0),
haar_scale, min_neighbors, haar_flags, min_size)
t = cv.GetTickCount() - t
print "time taken for detection = %gms" % (t/(cv.GetTickFrequency()*1000.))
if faces:

for ((x, y, w, h), n) in faces:
# the input to cv.HaarDetectObjects was resized, so scale the
# bounding box of each face and convert it to two CvPoints
pt1 = (int(x * image_scale), int(y * image_scale))
pt2 = (int((x + w) * image_scale), int((y + h) * image_scale))
cv.Rectangle(img, pt1, pt2, cv.RGB(255, 0, 0), 3, 8, 0)
count += 1
print count

但我不明白为什么它会出现此错误。我尝试在 if 之后进行增量,但仍然出现相同的错误。这是第一次使用 python,所以我无法了解作用域规则。我应该修改什么?

 File "detect.py", line 42, in detect_and_draw
count +=1
UnboundLocalError: local variable 'count' referenced before assignment

最佳答案

您有一个全局计数。该函数不知道这一点。

def detect_and_draw(img, cascade):
global count

关于python - python初学者错误中的变量增量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23437512/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com