用处:可自由关闭和打开摄像头,同时可进行处理其他事物
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 26 16:30:08 2022
@author: victor
"""
import threading
import cv2, time
# 视频流线程
class VideoStreamThread(threading.Thread):
def __init__(self, src=0,sleep_time=0.01):
self._stop_event = threading.Event()
self._sleep_time = sleep_time
self.capture = cv2.VideoCapture(src)
"""call base class constructor"""
super().__init__()
def update(self):
# Read the next frame from the stream in a different thread
if self.capture.isOpened():
(self.status, self.frame) = self.capture.read()
self._stop_event.wait(self._sleep_time)
def run(self):
while not self._stop_event.isSet():
#do work
self.update()
self.show_frame()
def show_frame(self):
# Display frames in main program
cv2.imshow('frame', self.frame)
cv2.waitKey(1)
def join(self, timeout=None):
"""set stop event and join within a given time period"""
self._stop_event.set()
self.capture.release()
cv2.destroyAllWindows()
super().join(timeout)
if __name__ == '__main__':
video_stream_thread = VideoStreamThread()
video_stream_thread.start()
time.sleep(5)
video_stream_thread.join()
if(video_stream_thread.is_alive()==False):
video_stream_thread = VideoStreamThread()
video_stream_thread.start()
time.sleep(5)
video_stream_thread.join()