101
101

Reputation: 8999

OpenCV imshow window cannot be reused when called within a thread

I'm having trouble using cv2 imshow when run in a separate python thread.

The code below works for the first call of start_cam, but the second call fails - the cv2 camera window does not reappear. This seems to have something to do with threading prevent that window being reused, because:

If the cv2 window is given a random name then it works indefinitely, although the window is not being reused as each window is new of course.

If _cam_loop() is called without threading this it also works and the same window can be reused indefinitely.

def start_cam(self):
    self.cam_live = True
    threading.Thread(target = self._cam_loop).start()

def stop_cam(self):
    self.cam_live = False

def _cam_loop(self):
    while self.cam_live:
        img = self.cam.get_image()
        cv2.imshow("cam", img)
        cv2.waitKey(1)

self.start_cam()   # live image window appears
self.stop_cam()    # image window disappears (as thread is killed)
self.start_cam()   # window fails to reappear

The window disappears when the thread finishes. Is there a way to keep a reference to the window after the thread finishes?

Upvotes: 3

Views: 6459

Answers (1)

101
101

Reputation: 8999

I didn't find a way to keep a reference to the named window, but if the window is destroyed it can be reused each time the thread is called. I simply added cv2.destroyAllWindows() to the end of the thread function and it worked. Curious to know why exactly.

def _cam_loop(self):
    while self.cam_live:
        img = self.cam.get_image()
        cv2.imshow("cam", img)
        cv2.waitKey(1)
        cv2.destroyAllWindows()

Upvotes: 3

Related Questions