批量将视频转为图像序列
代码如下,代码中带有解释:
# 导入所需要的库
import cv2
import os
import numpy as np# 多个视频所在的路径
datasets_path = ["/home/y/Code/数据集/1/007f.mp4","/home/y/Code/数据集/1/05f.mp4","/home/y/Code/数据集/1/024f.mp4", ]
# 保存图片的根目录
root_image_path = r"/home/y/Code/test/dataset/"# 定义保存图片函数:image:要保存的图片名字; target_image_path:图片序列地址; num: int 类型, 相片,名字的后缀。
def save_image(image,target_image_path, num):address = target_image_path + str(num) + '.jpg'cv2.imwrite(address, image)
# 将一个视频转为图像序列的函数
def get_video_to_img(source_video_path, target_image_path):# 读取视频文件 视频文件路径videoCapture = cv2.VideoCapture(source_video_path) # 读帧success, frame = videoCapture.read()i = 0timeF = 30j = 0while success:i = i + 1if (i % timeF == 0):j = j + 1save_image(frame, target_image_path, j) #视频截成图片存放的位置print('save image:', i)success, frame = videoCapture.read()# 主函数:用于读取多个视频的路径,并将每个视频对应的路径 和 保存图片序列的路径 传递给get_video_to_img()函数,实现视频转化。
def run_video_to_image():for source_video_path in datasets_path:#创建 保存图片序列所需的目录target_image_path = root_image_path + "/" + source_video_path.split("/")[-1].split(".")[-2]+"/"if not os.path.exists(target_image_path):os.makedirs(target_image_path)#调用视频转图片序列的函数get_video_to_img(source_video_path, target_image_path)run_video_to_image()