处理视频的时候,每次都要写重复的代码,故写篇小短文,做个备份;
1、视频转图片
##video_path 为输入的视频路径;
##imgs_path 为输出的图像序列路径;
def video2img(video_path,imgs_path):
num = 0
vid = cv2.VideoCapture(video_path)
fps = vid.get(cv2.CAP_PROP_FPS)
print('fps is ',fps)
while vid.isOpened():
is_read, frame = vid.read()
print('num is ',num,num%fps)
if is_read:
cv2.imwrite(imgs_path + '/'+str('%08d' % num) + '.jpg', frame)
num += 1
else:
break
2、图片转视频
#src_path 为图像序列的路径;
#dst_path 为输出视频的路径;
#默认输出的格式为mp4,输出文件为output.mp4;
def img2video(src_path,dst_path,name = 'output.mp4'):
# if not os.path.exists(dst_path):
# os.makedirs(dst_path, exist_ok=True)
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
#图片的尺寸,(width,height)
img_size = (640, 480)
fps = 10
video_writer = cv2.VideoWriter(filename=os.path.join(dst_path, name), fourcc=fourcc, fps=fps,
frameSize=img_size)
for jpg in os.listdir(src_path):
if jpg.endswith('.jpg'):
frame = cv2.imread(os.path.join(src_path,jpg))
video_writer.write(frame)
else:
print(jpg)
video_writer.release()
print('process ok!')
return
有问题欢迎交流!