Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #v2
- max_interval=180 # frames
- min_interval=max_interval-30
- import subprocess
- import os
- import sys
- if sys.argv[0]!="" and len(sys.argv)!=3:
- input("Drag and drop image and video")
- exit()
- print(f"image: {sys.argv[1]}\nvideo: {sys.argv[2]}")
- face=sys.argv[1]
- video=sys.argv[2]
- dir=os.path.dirname(video)
- outdir=f"{dir}\\..\\output\\"
- # retrieve frame data
- result = subprocess.run(['ffprobe', '-loglevel', 'error', '-select_streams', 'v:0', '-show_entries', 'frame=key_frame,coded_picture_number,pkt_pts_time', '-of', 'csv=print_section=0', video], stdout=subprocess.PIPE)
- fr=result.stdout.decode("utf-8").split("\r\n")
- fr=[x.split(",") for x in fr if x]
- if len(set([x[2] for x in fr]))==1:
- fr={i:[x[0],x[1]] for i,x in enumerate(fr)}
- else:
- fr={int(x[2]):[x[0],x[1]] for x in fr}
- # just do the editing if video is short
- if len(fr)<max_interval:
- subprocess.run(['video.bat', face, video])
- exit()
- # keyframes
- kf=[x for x in fr if fr[x][0]=="1"]
- dif=[]
- y=None
- for x in kf:
- if y!=None:
- dif.append(x-y)
- y=x
- video_s=os.path.splitext(video)
- if max(dif)>max_interval or min(dif)<min_interval:
- # cut video into [interval]-sized slices
- frames_left=len(fr)
- f0=0
- f1=0
- i=0
- while True:
- f1=f0+max_interval if f0+max_interval<len(fr) else len(fr)-1
- t=float(fr[f1][1])-float(fr[f0][1])
- subprocess.run(['ffmpeg', '-i', video, '-loglevel', 'warning', '-stats', '-ss', fr[f0][1], '-t', str(t), video_s[0]+"_"+str(i)+video_s[1]], stdout=subprocess.PIPE)
- i+=1
- f0=f1
- if f0+1>=len(fr):
- break
- else:
- # cut video by keyframes if intervals are short enough (usually faster)
- subprocess.run(['ffmpeg', '-i', video, '-loglevel', 'warning', '-stats', '-acodec', 'copy', '-f', 'segment', '-vcodec', 'copy', '-reset_timestamps', '1', '-map', '0', video_s[0]+"_%d."+video_s[1]], stdout=subprocess.PIPE)
- i=len(kf)
- # edit sliced fragments
- videos=[f"{video_s[0]}_{str(x)}{video_s[1]}" for x in range(0,i)]
- edited_videos=[]
- for x in videos:
- edited_videos.append(f"{outdir}{os.path.splitext(os.path.basename(face))[0]}_{os.path.basename(x)}")
- subprocess.run(['video.bat', face, x])
- # merge edited fragments
- list_video=os.path.join(dir, f"list_{os.path.basename(video)}.txt")
- with open(list_video,"w") as f:
- for x in edited_videos:
- f.write(f"file '{x}'\n")
- subprocess.run(['ffmpeg', '-f', 'concat', '-loglevel', 'warning', '-stats', '-safe', '0','-i', list_video, '-c', 'copy', f"{outdir}{os.path.splitext(os.path.basename(face))[0]}_{os.path.basename(video)}"], stdout=subprocess.PIPE)
- # remove temp files
- os.remove(list_video)
- for x,y in zip(videos,edited_videos):
- os.remove(x)
- os.remove(y)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement