目前接触到的视频保存方法有两种,一种是cv2.VideoWriter,另一种是imageio,对比下来imageio保存的录像文件要比opencv保存的小很多,具体原因暂时不清楚。
存在的问题:
imageio保存的视频不能获得视频总帧数这个属性
import imageio
import cv2
from tqdm import tqdm
class MyVideoWriter:
def __init__(self, save_path, height=None, width=None, fps=25):
self.save_path = save_path
self.height = height
self.width = width
self.fourcc = cv2.VideoWriter_fourcc(*'mp4v')
self.cur_frame_id = -1
self.fps = fps
self.videoWriter = None
def save(self, frame):
self.cur_frame_id += 1
if self.cur_frame_id == 0:
if self.height is None or self.width is None:
self.height, self.width, _ = frame.shape
self.videoWriter = cv2.VideoWriter(self.save_path, self.fourcc, self.fps, (self.width, self.height))
self.videoWriter.write(frame)
def release(self):
if self.videoWriter:
self.videoWriter.release()
self.videoWriter = None
def __del__(self):
self.release()
# reader = imageio.get_reader("io.mp4")
# for frame in tqdm(reader):
# print("xxxx")
# print(imageio.get_reader("cv.mp4").get_meta_data())
# cv_reader = cv2.VideoCapture("cv.mp4")
# print(cv_reader.get(5), cv_reader.get(7))
fps = 10
cv_writer = MyVideoWriter("cv.mp4",fps=fps)
io_writer = imageio.get_writer("io.mp4", fps=fps)
rtsp = "rtsp://xxxxxxxxxxxxxxxxxxxxxx"
cap = cv2.VideoCapture(rtsp)
# cap = imageio.get_reader(rtsp)
# print(cap.get_meta_data())
for _ in range(1000):
ret, frame = cap.read()
cv_writer.save(frame)
io_writer.append_data(frame[...,::-1])
cv_writer.release()
io_writer.close()
cap.release()