【问题标题】:How to collect tuple values in if statement?如何在 if 语句中收集元组值?
【发布时间】:2018-12-26 21:38:29
【问题描述】:

我有一个代码,它由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)

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

TargetState = target_state
StartState = start_state

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

【问题讨论】:

  • if 条件下是否总是只打印两个值?
  • 已编辑:可能会因图像而改变。但是现在,是的,我只得到两个值。此外,当我在 if 条件之外使用 print 函数时,我会获得更多价值。总而言之,我需要两个值,如上所述,必须指定为变量名。

标签: python opencv if-statement image-processing opencv-drawcontour


【解决方案1】:

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

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]

【讨论】:

    猜你喜欢
    • 2021-08-11
    • 2015-01-26
    • 2012-08-01
    • 2016-02-04
    • 2016-11-01
    • 2018-04-24
    • 2018-12-26
    • 2022-01-14
    • 1970-01-01
    相关资源
    最近更新 更多