1 读取视频为numpy数组以及将numpy数组转换为视频
1.1 读取视频为numpy数组
def video_to_numpy_array(video_path):
rgb_frame_list = []
video_read_capture = cv2.VideoCapture(video_path)
while video_read_capture.isOpened():
result, frame = video_read_capture.read()
if not result:
break
rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
rgb_frame_list.append(rgb_frame)
video_read_capture.release()
video_nparray = np.array(rgb_frame_list)
return video_nparray
1.2 将numpy数组转换为视频
def numpy_array_to_video(numpy_array,video_out_path):
video_height = numpy_array.shape[1]
video_width = numpy_array.shape[2]
out_video_size = (video_width,video_height)
output_video_fourcc = int(cv2.VideoWriter_fourcc(*'mp4v'))
video_write_capture = cv2.VideoWriter(video_out_path, output_video_fourcc, 30, out_video_size)
for frame in numpy_array:
video_write_capture.write(frame)
video_write_capture.release()
1.3 使用示例
# -*- coding: utf-8 -*-
import numpy as np
import cv2
def video_to_numpy_array(video_path):
rgb_frame_list = []
video_read_capture = cv2.VideoCapture(video_path)
while video_read_capture.isOpened():
result, frame = video_read_capture.read()
if not result:
break
rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
rgb_frame_list.append(rgb_frame)
video_read_capture.release()
video_nparray = np.array(rgb_frame_list)
return video_nparray
def numpy_array_to_video(numpy_array,video_out_path):
video_height = numpy_array.shape[1]
video_width = numpy_array.shape[2]
out_video_size = (video_width,video_height)
output_video_fourcc = int(cv2.VideoWriter_fourcc(*'mp4v'))
video_write_capture = cv2.VideoWriter(video_out_path, output_video_fourcc, 30, out_video_size)
for frame in numpy_array:
video_write_capture.write(frame)
video_write_capture.release()
if __name__ == '__main__':
video_input_path = r'C:\Users\Administrator\Desktop\1.mp4'
video_output_path = r'C:\Users\Administrator\Desktop\1_out.mp4'
# 将视频读取为维度为N * W * H * C的numpy数组
video_np_array = video_to_numpy_array(video_input_path)
# 将numpy数组写为视频
numpy_array_to_video(video_np_array,video_output_path)
本文作者:StubbornHuang
版权声明:本文为站长原创文章,如果转载请注明原文链接!
原文标题:Python – 读取视频为numpy数组以及将numpy数组转换为视频
原文链接:https://www.stubbornhuang.com/2195/
发布于:2022年07月06日 9:04:35
修改于:2023年06月25日 21:00:19
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
评论
52