背景:
在做圖像識別處理時候,通過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()