首页 > 解决方案 > 如何在 if 语句中收集元组值?

问题描述

我有一个由循环if语句组成的代码,如下所示,for

for i in range(len(contours)):

    x, y, w, h = cv2.boundingRect(contours[i])
    mask[y:y+w, x:x+w] = 0
    cv2.drawContours(mask, contours, i, (255, 255, 255), -1)
    r = float(cv2.countNonZero(mask[y:y+h, x:x+w])) / (w * h)

    if r > 0.5 and w > 8 and h > 8:
        cv2.rectangle(rgb, (x, y), (x+w, y+h), (255, 255, 255), -1)
        cv2.circle(rgb, (x+w/2,y+h/2), 3, (180, 25, 20), -1)
        start_target_states = x+w/2 , y+h/2
        print "start_target_states: %s" % (start_target_states,)

运行此代码时,结果如下;

start_target_states: (704, 463)
start_target_states: (83, 15)

但是,start_target_states变量必须按照start_state第一个结果命名,之后,它必须按照target_state第二个结果命名。例如;

target_state: (704, 463)
start_state: (83, 15)

此外,我想将这两个元组分配给变量名。这样我以后可以使用它们。我的意思是,

TargetState = target_state
StartState = start_state

我试图修改 if 语句以达到我的目的,不幸的是我无法成功。我怎样才能做我想做的事?

标签: pythonopencvif-statementimage-processingopencv-drawcontour

解决方案


如果您以后需要访问它们,只需将它们添加到列表中即可。

states = []
for i in range(len(contours)):

    x, y, w, h = cv2.boundingRect(contours[i])
    mask[y:y+w, x:x+w] = 0
    cv2.drawContours(mask, contours, i, (255, 255, 255), -1)
    r = float(cv2.countNonZero(mask[y:y+h, x:x+w])) / (w * h)

    if r > 0.5 and w > 8 and h > 8:
        cv2.rectangle(rgb, (x, y), (x+w, y+h), (255, 255, 255), -1)
        cv2.circle(rgb, (x+w/2,y+h/2), 3, (180, 25, 20), -1)
        start_target_states = x+w/2 , y+h/2
        states.append(start_target_states)
        print "start_target_states: %s" % (start_target_states,)

由于您将它们放在列表中,因此您仍然可以访问它们,因为您不会每次都覆盖它们。

target_state = states[0]
start_state = states[1]

或更一般地说,如果您想捕获第一个和最后一个:

target_state = states[0]
start_state = states[-1]

此外,这不是您要问的,但最好是使用enumerate这种循环。

for i, contour in enumerate(contours):

然后counters[i]你可以使用而不是使用contour.


推荐阅读