将视频保存为图像
import cv2
import glob
import os
from datetime import datetime
def video_to_frames(path):
videoCapture = cv2.VideoCapture()
videoCapture.open(path)
fps = videoCapture.get(cv2.CAP_PROP_FPS)
frames = videoCapture.get(cv2.CAP_PROP_FRAME_COUNT)
print("fps=", int(fps), "frames=", int(frames))
for i in range(int(frames)):
ret, frame = videoCapture.read()
cv2.imwrite(output_dir+"/"+str(i)+".jpg", frame)
return
if __name__ == '__main__':
output_dir = "frames"
if not os.path.exists(output_dir):
os.mkdir(output_dir)
t1 = datetime.now()
video_to_frames("20131207005_20131207094649.avi")
t2 = datetime.now()
print("Time cost = ", (t2 - t1))
print("SUCCEED !!!")
将图像转存为视频
import cv2
import glob
import os
from datetime import datetime
def frames_to_video(fps, save_path, frames_path,max_index, size):
fourcc = cv2.VideoWriter_fourcc(*'XVID')
videoWriter = cv2.VideoWriter(save_path, fourcc, fps, size)
imgs = glob.glob(frames_path + "/*.jpg")
frames_num = len(imgs)
for i in range(max_index):
if os.path.isfile("%s/%d.jpg" % (frames_path, i)):
frame = cv2.imread("%s/%d.jpg" % (frames_path, i))
frame = frame[200:200+size[0],200:200+size[1],:]
videoWriter.write(frame)
videoWriter.release()
return
if __name__ == '__main__':
t1 = datetime.now()
size = (512,512)
frames_to_video(fps=20, save_path="result.avi", frames_path='frames', max_index=100, size=size)
t2 = datetime.now()
print("Time cost = ", (t2 - t1))
print("SUCCEED !!!")
"""
# 如果写MP4格式的化:
fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
fourcc = cv2.VideoWriter_fourcc('M', 'P', '4', 'V')
fourcc = cv2.VideoWriter_fourcc(*'MP4V')
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
"""
|