转自
Steps:
- Fetch all the image file names using glob
- Read all the images using cv2.imread()
- Store all the images into a list
- Create a VideoWriter object using cv2.VideoWriter()
- Save the images to video file using cv2.VideoWriter().write()
- Release the VideoWriter and destroy all windows.
import cv2
import numpy as np
import glob
img_array = []
# glob.glob(正则表达式), 返回一个列表
for filename in glob.glob('C:/New folder/Images/*.jpg'):
img = cv2.imread(filename)
height, width, layers = img.shape
size = (width,height)
img_array.append(img)
out = cv2.VideoWriter('project.avi',cv2.VideoWriter_fourcc(*'DIVX'), 15, size)
for i in range(len(img_array)):
out.write(img_array[i])
out.release()
or
不使用列表,每次读取完后释放内存
import cv2
import numpy as np
import glob
img_array = []
size = (1226, 370)
out = cv2.VideoWriter('project1.avi', cv2.VideoWriter_fourcc(*'DIVX'), 10, size)
for filename in glob.glob(r'E:\8_DataSet\KITTI\KITTITrackingdata_tracking_image_2\testing\image_02\0028/*.png'):
img = cv2.imread(filename)
height, width, layers = img.shape
size = (width, height)
img_array.append(img)
out.write(img)
jpg转MP4
import cv2
import numpy as np
import glob
img_array = []
# glob.glob(正则表达式), 返回一个列表
for filename in glob.glob(r'C:\Users\lpf\Desktop\MOT16\test\MOT16-01\img1/*.jpg'):
img = cv2.imread(filename)
height, width, layers = img.shape
size = (width, height)
img_array.append(img)
out = cv2.VideoWriter('project.mp4', cv2.VideoWriter_fourcc(*'mp4v'), 30, size)
for i in range(len(img_array)):
out.write(img_array[i])
out.release()