Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cv2 imshow doesnt open window again after closing and opening again, when used with threads

In the sample code below,

import cv2
from threading import Thread

class Person_Item_Association(object):
    def __init__(self):
        self.stop = False

    def start_camera(self):
        self.stop =False
        camera_thread = Thread(target=self.start_analysis)
        camera_thread.start()

    def stop_camera(self):
        self.stop = True

    def start_analysis(self):
        cap = cv2.VideoCapture(0)

        while not self.stop:
            ret,image = cap.read()
            cv2.imshow("frame",image)
            cv2.waitKey(1)

        cap.release()
        print("resource released")
        cv2.destroyAllWindows()

I do the following sequence, call obj.start_camera(), obj.stop_camera(), cv2.imshow() opens a window , but when i again do obj.start_camera() and obj.stop_camera(), it doesn't open a window. What is wrong here ?

like image 322
avaj Avatar asked Nov 30 '25 21:11

avaj


1 Answers

You can use multiprocessing module instead of threading modeule to mitigate the issue. But I am still unable to find how to fix this with threading.

Take a look at a similar question.

like image 109
shashank2806 Avatar answered Dec 03 '25 10:12

shashank2806



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!