import os
import cv2
from moviepy.editor import *
import time
import os
from moviepy.editor import *
def formatchange(path_in, path_out):
"""
将mov、avi等视频格式转换为mp4格式
:param path_in: 输入路径
:param path_out: 输出路径
:return: 无返回值
"""
cmd = 'ffmpeg -i ' + path_in + ' -strict -2 -vcodec h264 ' + path_out
os.system(cmd)
def setfps(inputvideo, fps):
"""
设置视频帧数
:param inputvideo:
:param fps: 帧数,例如25
:return:
"""
path, _ = os.path.splitext(inputvideo)
a = '帧数设置{}.mp4'.format(fps)
name = path + a
cmd = 'ffmpeg -i ' + inputvideo + ' -r ' + str(fps) + ' ' + name
os.system(cmd)
def setbitrate(inputvideo, bitrate):
"""
改变视频码率,降低码率也可以实现对视频大小的最优化压缩
:param inputvideo:
:param bitrate: 例如600k
:return:
"""
path, _ = os.path.splitext(inputvideo)
a = '设置码率{}.mp4'.format(bitrate)
name = path + a
cmd = 'ffmpeg -i ' + inputvideo + ' -b:v ' + str(bitrate) + 'k ' + name
os.system(cmd)
def cutbegin(inputvideo, time):
"""
剪切视频片头
:param inputvideo: 输入视频目录
:param time: 片头时长
:return: 无返回值
"""
clip1 = VideoFileClip(inputvideo)
path, _ = os.path.splitext(inputvideo)
mp3 = path + '.mp3'
outmp3 = path + 'out.mp3'
end = clip1.duration
shenyin = clip1.audio
outname = path + '-剪切片头.mp4'
if shenyin != None:
shenyin.write_audiofile(mp3)
os.system(
"ffmpeg -i {in_path} -vn -acodec copy -ss {Start_time} -t {Dur_time} {out_path}".format(in_path=mp3,
out_path=outmp3,
Start_time=time,
Dur_time=end))
if time <= end:
clip1 = clip1.cutout(0, time)
clip1 = clip1.without_audio()
name = path + 'cut.mp4'
clip1.write_videofile(name, audio=False)
clip1.close()
cmd = 'ffmpeg -i ' + name + ' -i ' + outmp3 + ' -strict -2 -f mp4 ' + outname
os.system(cmd)
os.remove(mp3)
os.remove(outmp3)
os.remove(name)
else:
if time <= end:
clip1 = clip1.cutout(0, time)
clip1.write_videofile(outname, audio=False)
clip1.close()
def cutend(inputvideo, time):
"""
剪切视频片尾
:param inputvideo: 输入视频目录
:param time: 片尾时间节点
:return: 无返回值
"""
clip1 = VideoFileClip(inputvideo)
path, _ = os.path.splitext(inputvideo)
mp3 = path + '.mp3'
outmp3 = path + 'out.mp3'
end = clip1.duration
shenyin = clip1.audio
outname = path + '-剪切片尾.mp4'
if shenyin != None:
shenyin.write_audiofile(mp3)
os.system(
"ffmpeg -i {in_path} -vn -acodec copy -ss {Start_time} -t {Dur_time} {out_path}".format(in_path=mp3,
out_path=outmp3,
Start_time=0,
Dur_time=time))
if time <= end:
clip1 = clip1.cutout(time, end)
clip1 = clip1.without_audio()
name = path + 'cut.mp4'
clip1.write_videofile(name, audio=False)
clip1.close()
cmd = 'ffmpeg -i ' + name + ' -i ' + outmp3 + ' -strict -2 -f mp4 ' + outname
os.system(cmd)
os.remove(mp3)
os.remove(outmp3)
os.remove(name)
else:
if time <= end:
clip1 = clip1.cutout(0, time)
clip1.write_videofile(outname, audio=False)
clip1.close()
def star_subclip_end(inputvideo, startime, endtime):
"""
剪切自己感兴趣的部分视频片段
:param inputvideo: 输入视频目录
:param startime: 剪辑开始时间节点
:param endtime: 剪辑结束时间节点
:return: 无返回值
"""
clip1 = VideoFileClip(inputvideo)
path, _ = os.path.splitext(inputvideo)
mp3 = path + '.mp3'
outmp3 = path + 'out.mp3'
end = clip1.duration
shenyin = clip1.audio
outname = path + '-视频剪辑.mp4'
if shenyin != None:
shenyin.write_audiofile(mp3)
os.system(
"ffmpeg -i {in_path} -vn -acodec copy -ss {Start_time} -t {Dur_time} {out_path}".format(in_path=mp3,
out_path=outmp3,
Start_time=startime,
Dur_time=endtime))
if endtime <= end:
clip1 = clip1.subclip(startime, endtime)
clip1 = clip1.without_audio()
name = path + 'cut.mp4'
clip1.write_videofile(name, audio=False)
clip1.close()
cmd = 'ffmpeg -i ' + name + ' -i ' + outmp3 + ' -strict -2 -f mp4 ' + outname
os.system(cmd)
os.remove(mp3)
os.remove(outmp3)
os.remove(name)
else:
if endtime <= end:
clip1 = clip1.subclip(startime, endtime)
clip1.write_videofile(outname, audio=False)
clip1.close()
def rotation(inputvideo, rota):
"""
将视频旋转rota度
:param inputvideo:
:param rota:
:return:
"""
video1 = VideoFileClip(inputvideo)
video1 = video1.rotate(rota)
path, _ = os.path.splitext(inputvideo)
a = '视频旋转{}度.mp4'.format(rota)
name = path + a
video1.write_videofile(name)
def mirror(inputvideo, model):
"""
视频镜像
:param inputvideo:
:param model: model为1表示水平镜像,为2表示垂直镜像
:return:
"""
video1 = VideoFileClip(inputvideo)
path, _ = os.path.splitext(inputvideo)
if model == 1:
name = path + '水平镜像.mp4'
(video1.fx(vfx.mirror_x).write_videofile(name, codec='libx264'))
elif model == 2:
name = path + '垂直镜像.mp4'
(video1.fx(vfx.mirror_y).write_videofile(name, codec='libx264'))
def setsize(inputvideo, w_size, h_size):
"""
视频按尺寸进行缩放,等比例缩小相当于下调分辨率
:param inputvideo:
:param w_size: 视频宽度
:param h_size: 视频高度
:return:
"""
ship = VideoFileClip(inputvideo)
clip = ship.resize([w_size, h_size])
path, _ = os.path.splitext(inputvideo)
a = '视频缩放为{}x{}.mp4'.format(w_size, h_size)
name = path + a
clip.write_videofile(name)
def setresolution(inputvideo, w_size, h_size):
"""
调整视频分辨率
:param inputvideo:
:param w_size: 目标视频宽度
:param h_size: 目标视频高度
:return:
"""
path, _ = os.path.splitext(inputvideo)
a = '调整分辨率{}x{}.mp4'.format(w_size, h_size)
name = path + a
cmd = 'ffmpeg -i ' + inputvideo + ' -s ' + str(w_size) + 'x' + str(h_size) + ' ' + name
os.system(cmd)
def setbitrate(inputvideo, bitrate):
"""
改变视频码率,降低码率也可以实现对视频大小的最优化压缩
:param inputvideo:
:param bitrate: 例如600k
:return:
"""
path, _ = os.path.splitext(inputvideo)
a = '设置码率{}.mp4'.format(bitrate)
name = path + a
cmd = 'ffmpeg -i ' + inputvideo + ' -b:v ' + str(bitrate) + 'k ' + name
os.system(cmd)
def addmp3(inputvideo, mp3path):
"""
给视频增加音频
:param inputvideo: 输入视频目录
:param mp3path: 输入音频目录
:return:
"""
path, _ = os.path.splitext(inputvideo)
a = '增加音频{}.mp4'.format(mp3path)
outname = path + a
cmd = 'ffmpeg -i ' + inputvideo + ' -i ' + mp3path + ' -strict -2 -f mp4 ' + outname
os.system(cmd)
def speedplay(inputvideo, speed):
"""
倍速播放
:param inputvideo:
:param speed: 速度,例如1.5
:return:
"""
path, _ = os.path.splitext(inputvideo)
a = '改变速度{}.mp4'.format(speed)
outname = path + a
video = VideoFileClip(inputvideo)
result = video.fl_time(lambda t: speed * t,
apply_to=['mask', 'video', 'audio']).set_end(video.end / speed)
result.write_videofile(outname)
def addstarvideo(inputvideo, starvideo):
"""
添加片头
:param inputvideo:
:param starvideo:
:return:
"""
path, _ = os.path.splitext(inputvideo)
a = '增加片头{}.mp4'.format(starvideo)
outname = path + a
video1 = VideoFileClip(starvideo)
video2 = VideoFileClip(inputvideo)
video3 = concatenate_videoclips([video1, video2])
video3.write_videofile(outname)
def addendvideo(inputvideo, endvideo):
"""
添加片尾
:param inputvideo:
:param endvideo:
:return:
"""
path, _ = os.path.splitext(inputvideo)
a = '增加片尾{}.mp4'.format(endvideo)
outname = path + a
video1 = VideoFileClip(inputvideo)
video2 = VideoFileClip(endvideo)
video3 = concatenate_videoclips([video1, video2])
video3.write_videofile(outname)
def comvideo(inputvideo, endvideo):
"""
视频合成
:param inputvideo:合成的第一段视频
:param endvideo:合成的第二段视频
:return:
"""
path, _ = os.path.splitext(inputvideo)
a = '视频空间合成{}.mp4'.format(endvideo)
outname = path + a
video1 = VideoFileClip(inputvideo)
video2 = VideoFileClip(endvideo)
video3 = CompositeVideoClip([video1, video2])
video3.write_videofile(outname)
def clipVideo(video):
clip = VideoFileClip(video)
clip = clip.subclip(90, clip.duration)
cur_dir = os.path.dirname(os.path.abspath(video))
cur_name=os.path.basename(video)
file_name = video.split('.')[0]
new_file =file_name+ str(int(time.time())) + '_subclip.mp4'
clip.write_videofile(new_file)
def filter_file(filter,dirname):
result = []
for maindir, subdir, file_name_list in os.walk(dirname):
for filename in file_name_list:
apath = os.path.join(maindir, filename)
ext = os.path.splitext(apath)[1]
if ext in filter:
result.append(apath)
return result
def save_img2(videos):
for video_name in videos:
cur_dir = os.path.dirname(os.path.abspath(video_name))
cur_name=os.path.basename(video_name)
print("curDir:{0} curname:{1}".format(cur_dir,cur_name))
file_name = video_name.split('.')[0]
folder_name=cur_dir
vc = cv2.VideoCapture(video_name)
fps = vc.get(cv2.CAP_PROP_FPS)
print(fps)
rval = vc.isOpened()
n=1
fps=0.2
totalframs=vc.get(cv2.CAP_PROP_FRAME_COUNT)
while rval and fps<1.0:
vc.set(cv2.CAP_PROP_POS_FRAMES ,fps*totalframs)
rval, frame = vc.read()
pic_path = folder_name + '/'
print("rival",rval)
if rval:
savepath=pic_path + cur_name[-15:-5]+"_" + str(round(n)) + '.jpg'
cv2.imencode('.jpg',frame)[1].tofile(savepath)
print(savepath)
fps+=0.15
n+=1
cv2.waitKey(1)
else:
break
vc.release()
print('save_success' + folder_name)
def main():
video_path = r'H:/newFolder/GUOCHAN/shtGuochanJP/dist/videoproject/upload/pics/'
filelist=filter_file(r'.mp4',video_path)
print("files:{0}".format(filelist))
print("dealing:....")
save_img2(filelist)
if __name__ == '__main__':
main()
import cv2
import os
import hashlib
file_dict = {"2017-07-04-07-39-28_fovs5.h264": (list(range(2030,3150)) + list(range(3960,4050))),
"2017-07-04-09-41-55_fovs5.h264": (list(range(1100,1700)) + list(range(2430,4450))),
"2017-07-04-09-50-22_fovs5.h264": (list(range(0,1240)) + list(range(2200,9000)) + list(range(11320,14000)))}
def getFileMD5(filepath):
f = open(filepath, 'rb')
md5obj = hashlib.md5()
md5obj.update(f.read())
hash = md5obj.hexdigest()
f.close()
return str(hash).upper()
def selct_sample(video_path,target_path,video_index,filemd5,frameFrequency,extract_num):
cap = cv2.VideoCapture(video_path)
frame_index = 0
while True:
res, image = cap.read()
if not res:
print('not res, not image')
break
if frame_index % frameFrequency == 0 and frame_index in extract_num:
image_name = ("{}_{}_{}.png".format(
(str(video_index)).zfill(4),
filemd5,
(str(frame_index)).zfill(5))
)
cv2.imwrite(os.path.join(target_path,image_name),image)
print("正在截取:{} ---> {}帧".format(os.path.basename(target_path),frame_index))
frame_index += 1
print("图片提取结束")
cap.release()
def gen_sample(video_path,target_path,video_index,filemd5,frameFrequency):
cap = cv2.VideoCapture(video_path)
frame_index = 0
while True:
res, image = cap.read()
if not res:
print('not res, not image')
break
if frame_index % frameFrequency == 0:
image_name = ("{}_{}_{}.png".format(
(str(video_index)).zfill(4),
filemd5,
(str(frame_index)).zfill(5))
)
cv2.imwrite(os.path.join(target_path,image_name),image)
print("正在截取:{} ---> {}帧".format(os.path.basename(target_path),frame_index))
frame_index += 1
print("图片提取结束")
cap.release()
def main():
src_path = r'C:/Users/19088/Desktop/pypics/'
target_path = r'D:/pypics/'
frameFrequency = 100000
filelist = os.listdir(src_path)
video_num = len(filelist)
print("视频个数为:%d" % video_num)
for item in filelist:
video_index = 0
if item.endswith(('.h264','.mp4','.mkv','avi')):
video_path = os.path.join(src_path,item)
filemd5 = getFileMD5(video_path)
filename = item.split(".")[0]
outPutDir = os.path.join(target_path,filename)
if not os.path.exists(outPutDir):
os.mkdir(outPutDir)
gen_sample(video_path,outPutDir,video_index,filemd5,frameFrequency)
video_index += 1
if __name__ == '__main__':
main()