如何在 if 语句中收集元组值?

How to collect tuple values in if statement?

我有一个代码,其中包含 for 循环中的 if 语句,如下所示,

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)

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

TargetState = target_state
StartState = start_state

我尝试修改if语句来达到我的目的,不幸的是我没有成功。我怎样才能做我想做的事?

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

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):

然后您可以使用 contour.

而不是使用 counters[i]