将视频按 FPS 拆解成单张图片 使用 cv2.VideoCapture cv2.VideoCapture (video_path) 计算 FPS 使用,注意部分压缩视频 FPS 存在丢帧情况,需要进行跳帧处理 fps = int (vidcap.get (cv2.CAP_PROP_FPS))
def video_split():
video_path = 'test/video/video_01.mp4'
video_name = video_path[:-4]
vidcap = cv2.VideoCapture(video_path)
success,image = vidcap.read()
fps = int(vidcap.get(cv2.CAP_PROP_FPS))
count = 0
while success:
image = image_process(image)
cv2.imwrite("%s/%d.jpg" % (video_name, count), image)
#if count % fps == 0:
# cv2.imwrite("%s/%d.jpg" % (video_name, int(count / fps)), image)
print (' 处理第 % d 秒: ' % int (count /fps), success)
success,image = vidcap.read()
count += 1
将单张图片集合合并成视频 使用 cv2.VideoWriter fourcc = cv2.VideoWriter_fourcc ('D', 'I', 'V', 'X') #不同视频编码对应不同视频格式(例:'I','4','2','0' 对应 avi 格式) video = cv2.VideoWriter ( file_path, fourcc, fps, size)
def video_combine():
path = 'test/video/video_01/'# 文件路径
filelist = os.listdir (path) #获取该目录下的所有文件名
filelist.sort(key=alphanum_key)
fps = 6
size = (580,420) #图片的分辨率片
file_path = 'test/video/video_01_out.mp4'# 导出路径
fourcc = cv2.VideoWriter_fourcc ('D', 'I', 'V', 'X') #不同视频编码对应不同视频格式(例:'I','4','2','0' 对应 avi 格式)
video = cv2.VideoWriter( file_path, fourcc, fps, size)
for item in filelist:
if item.endswith('.png'): #判断图片后缀是否是.png
item = path + '/' + item
image = cv2.imread(item) #使用opencv读取图像,直接返回numpy.ndarray 对象,通道顺序为BGR ,注意是BGR,通道值默认范围0-255。
video.write(image) #把图片写进视频
video.release() #释放
现在编码用到了 CV_FOURCC 获取编码格式: CV_FOURCC ('P', 'I', 'M', '1') = MPEG-1 编码 CV_FOURCC ('M', 'J', 'P', 'G') = motion-jpeg 编码 CV_FOURCC ('M', 'P', '4', '2') = MPEG-4.2 编码 CV_FOURCC ('D', 'I', 'V', '3') = MPEG-4.3 编码 CV_FOURCC ('D', 'I', 'V', 'X') = MPEG-4 编码 CV_FOURCC ('U', '2', '6', '3') = H263 编码 CV_FOURCC ('I', '2', '6', '3') = H263I 编码 CV_FOURCC ('F', 'L', 'V', '1') = FLV1 编码
参考: https://blog.csdn.net/errors\_in\_life/article/details/72809580 http://www.fjii.com/yw/2018/0919/182870.shtml