优化视频保存Python的Opencv代码
我已经编写了一段python代码,其中我正在使用优化视频保存Python的Opencv代码,python,multithreading,opencv,video-processing,Python,Multithreading,Opencv,Video Processing,我已经编写了一段python代码,其中我正在使用opencv显示和保存实时摄影机流,并制作10分钟的剪辑 我已经为100多台摄像机做了这项工作,但目前我正在为5台摄像机做这项工作(通过从一台摄像机中获取多个流) 现在,问题是我的脚本消耗了大约12%的CPU和125 MB的RAM。它不可能处理100多个摄像头。因此,我想优化代码,使其消耗很少的资源,这将有助于我运行100个摄像头 如果使用opencv无法做到这一点,我甚至准备换一个不同的库 代码: IMHO这不是优化一个简单的Python脚本,而
opencv
显示和保存实时摄影机流,并制作10分钟的剪辑
我已经为100多台摄像机做了这项工作,但目前我正在为5台摄像机做这项工作(通过从一台摄像机中获取多个流)
现在,问题是我的脚本消耗了大约12%的CPU和125 MB的RAM。它不可能处理100多个摄像头。因此,我想优化代码,使其消耗很少的资源,这将有助于我运行100个摄像头
如果使用opencv
无法做到这一点,我甚至准备换一个不同的库
代码:
IMHO这不是优化一个简单的Python脚本,而是回到绘图板。让我们忘记可视化,考虑减压是可以忽略不计的。现在,您解压缩每个传入帧,然后再次压缩它。对于
640x480x3x10字节/秒或大约9 MB/s的每个流。对于其中100个,这接近每秒1千兆字节(大致相当于每秒110帧的超高清(4k)视频)。因此,我要问的第一件事是,哪种编解码器可以在空闲时间内处理这个问题,以及它需要什么样的硬件来处理这个问题。
# organize imports
import numpy as np
import cv2
import time
from threading import Thread
def multi_stream(video_id):
start_time = time.time()
count = 1
# This will return video from the first webcam on your computer.
cap = cv2.VideoCapture("rtsp://admin:vaaan@123@192.168.1.51/Streaming/Channels/2")
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('Output_{}/{}.avi'.format(video_id, count), fourcc, 10, (640, 480))
# loop runs if capturing has been initialized.
while(True):
# reads frames from a camera
# ret checks return at each frame
ret, frame = cap.read()
# output the frame
out.write(frame)
# this will help to create 10 min video clips
if time.time() - start_time >= 600:
count += 1
start_time = time.time()
out = cv2.VideoWriter('Output_{}/{}.avi'.format(video_id, count), fourcc, 10, (640, 480))
# The original input frame is shown in the window
cv2.imshow('Original_{}'.format(video_id), frame)
# Wait for 'a' key to stop the program
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Close the window / Release webcam
cap.release()
# After we release our webcam, we also release the output
out.release()
# De-allocate any associated memory usage
cv2.destroyAllWindows()
t1 = Thread(target=multi_stream, args=(1,))
t2 = Thread(target=multi_stream, args=(2,))
t3 = Thread(target=multi_stream, args=(3,))
t4 = Thread(target=multi_stream, args=(4,))
t5 = Thread(target=multi_stream, args=(5,))
t1.start()
t2.start()
t3.start()
t4.start()
t5.start()