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:[email protected]: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:[email protected]: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()




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章