python - 如何在 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 语句以达到我的目的,不幸的是我无法成功。我怎样才能做我想做的事?
解决方案
如果您以后需要访问它们,只需将它们添加到列表中即可。
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
.
推荐阅读
- python - 如何删除数组中的多行
- node.js - 当我尝试将 express 添加到我的第一个 react 应用程序时,为什么会出现 TypeError
- ibm-cloud - 如何在通过 ibmcloud CLI 创建新的经典虚拟服务器时启用暂停计费
- linux - 在 pi 上流式传输视频的更有效方式
- corda - Reg : 为特定的 CordaVersion=4.x 构建 CorDApp
- authentication - 为基于 SMS OTP 的登录扩展身份
- database - 你如何保存矢量的内容?
- javascript - 访问任何 DOM 按钮以应用 Javascript 中的 addEventListener 事件可能有什么问题?
- javascript - 单击饼图切片时不显示引导模式
- pycharm - 为什么pycharm无法识别模块?