[英]opencv while loops, going back to first loop
I have a the following python code (and I'm using opencv3). 我有以下python代码(并且我正在使用opencv3)。 What this code needs accomplish is to take a live stream of a generic camera, and then analyze a static picture (or frame).
此代码需要完成的工作是拍摄通用摄像机的实时流,然后分析静态图片(或帧)。 The problem that I have have, is that after exiting the second nested while loop, i can figure out how to go back to the initial loop (#1st loop).
我遇到的问题是,退出第二个嵌套的while循环后,我可以弄清楚如何返回到初始循环(#1st循环)。
The code should : 该代码应:
Take live stream press 'q' to capture frame and go to the next loop on this second loop: if 's' -after the images is analyzed- it should go back to the 1st loop. 进行直播时,按“ q”捕获帧并转到第二个循环中的下一个循环:如果“ s”(在分析了图像之后),则应回到第一个循环。 if 'esc' the program should be terminated.
如果为“ esc”,则程序应终止。
I did tried the recursion method (def () ) but I run into another problem in which i couldn't figure out how to terminate the program. 我确实尝试过递归方法(def()),但遇到另一个问题,我无法弄清楚如何终止程序。
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
#Set LED brightness for camera
cap.set(cv2.CAP_PROP_BRIGHTNESS, 120)
#1st loop
while (True):
#capture camera stream
ret, frame = cap.read()
cv2.imshow('live image', frame)
if cv2.waitKey(0) == ord('q'):
cap.release()
cv2.destroyAllWindows()
pass
print ('image alteration block')
#2nd loop
while (True):
img = frame
cv2.imshow('image',img)
k = cv2.waitKey(0)
if k == 27: # wait for ESC key to exit and terminate progra,
cv2.destroyAllWindows()
break
elif k == ord('s'): # wait for 's' key to save the image and go back to the live stream
cv2.imwrite('messigray.png',img)
print ('go back to the beginning')
cv2.destroyAllWindows()
continue #NOT SURE WHAT TO DO HERE
You're not allowing the program to escape the second while loop. 您不允许程序转义第二个while循环。 Use a different while condition in the second loop.
在第二个循环中使用其他while条件。 Instead of while(True) use a boolean:
代替while(True)使用布尔值:
#2nd loop
second=True
while (second):
img = frame
cv2.imshow('image',img)
k = cv2.waitKey(0)
if k == 27: # wait for ESC key to exit and terminate progra,
cv2.destroyAllWindows()
break
elif k == ord('s'):
cv2.imwrite('messigray.png',img)
print ('go back to the beginning')
cv2.destroyAllWindows()
#modify the loop condition
second = False
continue
That should get you out of the second loop, relying on breaks is not always the best way to handle while loops. 那应该使您摆脱第二个循环,依靠中断并不总是处理while循环的最佳方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.