python图片和视频相互转换
2019-12-03 本文已影响0人
顾北向南
1. 图片转换视频
import cv2
import torch
import numpy as np
import os
path='D:/Imgs'
filelist = os.listdir(path)
fps = 4 #视频每秒24帧
size = (2048, 1024) #需要转为视频的图片的尺寸
fourcc = cv2.VideoWriter_fourcc(*"MJPG")
video = cv2.VideoWriter('D:/Vidoes/val_gt.avi',fourcc, fps, size)
#视频保存在当前目录下
for item in filelist:
if item.endswith('_gtFine_color.png'):
item = path + item
# 路径为中文名
img= cv2.imdecode(np.fromfile(item, dtype=np.uint8), 1)
# 路径为英文名
img = cv2.imread(item)
video.write(img)
video.release()
cv2.destroyAllWindows()
2. 视频转换图片
""" 将视频转换成图片 path: 视频路径 """
import cv2
path='D:/Videos/val_gt.avi'
cap = cv2.VideoCapture(path)
suc = cap.isOpened() # 是否成功打开
frame_count = 0
while suc:
frame_count += 1
suc, frame = cap.read()
params = []
params.append(2) # params.append(1)
cv2.imwrite('frames\\%d.jpg' % frame_count, frame, params)
cap.release()
print('unlock movie: ', frame_count)