ffmpeg.py 2.1 KB
Newer Older
HypoX64's avatar
preview  
HypoX64 已提交
1 2
import os,json

H
hypox64 已提交
3 4
# ffmpeg 3.4.6

HypoX64's avatar
preview  
HypoX64 已提交
5
def video2image(videopath,imagepath):
H
hypox64 已提交
6
    os.system('ffmpeg -i "'+videopath+'" -f image2 '+imagepath)
HypoX64's avatar
preview  
HypoX64 已提交
7 8

def video2voice(videopath,voicepath):
H
hypox64 已提交
9
    os.system('ffmpeg -i "'+videopath+'" -f mp3 '+voicepath)
HypoX64's avatar
preview  
HypoX64 已提交
10 11

def image2video(fps,imagepath,voicepath,videopath):
H
hypox64 已提交
12 13
    os.system('ffmpeg -y -r '+str(fps)+' -i '+imagepath+' -vcodec libx264 '+'./tmp/video_tmp.mp4')
    #os.system('ffmpeg -f image2 -i '+imagepath+' -vcodec libx264 -r '+str(fps)+' ./tmp/video_tmp.mp4')
H
hypox64 已提交
14
    os.system('ffmpeg -i ./tmp/video_tmp.mp4 -i "'+voicepath+'" -vcodec copy -acodec copy '+videopath)
HypoX64's avatar
preview  
HypoX64 已提交
15 16

def get_video_infos(videopath):
H
hypox64 已提交
17
    cmd_str =  'ffprobe -v quiet -print_format json -show_format -show_streams -i "' + videopath + '"'  
HypoX64's avatar
preview  
HypoX64 已提交
18 19
    out_string = os.popen(cmd_str).read()
    infos = json.loads(out_string)
H
hypox64 已提交
20 21 22 23 24 25 26 27 28 29 30
    try:
        fps = eval(infos['streams'][0]['avg_frame_rate'])
        endtime = float(infos['format']['duration'])
        width = int(infos['streams'][0]['width'])
        height = int(infos['streams'][0]['height'])
    except Exception as e:
        fps = eval(infos['streams'][1]['r_frame_rate'])
        endtime = float(infos['format']['duration'])
        width = int(infos['streams'][1]['width'])
        height = int(infos['streams'][1]['height'])

HypoX64's avatar
preview  
HypoX64 已提交
31 32
    return fps,endtime,width,height

H
hypox64 已提交
33 34 35 36 37 38 39 40 41
def cut_video(in_path,start_time,last_time,out_path,vcodec='h265'):
    if vcodec == 'copy':
        os.system('ffmpeg -ss '+start_time+' -t '+last_time+' -i "'+in_path+'" -vcodec copy -acodec copy '+out_path)
    elif vcodec == 'h264':    
        os.system('ffmpeg -ss '+start_time+' -t '+last_time+' -i "'+in_path+'" -vcodec libx264 -b 12M '+out_path)
    elif vcodec == 'h265':
        os.system('ffmpeg -ss '+start_time+' -t '+last_time+' -i "'+in_path+'" -vcodec libx265 -b 12M '+out_path)

def continuous_screenshot(videopath,savedir,fps):
H
HypoX64 已提交
42 43 44 45 46 47
    '''
    videopath: input video path
    savedir:   images will save here
    fps:       save how many images per second
    '''
    videoname = os.path.splitext(os.path.basename(videopath))[0]
H
hypox64 已提交
48
    os.system('ffmpeg -i '+videopath+' -vf fps='+str(fps)+' '+savedir+'/'+videoname+'_%05d.jpg')