0

I followed this program tutorial that captures the screen and puts it in a video file. The recording stops when the 'q' button is pressed. However, I didn't want to show the screen in a mini window and just write straight to the file. I am just calling the while loop shown in the tutorial except that I didn't include the part about showing the image to the 'Live' window. Now when I use:

while True:
    img = pyautogui.screenshot()
    frame = np.array(img)
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    out.write(np.array(frame))
    # cv2.imshow('Live', frame)
    if cv2.waitKey(1) == ord('q'):
        print('done')
        break

it won't detect my pressing q. What is going on here? When I press q the loop should stop right? I am just getting a 44 bit mp4 file as an end result from this. I think it might be because I didn't use imshow so waitkey won't do anything but I am not sure. Is there a way to get it to stop recording on a key press?

James Huang
  • 848
  • 1
  • 7
  • 35

2 Answers2

2

It's very likely that waitKey() doesn't do anything unless there's a window, since it's likely related to a window key event handler.

If you're on Windows, you could try msvcrt.kbhit(), which is a non-blocking call to request whether a key has been pressed on the console and could be read.

On other platforms, waiting for a keypress in a non-blocking manner might be non-trivial.

AKX
  • 152,115
  • 15
  • 115
  • 172
  • When I called it, it doesn't seem to return True even when I am pressing a key. Is there a particular textbox I have to press the key in for it to return something? I heard of something called getch from the same module which returns the exact keys pressed but I'm not sure if that will help me – James Huang Mar 08 '21 at 06:53
  • Not a text box, but the console window your app is running in. If you're running in an IDE or something, `getch()` might not work. – AKX Mar 08 '21 at 09:23
2

I think, you are right in assuming that since you didn't start the display(ie., cv2.imshow()) the cv2.watikey() doesn't work. Since your goal is to stop recording on key press I think you can follow this link's suggestion. or try this pattern:

try:
    while True:
        break
        #replace break with your code

except KeyboardInterrupt:
    print("Press Ctrl-C to terminate while statement")
    pass