关键点:
视频–>图片
cap = cv2.VideoCapture(video_path)
success, frame = cap.read()
图片–>视频
video = cv2.VideoWriter(videoPath, fourcc, fps, size)
video.write(img)
完整代码
import cv2
import os
import shutil
def video2imgs(videoPath, imgPath, interval=1):
if not os.path.exists(imgPath):
os.makedirs(imgPath)
else:
shutil.rmtree(imgPath)
os.makedirs(imgPath)
print('path of %s already exist and rebuild!' % imgPath)
cap = cv2.VideoCapture(videoPath)
judge = cap.isOpened() #judge whether video can be opened
print(judge)
i = 0
while True:
success, frame = cap.read()
if success:
i += 1
if i % interval == 0:
#create the save path of img
img_name = str(i) + '.jpg'
img_path = os.path.join(imgPath, img_name)
cv2.imwrite(img_path, frame)
print('image of %s is saved!' % img_name)
else:
print('video is all read!')
break
cap.release()
def imgs2video(imgPath, videoPath):
if not videoPath.endswith('.mp4'):
print('Warning: the videoPath is not valid, please correct it which ends with \'.mp4\'')
return 0
#get the all properties of cap
#cap = cv2.VideoCapture(videoPath)
# height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
# width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
# fps = cap.get(cv2.CAP_PROP_FPS)
# total_frames = cap.get(cv2.CAP_PROP_FRAME_COUNT)
#get imgs url
filelist = os.listdir(imgPath)
img_url = [os.path.join(imgPath, file) for file in filelist]
#set the properties of video
ImgSizeInfo = cv2.imread(img_url[0]).shape #height, width
size = (ImgSizeInfo[1], ImgSizeInfo[0]) #width, height
fps = 15
fourcc = cv2.VideoWriter_fourcc(*'XVID') #.mp4
video = cv2.VideoWriter(videoPath, fourcc, fps, size)
# VideoWriter 中指定的尺寸要和 write() 中写进去的一样,不然视频会存储失败
for url in img_url:
if url.endswith('.jpg') or url.endswith('.JPG'):
img = cv2.imread(url)
video.write(img)
print('the video has been maked successfully!')
video.release()
if __name__ == '__main__':
video_path = './read.mp4'
imgs_path = './imgs'
video_name = './write.mp4'
video2imgs(video_path, imgs_path, 15)
input('Now starting to use imgs transfer to video......')
imgs2video(imgs_path, video_name)