我正在尝试创建一个python程序,通过实时摄像头进行自动瞳孔检测。我的程序有多个线程从我的相机获取图像,分析代码并显示相机源的编辑版本。
由于我是线程新手,我当前的代码只显示相机Feed的负片。运行时,程序按预期工作。但是,如果我在关闭cv2窗口后第二次尝试运行代码,程序将无法正常工作。我的相机开启(如预期的那样)但是,新的cv2窗口无法打开。我需要重新打开我的ide(spyder)才能使程序再次正常工作。
我认为这可能是由于我的线程没有正确终止,但是,鉴于我在该领域缺乏经验,我不确定。如果我跑
threading.current_thread()
在我关上窗户后,我得到了
<_MainThread(MainThread, started 2468)>
我很欣赏任何有关问题所在的见解。
我的代码:
frame_to_detect = None
filtering = True
filter_frame = None
view = True
stopper = None
class Filter(Thread):
#indenting got mess up here
def __init_(self):
Thread.__init__(self)
def run(self):
global frame_to_detect
global filter_frame
while view:
if frame_to_detect is not None:
filter_frame = 255-frame_to_detect
class displayFrame(Thread):
#indenting got messed up here
def __init__(self):
Thread.__init__(self)
def run(self):
global view
while view:
if filter_frame is not None:
cv2.imshow('frame',filter_frame)
if (cv2.waitKey(1) & 0xFF == ord('q')):
view = False
Filter_thread = Filter()
Filter_thread.daemon = True
Filter_thread.start()
display = displayFrame()
display.daemon = True
display.start()
video_capture = cv2.VideoCapture(filepath)
while view:
ret,frame_to_detect = video_capture.read()
filtering = False
video_capture.release()
cv2.destroyAllWindows()
当你关闭cv2窗口时,线程继续在后台运行。 cv2.imshow的线程最终会超时。但是为了加快速度,你可以让线程以异常关闭。如
thread.raise_exception()
thread.join()