0

I have a python 3.7 and OpenCV 3 programming running on windows 10 and raspberry pi. The program has three threads. The first thread is a main loop, the second thread is a camera, and the third thread is writing videos and images. I searched many references and put together what I think is a way to catch the correct "stop" keyboard signals. I tested on win10 and RPI using the threading packages and it appears to work. I am wondering if there is a more approriate way to handle keyboard input? I had to put the keyboard handler in main as I wasn't able to catch it in the wile loop. The following example doesn't show threading but in my larger program it worked also.

import signal
import cv2


class main():
    def __init__(self):
        self.stop_by_signal = False
        return  

    def signal_term_handler(self,signal, frame):
        self.stop_by_signal = True
        return


    def run(self):
        signal.signal(signal.SIGTERM, self.signal_term_handler)
        self.cap = cv2.VideoCapture(0)
        print("starting")

        while True:
        # read cameras and display
            ret, frame = self.cap.read()
            if not ret: break
            cv2.imshow('frame',frame)

            # look for kill, ctl-c or cv2.waitkey to stop
            if self.stop_by_signal == True:
                print("main: stopping loop via kill")
                break
            key = cv2.waitKey(1) & 0xFF
            if key == ord('q') or key == 27:
                print("main: cv2 esc or q entered to stop")
                break
            elif key != 255:
                print('key: %s' % [chr(key)])

        self.cap.release()
        cv2.destroyAllWindows()

if __name__ == '__main__':
    try:
        main = main()
        main.run()

    except KeyboardInterrupt:
        main.cap.release()
        print("__main:__ ctl-c entered to stop.")
PeterB
  • 156
  • 1
  • 5

1 Answers1

0

Looks like it is working well. For the kill command, it works without the -9 option.

PeterB
  • 156
  • 1
  • 5