我的 pytorch 模型的 FPS 较低且延迟较多

问题描述 投票:0回答:1

我的任务是使用 OpenCV 处理来自 Hikvision IP 摄像机的流视频。最初,视频的 FPS 约为 20-25,有 2-3 秒的延迟。然而,随着代码运行时间的延长,FPS 会迅速下降,延迟也会增加。最终,FPS 下降到 2-3,视频冻结。

class VideoLoader:
    @staticmethod
    def load_video(video_path):
        cap = cv2.VideoCapture(video_path)
        cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter.fourcc('M', 'J', 'P', 'G'))
        cap.set(cv2.CAP_PROP_FPS, 25)
        cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
        cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)  
        assert cap.isOpened(), "Video dosyası okunurken hata oluştu"
        return cap

我尝试过使用GPU、采用多线程、降低分辨率等方法,但效果都不是很好。您认为问题是什么?我该如何解决它

def frame_reader(cap, frame_queue):
    while cap.isOpened():
        success, frame = cap.read()
        if not success:
            break
        if not frame_queue.full():  # Check if the queue has space
            frame_queue.put(frame)
    cap.release()
    frame_queue.put(None)  # End-of-stream signal

def video_processor(frame_queue, output_queue, model, class_names, played_sounds):
    threshold = 0.5  # Tespit eşik değeri
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    model.to(device)

    while True:
        frame = frame_queue.get()
        if frame is None:  # End-of-stream signal
            break
        start_time = time.time()
        img = cv2.resize(frame, (640, 480))
        img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        img_tensor = torch.from_numpy(img_rgb).permute(2, 0, 1).float().unsqueeze(0).to(device)
        img_tensor /= 255.0  # Normalize

def video_detection(video_source):
    cap = VideoLoader.load_video(video_source)
    model = YOLO("YOLO-Weights/ppe.pt")
    class_names = ['safety-glasses', 'gloves', 'orange-vest', 'yellow-vest',]
    played_sounds = set()

    frame_queue = Queue(maxsize=5)
    output_queue = Queue(maxsize=5)

    reader_thread = threading.Thread(target=frame_reader, args=(cap, frame_queue), daemon=True)
    processor_thread = threading.Thread(target=video_processor, args=(frame_queue,output_queue, model,class_names, played_sounds), daemon=True)

    reader_thread.start()
    processor_thread.start()
python opencv machine-learning pytorch rtsp
1个回答
0
投票

在工作笔记本电脑和家用电脑上进行了测试(添加了 yolov8 作为计数器)

工作笔记本电脑使用CPU进行解码,家用PC使用GPU

结果: - 笔记本电脑 CPU 几乎达到 100%,出现掉帧和持续死机的情况 (1080p) -家用电脑完全不卡顿、不掉帧(4k)

在这两种情况下我都使用了 IP 摄像机 rtsp 流。

您能否确认您的硬件有资源来解决这个问题?

© www.soinside.com 2019 - 2024. All rights reserved.