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

标签 python opencv if-statement image-processing contour

我有一个代码,它由 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 语句来达到我的目的,不幸的是我没有成功。我怎样才能做我想做的事?

最佳答案

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

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]

关于python - 如何在 if 语句中收集元组值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51410961/

相关文章:

python - OpenCV:识别图像的部分

visual-c++ - OpenCV 2.0 C++ API 使用 imshow : returns unhandled exception and "bad-flag"

ruby - 在两个平台之间开发时的 Gemfile

python - "No child processes"on os.waitpid

python - appengine 中静态文件的 IO 错误

python - 在 Pythonscript 中获取 Netcat 的输出

android - OpenCv4Android : frame masking by an image

java - 使用 if 语句比较 String 和 Arrays.asList 值

matlab - 条件向量化(循环内)

python - 使用Python向 super 计算机提交多个作业