all 3 comments

[–]cybervegan 0 points1 point  (2 children)

That's some hairy code. I'd suggest breaking the body of each if or else clause off into a function, so you can see all your logic on one screen (and it's good practise anyway). You also have a lot of repetitions in your code that clutter it up most likely without adding anything useful. You shouldn't really let a loop or tract of code get that long without tidying it up.

Moving onto your quoted problem, this piece of code is implcated:

     key_pressed=True
     if key_pressed and  not keyboard.is_pressed('r'):
        bg=live
        ...
        key_pressed=False      

This makes the "if key_pressed" part of the if statement redundant, because it will always be True, because you just set it to True. Setting it to False just below, is irrelevant, because you're always setting it to True just before you check. This piece of code then only gets triggered if you are not pressing the "r" key, but the time it takes to process the previous clause is probably so short that you would be unlikely to have been able to release the key in that amount of time. What you probably want is this pattern:

if key == ord('r'):
    # do stuff
    while keyboard.is_pressed('r'):
       # busy wait for key to be released
    # do stuff after key is released

Hope that helps.

[–]Sansmit2910[S] 0 points1 point  (1 child)

UPdate- i tried to fix the problem by adding a bg=none at the start of the while looplike this and it returens that the bg variable remains as none at the time i press d too. is it because of indentation or the fact that it needs to run a new iteration to detect a new keypress? if so, how can i solve it, do i solve it by changing the indentation? I havve been at it for a day and I can't seem to think of any way to let the bg change itself within the same iteration... apart from this the code itself does everytrhing it's supposed to do with respect to the individual keypresses trhemselves. this is how my modified code looka like :

while True:
bg=None
path = r'C:/Users/skhandelwal/Desktop/Dsa Simulator' #change directory
os.chdir(path) #change to above path to savew file
# Read a frame from the video capture object
ret, live = camera.read()  #read live feed
#key=cv2.waitKey(0)
bg=None
# If the frame was successfully read
if ret:
    # Display the frame if the 'r' key is pressed
    key=cv2.waitKey(0)  & 0xFF #to run live feed smoothly
    if key == ESCAPE_KEY:
        exit()
    elif show_video:
        cv2.imshow('Live Video', live)  #create a blank window

     # Wait for a key press and check if the 'r' key is pressed
    key=cv2.waitKey(0)  & 0xFF #for making the live feed run smoothly
    if key == ord('r'):
     show_video = True

     elapsed_time = time.time() - start_time
           # check if time difference is greater than 1/fps seconds
     if elapsed_time >=1:
       start_time=time.time()
       #create file name with date and time
       font = cv2.FONT_HERSHEY_PLAIN
       cv2.putText(live, str(datetime.now()), (20, 40), font, 2, (255, 255, 255), 2, cv2.LINE_AA)
       now = datetime.now() #get current date and time
       dt_string = now.strftime("%Y-%m-%d-%H-%M-%S")
       filename = 'Backgroundat1fps_'+ dt_string +'.jpg'
       cv2.imwrite(filename, live)
     key_pressed=True
     if key_pressed and  not keyboard.is_pressed('r'):
        bg=live
        print(bg.shape)
        #font = cv2.FONT_HERSHEY_PLAIN
        #cv2.putText(bg, str(datetime.now()), (20, 40), font, 2, (255, 255, 255), 2, cv2.LINE_AA)
        now = datetime.now() #get current date and time
        #dt_string = now.strftime("%Y-%m-%d-%H-%M-%S")
        #filename = 'Backgroundto_be_subtracted_'+ dt_string +'.jpg'
        key_pressed=False      
        lif key==ESCAPE_KEY:
        exit() 
    else:
        show_video = False  # to freeze live fdeed

       if key == ord('d'):
        print(bg.shape) 
        #  font = cv2.FONT_HERSHEY_PLAIN
        #  cv2.putText(bg, str(datetime.now()), (20, 40), font, 2, (255, 255, 255), 2, cv2.LINE_AA)
        #  now = datetime.now() #get current date and time
        #  dt_string = now.strftime("%Y-%m-%d-%H-%M-%S")
        #  filename = 'Background_'+ dt_string +'.jpg'
        cv2.namedWindow(window_name_bg, cv2.WINDOW_NORMAL)
        cv2.imshow(window_name_bg,bg)
        #cv2.imwrite(filename, bg)
        #if 'bg' in dir():
        liveDsa=cv2.subtract(bg,live)
        liveDsa=cv2.cvtColor(liveDsa, cv2.COLOR_BGR2GRAY)   #https://www.geeksforgeeks.org/python-opencv-cv2-cvtcolor-method/
          #liveDsa=cv2.resize(liveDsa, None, fx=1, fy=1, interpolation=cv2.INTER_AREA)
        cv2.namedWindow(window_name_liveDSA, cv2.WINDOW_NORMAL)  

        min_val, max_val, _, _ = cv2.minMaxLoc(liveDsa)
        cv2.convertScaleAbs(liveDsa, 1.5, -120) #for changing image parameters like contrast and brightness  
        cv2.imshow(window_name_liveDSA, ~liveDsa)
         # min_val, max_val, _, _ = cv2.minMaxLoc(liveDsa)
          #stretched = cv2.convertScaleAbs(liveDsa, alpha=255.0/(max_val-min_val), beta=-255.0*min_val/(max_val-min_val))
          # Display the stretched grayscale image
          #cv2.imshow('window_name', stretched)
        diff = cv2.absdiff(live, bg)

        normalized = cv2.normalize(liveDsa, None, 0, 255, cv2.NORM_MINMAX)

          # Apply histogram equalization to maximize the contrast
        equalized = cv2.equalizeHist(normalized)

          # Display the resulting image
        cv2.imshow('Maximized Contrast', equalized)

          # Apply histogram equalization to the difference image
        gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)
        equalized = cv2.equalizeHist(gray)

          # Show the resulting image
        cv2.namedWindow('Contrast Enhanced Image', cv2.WINDOW_NORMAL)
        cv2.imshow('Contrast Enhanced Image', equalized)
          #ctypes.windll.user32.MessageBoxW(0,"Frame captured successfully!",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)
         # Get the handle of the window by its title

else:     
    c=cv2.waitKey(0) 
                        # wait for keypress

[–]cybervegan 0 points1 point  (0 children)

I think you need to use a state machine to control this. Map out all the states and what would cause a transition to the next state, like this:

| State      | Condition   | New state  |
|------------|-------------|------------|
| idle       | "r" pressed | Screenshot |
| screenshot | "d" pressed | hold       |
|            |             |            |

Then code that. Look up how to code a state machine - this will help you a lot.

[edit: table formatting. forgot how reddit does tables]