在工作中经常会用到抽取视频帧或把一堆图片转化为视频,这些工作有些工具也可以做的,但对于做视觉算法的热来说很多时候要在程序中搞这些事情,因此这些工具就不太好使了,对此我用python-opencv写了视频和图片相互转化的程序,代码如下:

#!/usr/bin/python
# -*- coding: utf-8 -*-
# 2019/08/20 by DQ
import os
import cv2
import shutil


def Video2ImSet(VideoPath, ImGap, ImExtName,ImDir,SaveImPrefix=''):
	FrameId = 0
	VideoObj = cv2.VideoCapture(VideoPath)
	while True:
		FrameId += 1
		res, Im = VideoObj.read()
		if not res:
			print('not res , not Im')
			break
		if FrameId % ImGap == 0:
			ImName = SaveImPrefix+str(FrameId).zfill(5) + ImExtName
			ImPath = os.path.join(ImDir, ImName)
			cv2.imwrite(ImPath, Im)
	VideoObj.release()


def ImSet2Video(ImDir, ImExtName, FPS, VideoPath):
	ImNameSet = os.listdir(ImDir)
	ImNameSet.sort()
	fps = FPS
	ImPath = os.path.join(ImDir, ImNameSet[0])
	Im = cv2.imread(ImPath)
	tSize = Im.shape[:-1]
	size = (tSize[1], tSize[0])
	
	VideoObj = cv2.VideoWriter(VideoPath, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), fps, size)
	for ImName in ImNameSet:
		if ImName.endswith(ImExtName):
			ImPath = os.path.join(ImDir, ImName)
			Im = cv2.imread(ImPath)
			VideoObj.write(Im)
	VideoObj.release()




if __name__ == '__main__':
	VideoDir='.\\Data\\VideoSet'
	ImMainDir='.\\Data\\ImSet'
	ImExtName = '.jpg'
	ImGap =10
	VideoName='VDS_0779.mp4'
	VideoPath =os.path.join(VideoDir,VideoName)
	PureVideoName=VideoName.split('.')
	ImDir = os.path.join(ImMainDir,PureVideoName)
	if os.path.isdir(ImDir):
		shutil.rmtree(ImDir)
	else:
		os.makedirs(ImDir,0o777,True)
	SaveImPrefix=PureVideoName+'-'
	Video2ImSet(VideoPath, ImGap, ImExtName, ImDir, SaveImPrefix)
	
	"""
	ImDir = '.\\ImSet\\x'
	FPS = 30
	VideoPath = '.\\VideoSet\\x.avi'
	ImSet2Video(ImDir, ImExtName, FPS, VideoPath)
	"""

程序比较简短明了,不做注解。

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐