视频帧提取、序列图片合成视频、多幅图像拼接
视频帧提取 及 序列图片合成视频
1 import cv2 2 import os 3 4 # cap = cv2.VideoCapture("./video/calib.mp4") 5 input_dir = "E:/underwater_video_frames/under_water.avi" 6 7 output_img_dir = r"E:/underwater_video_frames/frames" 8 output_video_dir = r"E:/underwater_video_frames/" 9 10 if not os.path.exists(output_img_dir): 11 os.makedirs(output_img_dir, exist_ok=True) 12 if not os.path.exists(output_video_dir): 13 os.makedirs(output_video_dir, exist_ok=True) 14 15 def video_2_img(img_dir, video_dir): 16 cap = cv2.VideoCapture(video_dir) 17 i = 0 18 while True: 19 i += 1 20 ret, frame = cap.read() 21 if ret is False: 22 break 23 24 if i % 1 == 0: 25 print("i:", i) 26 # resized_frame = cv2.resize(frame, (1920, 1080), interpolation=cv2.INTER_AREA) 27 cv2.imwrite(img_dir + str('/%05d' % i) + ".jpg", frame) 28 29 cap.release() 30 31 def img_2_video(video_dir, im_dir): 32 print("----正在合成视频-----") 33 video_ = video_dir + 'under_water_color.mp4' 34 fourcc = cv2.VideoWriter_fourcc('M', 'P', '4', 'V') 35 videoWriter = cv2.VideoWriter(video_, fourcc, 30, (640,360)) 36 for i in range(340, 701): 37 image_number = i 38 print(im_dir + (str(image_number)) + '.jpg') 39 img12 = cv2.imread(im_dir + (str(image_number).zfill(5)) + '.jpg') 40 #cv2.imshow('img', img12) 41 #cv2.waitKey(1) 42 videoWriter.write(img12) 43 videoWriter.release() 44 45 # video_2_img(output_img_dir, input_dir) 46 _img_dir = 'E:/underwater_video_frames/frames/' 47 img_2_video(output_video_dir, _img_dir)
多幅图像拼接
1 import cv2 2 import numpy as np 3 4 INPUT_FILE1 = 'E:/underwater_video_frames/under_water_color.mp4' 5 INPUT_FILE2 = 'E:/underwater_video_frames/under_water_color_correct.mp4' 6 OUTPUT_FILE = 'E:/underwater_video_frames/result.mp4' 7 8 reader1 = cv2.VideoCapture(INPUT_FILE1) 9 reader2 = cv2.VideoCapture(INPUT_FILE2) 10 width = int(reader1.get(cv2.CAP_PROP_FRAME_WIDTH)) 11 height = int(reader1.get(cv2.CAP_PROP_FRAME_HEIGHT)) 12 print(width, height) 13 14 videoWriter = cv2.VideoWriter(OUTPUT_FILE, cv2.VideoWriter_fourcc('m', 'p', '4', 'v'), 30, (width*2, height)) 15 16 print(reader1.isOpened()) 17 print(reader2.isOpened()) 18 have_more_frame, frame1 = reader1.read() 19 _, frame2 = reader2.read() 20 c = 0 21 while have_more_frame: 22 23 frame1 = cv2.resize(frame1, (width, height)) 24 frame2 = cv2.resize(frame2, (width, height)) 25 img = np.hstack((frame1, frame2)) 26 print(img.shape) 27 # cv2.waitKey(1) 28 videoWriter.write(img) 29 c += 1 30 print(str(c) + ' is ok') 31 have_more_frame, frame1 = reader1.read() 32 _, frame2 = reader2.read() 33 print('finish!') 34 35 videoWriter.release() 36 reader1.release() 37 reader2.release()
opencv中cv2.VideoWriter_fourcc 输出视频的格式要求