Python设置额外线程处理图像

用处:可自由关闭和打开摄像头,同时可进行处理其他事物

# -*- 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()
        
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值