python3用消费者和生产者模型,实现视频流读取播放

背景:

    在做图像识别处理时候,通过opencv读入RTSP流,解码成每一帧,对每一帧做算法处理,结果会出现解码错误,然后视频读取就卡死。因此采用消费者-生产者模型,通过生产者线程进行生成(读入视频帧)存入queue队列,再通过消费者线程对视频帧进行消费处理。

代码如下:

from queue import Queue
import threading
import cv2
import time,random

class Producer(threading.Thread):
    """docstring for ClassName"""
    def __init__(self, frame_queue):
        super(Producer, self).__init__()
        self.frame_queue = frame_queue

    def run(self):
        print('in producer')
        cap = cv2.VideoCapture('rtsp://admin:passwd@10.130.10.111:554/MPEG-4/ch1/main/av_stream')
        print('cap is open',cap.isOpened())
        while True:
            ret,image = cap.read()
            print('get frame = ',ret)
            if (ret == True):
                self.frame_queue.put(image)
            else:
                cap = cv2.VideoCapture('rtsp://admin:passwd@10.130.10.111:554/MPEG-4/ch1/main/av_stream')
                print('cap is open',cap.isOpened())
                # continue

class Consumer(threading.Thread):
    """docstring for Consumer"""
    def __init__(self, frame_queue):
        super(Consumer, self).__init__()
        self.frame_queue = frame_queue

    def run(self):
        print('in consumer')
        while True:
            print('frame_queue size=',self.frame_queue.qsize())
            frame = self.frame_queue.get()
            cv2.imshow('cap video',frame)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                videoWriter.release()
                cap.release()
                cv2.destroyAllWindows()
                break


if __name__ == '__main__':

    print('run program')
    #定义队列
    frame_queue = Queue()
   
    producer = Producer(frame_queue)
    producer.daemon = True
    producer.start()

    print('run  Consumer')
    consumer = Consumer(frame_queue)
    consumer.daemon = True
    consumer.start()

    producer.join()
    consumer.join()




评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值