直接上代码。
1. 视频转为图像
import cv2
import os
def video2img(video_path, frame_save_dir,frame_interval = 1000):
"""
:param video_path: 视频路径
:param frame_save_dir: 视频帧的存储路径
:param frame_interval: 视频帧的采样间隔
:return:
"""
cap = cv2.VideoCapture(video_path,)
suc = cap.isOpened()
frame_count = 0
while suc:
suc, frame = cap.read() # suc是bool变量,用于判断视频帧是否存在
frame_count += 1
if (suc and frame_count%frame_interval==0):
save_path = os.path.join(frame_save_dir, "{:04d}.jpg".format(frame_count)) # 格式化命名,不足补零
cv2.imwrite(save_path, frame)
print(frame_count, suc)
cap.release()
if __name__ =="__main__":
video_path = "./01_001.avi"
frame_save_dir = "./images" # 需要预先创立该文件夹
video2img(video_path,frame_save_dir)
2. 图像转视频
import cv2
import os
import glob
imgs_dir = './images'
video_path = './video.avi'
img_list = glob.glob(os.path.join(imgs_dir,"*.jpg"))
print(len(img_list))
fps = 100
H,W = 256,500
fourcc = cv2.VideoWriter_fourcc(*"MJPG")
videoWriter = cv2.VideoWriter(video_path,fourcc,fps,(W,H))
for index,name in enumerate(img_list):
print(index)
frame = cv2.resize(cv2.imread(name),(W,H))
videoWriter.write(frame)
videoWriter.release()
print("finish")