for an openCV program i was trying to build for a personal project, I needed to build a while loop that had 2 nested loops inside it which could be accessed by the keypress of the key m or the key a. the individual while loops themselves seem to function exactly as they should, but the code seems to require multiple keypresses of the key m or a to access the two erespective nested loops. I can't seem to locate/understand if the problem lies in my code itself or in perhaps my incorrect understanding of the use of the cv2.waitKey syntax. does anyone have experience with this and could perhaps help me understand where my error lies (if any)m or perhps guide me so as to help design my loop better?

while True:
        # Read a frame from the video capture object
    ret, live = camera.read()  #read live feed
    gray = cv2.cvtColor(live, cv2.COLOR_BGR2GRAY)
    key=cv2.waitKey(1) & 0xFF
    #bg=None
    # If the frame was successfully read
    if ret:
        # Display the frame if the 'r' key is pressed
        key=cv2.waitKey(1)  & 0xFF #to run live feed smoothly
        if key == ESCAPE_KEY:
            exit()
        if show_video:
          cv2.imshow('angio sim', live)  #create a blank window
        
          # Wait for a key press and check if the 'r' key is pressed
          key=cv2.waitKey(1)  & 0xFF #for making the live feed run smoothly
        if key == ord('r'): #if condition for keypress r
          show_video = True  #change value of flag          
        elif not keyboard.is_pressed('r'):
          show_video = False
        if key==ord('s'):
                 target = pyautogui.getActiveWindow()
                 location = (
                 target.left,
                 target.top,
                 target.width,
                 target.height
                 )
                 image = pyautogui.screenshot(region=location)
                 now = datetime.now() #get current date and time
                 dt_string = now.strftime("%Y-%m-%d-%H-%M-%S")
                 image.show()
                 filename1 = 'Screenshot_' + dt_string  +'.jpg'
                 image=image.save(filename1)
                 # Get the handle of the window by its title
        if key==ord('m'):
                 flag=Roadmap
                  # initialize a frame counter
        count = 1
        ret, frame = camera.read()
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        acc = gray.astype('float')  
           
        # Loop through the frames in the video              
        while flag==Roadmap:
                # Read the next frame
                ret, frame = camera.read()
                if not ret:
                    break
                gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

                #acc = gray.astype('float')  
                # Check for user input
                key=cv2.waitKey(1)
                if key == 27:  # Escape key
                    flag=False
                elif key == ord('r'):
                 # Compute the minimum blend of the current frame and the accumulator
                 acc = np.minimum(acc, gray.astype('float'))

                 # Increment the frame counter
                 count += 1

                 # Convert the blended frame to an unsigned 8-bit integer
                 blended = acc.astype('uint8')

                 # Display the blended frame
                 cv2.imshow("angio sim", blended)
                elif key == ord('d'):
                 # Compute the difference between the current frame and the blended frame
                 result = cv2.subtract(gray, blended)
                 # Set the result to white
                 result = cv2.cvtColor(result, cv2.COLOR_GRAY2BGR)
                 result[np.where((result == [255, 255, 255]).all(axis=2))] = [0, 0, 255]
                 # Set the background to light gray
                 background = np.zeros_like(result)
                 background.fill(192)
                 # Combine the background and the result
                 output = cv2.addWeighted(background, 0.5, result, 0.5, 0.0)

                    # Display the difference frame
                 cv2.imshow("angio sim", output)
        if key==ord('a'):
                 flag=DSA
                 ret, live = camera.read()  #read live feed
                 gray = cv2.cvtColor(live, cv2.COLOR_BGR2GRAY)
                 key=cv2.waitKey(1) & 0xFF
        while flag==DSA:
                 print ('hello')
                 ret, live = camera.read()  #read live feed
                 gray = cv2.cvtColor(live, cv2.COLOR_BGR2GRAY)
                 key=cv2.waitKey(1) & 0xFF   
                 if ret:
                  
                   # Display the frame if the 'r' key is pressed
                   key=cv2.waitKey(1)  & 0xFF #to run live feed smoothly
                   if key == ESCAPE_KEY:
                     flag=False
                   if show_video:
                     cv2.imshow('angio sim', live)  #create a blank window
                     key=cv2.waitKey(1)
                     # Wait for a key press and check if the 'r' key is pressed
                     key=cv2.waitKey(1)  & 0xFF #for making the live feed run smoothly
                   if key == ord('r'): #if condition for keypress r
                     show_video = True  #change value of flag
                     bg=None
                     key_pressed=True
                     now = datetime.now() #get current date and time
                     dt_string = now.strftime("%Y-%m-%d-%H-%M-%S")
                     filename = 'Backgroundat1fps_'+ dt_string +'.jpg'          
                   if key_pressed and  not keyboard.is_pressed('r'):
                     bg=gray
                     #print(bg.shape)
                     font = cv2.FONT_HERSHEY_PLAIN
                     now_without_ms= now.strftime('%Y-%m-%d %H:%M:%S')

                     cv2.putText(bg, str(now_without_ms), (20, 40), font, 2, (255, 255, 255), 2, cv2.LINE_AA)
                     now = datetime.now() #get current date and time
                     cv2.imwrite(filename,bg)
                     maske=live
                     gray_mask=cv2.cvtColor(live, cv2.COLOR_BGR2GRAY)
                     key_pressed=False# to freeze live feed
                   if key==ord('a'):
                     flag=DSA
                   if key==ord('m'):
                     flag =Roadmap
                   if key==ESCAPE_KEY:
                     flag=False 
                   elif not keyboard.is_pressed('r'):
                     show_video = False
                   if key == ord('d'):
                     diff = cv2.absdiff(gray, bg)
                     inverted_diff= cv2.bitwise_not(diff)
                     diff_colormap = cv2.applyColorMap(diff, cv2.COLORMAP_BONE)
                     cv2.imshow('angio sim', inverted_diff)
                     key=cv2.waitKey(1)
                   if key==ord('s'):
                     path = r'C:/Users/skhandelwal/Desktop/Dsa Simulator'
                     os.chdir(path)
                     target = pyautogui.getActiveWindow()
                     location = (
                     target.left,
                     target.top,
                     target.width,
                     target.height
                     )
                     image = pyautogui.screenshot(region=location)
                     now = datetime.now() #get current date and time
                     dt_string = now.strftime("%Y-%m-%d-%H-%M-%S")
                     image.show()
                     filename1 = 'Screenshot_' + dt_string  +'.jpg'
                     image=image.save(filename1)                        
                     
                   else:
                      key=cv2.waitKey(1)

the code itself us expected to run three "modes" depending on whether no keyy is pressed or the key m or the key a. the three while loops themselves seem to function perfectly well on their own, but the access to those nested loops seem to require more than one keypress of a or m or the escape key respectively, I fail to understand if the problem lies in my use of the cv2.waitKey command or in my loop design itself... could someone help me understand it better and learn the right way to get my loop to recognise the keypress at once? I feel like i've hit a wall with this problem.

0

There are 0 best solutions below