我是python的新手,刚刚习惯了线程处理-很好地管理了我的第一个脚本,该脚本运行良好,但是却查询了作业,而不是同时运行它们。
基本上,我打开了我的家用CCTV摄像机供稿-我有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个不同的“ video_stream_widget”,但我不认为这是最佳做法。有人可以指导我如何更改此代码,以便它使用多处理而非线程处理吗?
我尝试了一种将“线程”更改为“进程”的基本方法,但这没有用。
谢谢 克里斯