最好的方法是使用线程,
这是我的代码来实现这个目标。
"""
This module contains the Streamer class, which is responsible for streaming the video from the RTSP camera.
Capture the video from the RTSP camera and store it in the queue.
NOTE:
You can preprocess the data before flow from here
"""
import cv2
from queue import Queue
import time
from env import RESOLUTION_X, RESOLUTION_Y,FPS
from threading import Thread
class Streamer:
def __init__(self,rtsp):
"""
Initialize the Streamer object, which is responsible for streaming the video from the RTSP camera.
stream (cv2.VideoCapture): The VideoCapture object.
rtsp (str): The RTSP url.
Q (Queue): The queue to store the frame.
running (bool): The flag to indicate whether the Streamer is running or not.
Args:
rtsp (str): The RTSP url.
"""
print("Creating Streamer object for",rtsp)
self.stream = cv2.VideoCapture(rtsp)
self.rtsp = rtsp
self.stream.set(cv2.CAP_PROP_FRAME_WIDTH, RESOLUTION_X)
self.stream.set(cv2.CAP_PROP_FRAME_HEIGHT, RESOLUTION_Y)
self.Q = Queue(maxsize=2)
self.running = True
print("Streamer object created for",rtsp)
def info(self):
"""
Print the information of the Streamer.
"""
print("==============================Stream Info==============================")
print("| Stream:",self.rtsp,"|")
print("| Queue Size:",self.Q.qsize(),"|")
print("| Running:",self.running,"|")
print("======================================================================")
def get_processed_frame(self):
"""
Get the processed frame from the Streamer.
Returns:
dict: The dictionary containing the frame and the time.
"""
if self.Q.empty():
return None
return self.Q.queue[0]
def release(self):
"""
Release the Streamer.
"""
self.stream.release()
def stop(self):
"""
Stop the Streamer.
"""
print("Stopping",self.stream,"Status",self.rtsp)
self.running = False
def start(self):
"""
Start the Streamer.
"""
print("Starting streamer",self.stream, "Status",self.running)
while self.running:
ret, frame = self.stream.read()
if not ret:
print("NO Frame for",self.rtsp)
continue
frame =cv2.resize(frame,(RESOLUTION_X,RESOLUTION_Y))
if not self.Q.full():
print("Streamer PUT",self.Q.qsize())
self.Q.put({"frame":frame,"time":time.time()})
print("Streamer PUT END",self.Q.qsize())
self.release()
if __name__ == "__main__":
streamer = Streamer("rtsp://localhost:8554/105")
thread = Thread(target=streamer.start)
thread.start()
while streamer.running:
data = streamer.get_processed_frame()
if data is None:
continue
frame = data["frame"]
cv2.imshow("frame",frame)
cv2.waitKey(1)