简体   繁体   中英

opencv while loops, going back to first loop

I have a the following python code (and I'm using 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).

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. if 'esc' the program should be terminated.

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.

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. Use a different while condition in the second loop. Instead of while(True) use a boolean:

#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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM