使用RTSP Feed的Python多处理

2024-05-18 23:31:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,刚刚习惯了线程技术——我成功地创建了第一个工作正常的脚本,但它没有同时运行作业,而是对作业进行了查询。你知道吗

基本上我打开我的家庭闭路电视摄像头饲料-我有5个摄像头,但因为他们是线程打开,他们只显示图像每秒钟可以。我已经研究过了,我认为我需要使用多处理而不是线程。你知道吗

以下是我使用线程的现有代码-删除了一些额外的部分:

from threading import Thread
import imutils
import cv2, time
import argparse
import numpy as np
import datetime
import time

from multiprocessing import Process

camlink1 = "rtsp://link1"
camlink2 = "rtsp://link2"
camlink3 = "rtsp://link3"
camlink4 = "rtsp://link4"
camlink5 = "rtsp://link5"

class VideoStreamWidget(object):
    def __init__(self, link, camname, src=0):
        self.capture = cv2.VideoCapture(link)
        self.capture.set(cv2.CAP_PROP_FPS, 2)


        # Start the thread to read frames from the video stream
        self.thread = Thread(target=self.update, args=())
        self.thread.daemon = True
        self.thread.start()
        self.camname = camname
        self.link = link


    def update(self):
        # Read the next frame from the stream in a different thread
        while True:
            if self.capture.isOpened():
                (self.status, self.frame) = self.capture.read()

    def show_frame(self):

        try:

            # Display frames in main program
            frame = self.frame
            (h, w) = frame.shape[:2]

            cv2.imshow('Frame ' + self.camname, frame)
            key = cv2.waitKey(1)

            if key == ord('q'):
                self.capture.release()
                cv2.destroyAllWindows()
            exit(1)     
            time.sleep(.05)
        except AttributeError:
            print("[ISSUE] Problem with " + self.camname + "...")
            self.capture = cv2.VideoCapture(self.link)
            print("[INFO] Reconnected with " + self.camname + "...")
            pass

if __name__ == '__main__':
    video_stream_widget = VideoStreamWidget(camlink1,"Cam1")
    video_stream_widget2 = VideoStreamWidget(camlink2,"Cam2")
    video_stream_widget3 = VideoStreamWidget(camlink3,"Cam3")
    video_stream_widget4 = VideoStreamWidget(camlink4,"Cam4")
    video_stream_widget5 = VideoStreamWidget(camlink5,"Cam5")

    while True:
        video_stream_widget.show_frame()
        video_stream_widget2.show_frame()
        video_stream_widget3.show_frame()
        video_stream_widget4.show_frame()
        video_stream_widget5.show_frame() 

正如你在底部看到的,我创建了5个不同的“视频流小部件”,但我不知道这是最佳实践。有人能告诉我如何修改这段代码,使其使用多处理而不是线程处理吗?你知道吗

我尝试了一种将“线程”改为“进程”的基本方法,但没有成功。你知道吗

谢谢 克里斯


Tags: fromimportselfstreamvideoshowlink线程

热门问题