使用Python如何將視頻按照一定時(shí)間切割(比如:每10s進(jìn)行裁切)
使用Python將視頻按照一定時(shí)間切割(比如:每10s進(jìn)行裁切)
平臺(tái): Ubuntu 16.04
函數(shù)庫: ffmpeg、subprocess
需求: 將path路徑下的所有.mp4視頻每delta_X(10s)進(jìn)行裁切,并保存在save_path下,并裁切好的視頻以id00001.mp4、id00002.mp4、id00003.mp4…命名保存
注意:
1.每個(gè)視頻不超過1小時(shí)、最后不足delta_X時(shí)間的會(huì)被舍棄。(根據(jù)需求自行修改)
參考代碼見文末補(bǔ)充介紹。
2.關(guān)于path和save_path路徑的問題(今天有小可愛問我這個(gè)問題):最好是獨(dú)立分開,別有包含關(guān)系。比如:不要出現(xiàn) path=‘/home/video’ save_path=‘/home/video/save’ 這種情況,因?yàn)槲业膙ideo_list的獲取方式是os.listdir(path) ,已經(jīng)默認(rèn)了path下的文件都是視頻格式的,這一點(diǎn)確實(shí)魯棒性不是很好,,我考慮欠佳,希望可以幫助到你:)
import subprocess import os path = '/home/dataset' # 待切割視頻存儲(chǔ)目錄 video_list = os.listdir(path) delta_X = 10 # 每10s切割 save_path = '/home/save' mark = 0 # 獲取視頻的時(shí)長(zhǎng) def get_length(filename): result = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", filename], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) return float(result.stdout) for file_name in video_list: min = int(get_length(os.path.join(path, file_name))) // 60 # file_name視頻的分鐘數(shù) second = int(get_length(os.path.join(path, file_name))) % 60 # file_name視頻的秒數(shù) for i in range(min+1): if second >= delta_X: # 至少保證一次切割 start_time = 0 end_time = start_time+delta_X for j in range((second//10)+1): min_temp = str(i) start = str(start_time) end = str(end_time) # crop video # 保證兩位數(shù) if len(str(min_temp)) == 1: min_temp = '0'+str(min_temp) if len(str(start_time)) == 1: start = '0'+str(start_time) if len(str(end_time)) == 1: end = '0'+str(end_time) # 設(shè)置保存視頻的名字 if len(str(mark)) < 6: name = '0'*(6-len(str(mark))-1)+str(mark) else: name = str(mark) command = 'ffmpeg -i {} -ss 00:{}:{} -to 00:{}:{} -strict -2 {}'.format(os.path.join(path,file_name), min_temp,start,min_temp,end, os.path.join(save_path,'id'+str(name))+'.mp4') mark += 1 os.system(command) if i != min or (i == min and (end_time+delta_X) < second): start_time += delta_X end_time += delta_X elif (end_time+delta_X) <= second: start_time += delta_X end_time += delta_X elif (end_time+delta_X) > second: # 最后不足delta_X的部分會(huì)被舍棄 break
補(bǔ)充介紹:python處理視頻的幾個(gè)操作
兩組圖片序列幀合成一個(gè)視頻(左右排列),只合成一個(gè)的自行修改
參數(shù)介紹:
- 兩組圖片序列幀存放在source中,命名格式為
real_1.png、real_2.png、..........
fake_1.png、fake_2.png、...........
- 將合成好的視頻name(final.avi),保存在file('./results')中。
- size為name(final.avi)的大小,注意格式為(width,height)
- size一定要和圖片的大小對(duì)應(yīng)好,否則final.avi無法播放
import os import cv2 import numpy as np def picvideo(path,size,file,name): filelist = os.listdir(path) # 獲取path中的所有序列幀 fps = 35 file_path = os.path.join(file,name) fourcc = cv2.VideoWriter_fourcc('I','4','2','0') # fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v') # mp4 video = cv2.VideoWriter(file_path,fourcc,fps,size) real = [] fake = [] for item in filelist: # if 后的判斷根據(jù)自己的實(shí)際情況去編寫,如果用到以aaa結(jié)尾的,自行改成item.endswith('aaa') if item.startswith('real'): item=path+'/'+item real.append(item) if item.startswith('fake'): item=path+'/'+item fake.append(item) real.sort() fake.sort() for path1,path2 in zip(real,fake): img1=cv2.imread(path1) img2=cv2.imread(path2) assert img1.shape==img2.shape, "shape error" # 豎排用 image=np.vstack([img1,img2]) image=np.hstack([img1,img2]) # 橫排 video.write(image) video.release() number=2 path = 'source' # 豎排用 size=(1024,512*number) size = (1024*number,512) file = './results' name = 'final.avi' picvideo(path, size, file, name)
計(jì)算一個(gè)視頻的FPS
import cv2 if __name__ == '__main__' : video = cv2.VideoCapture("video.mp4"); # Find OpenCV version (major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.') if int(major_ver) < 3 : fps = video.get(cv2.cv.CV_CAP_PROP_FPS) print "Frames per second using video.get(cv2.cv.CV_CAP_PROP_FPS): {0}".format(fps) else : fps = video.get(cv2.CAP_PROP_FPS) print "Frames per second using video.get(cv2.CAP_PROP_FPS) : {0}".format(fps) video.release();
將一個(gè)視頻中的音頻提取出來
from moviepy.editor import * video = VideoFileClip('test.mp4') audio = video.audio audio.write_audiofile('test.wav')
將A.mp4的音頻加到B.mp4
from moviepy.editor import VideoFileClip origin_video = "A.mp4" add_video = "B.mp4" res_video = "res.mp4" voice_video = VideoFileClip(origin_video) audio = voice_video.audio video = VideoFileClip(add_video) new = video.set_audio(audio) new.write_videofile(res_video)
將格式不同(mp4,avi)兩個(gè)視頻合成為一個(gè)avi(256,256*4),一個(gè)大小為(256,256*3),另一個(gè)大小為(256,256)
import cv2 import numpy as np import imageio # 將statue.avi 和 voice3.mp4 (兩個(gè)格式不同的視頻) 合并成 final3.avi path = './results/final3.avi' video1 = imageio.get_reader('./results/statue.avi') video2 = imageio.get_reader('./results/voice3.mp4') video1_L = [] for im in video1: video1_L.append(im) video1.close video2_L = [] for im in video2: video2_L.append(im) video2.close fourcc = cv2.VideoWriter_fourcc(*'MJPG') out1 = cv2.VideoWriter(path,fourcc,20,(256*4,256),True) for frame1,frame2 in zip(video1_L ,video2_L): frame1 = cv2.cvtColor(frame1.astype('float32'), cv2.COLOR_BGR2RGB) frame2 = cv2.cvtColor(frame2.astype('float32'), cv2.COLOR_BGR2RGB) # 對(duì)于不同格式的視頻 下面這個(gè)步驟至關(guān)重要 frame1 = frame1.astype(np.uint8) frame2 = frame2.astype(np.uint8) image = np.concatenate((frame1,frame2),axis=1) out1.write(image)
將一個(gè)文件夾中的圖片resize成(256,256),并把jpg轉(zhuǎn)成png
import PIL.Image import os path = './data' path_list = os.listdir(path) for file in path_list: im = PIL.Image.open(os.path.join(path,file)) im = im.resize((256,256)) im.save(os.path.join(path,file[:-3]+'png')) os.remove(os.path.join(path,file))
將視頻test.mp4進(jìn)行裁切(比如:00:00:01-00:05:00)保存為crop.mp4(需要安裝ffmpeg)
ffmpeg -i test.mp4 -ss 00:00:01 -to 00:05:00 -c:v copy -c:a copy crop.mp4
如果使用上面的命令出現(xiàn)黑視頻的情況則使用下面的命令
ffmpeg -i test.mp4 -ss 00:00:01 -to 00:05:00 -strict -2 crop.mp4
將視頻test.mp4每5s保存一次圖片(fps=1時(shí)一秒1張圖保存、fps=1/5=0.2時(shí)5秒一張圖保存)
ffmpeg -i test.mp4 -vf fps=0.2 out%d.png
將視頻進(jìn)行旋轉(zhuǎn)(需要安裝moviepy)
from moviepy.editor import * clip = VideoFileClip("result.mp4") # clip = clip.rotate(-90) # 順時(shí)針旋轉(zhuǎn)90 clip = clip.rotate(90) # 逆時(shí)針旋轉(zhuǎn)90 clip.write_videofile("res.mp4") # save
獲取視頻的時(shí)長(zhǎng)(按秒計(jì)算)
import subprocess def get_length(filename): result = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", filename], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) return float(result.stdout) print("minute:"+str(int(get_length("test.mp4")) // 60)) print("second:"+str(int(get_length("test.mp4")) % 60))
將視頻轉(zhuǎn)換成幀序列
import cv2 import numpy as np import os video = cv2.VideoCapture("test.mp4") result_path = './save_result' # 保存的文件夾 success, frame = video.read() i = 0 while success: cv2.imwrite(os.path.join(result_path,str(i)+'.png'),frame) i = i + 1 success, frame = video.read()
從圖片中提取人臉
from PIL import Image import face_recognition inputImg = "biden.jpg" image = face_recognition.load_image_file(inputImg) faces = face_recognition.face_locations(image) for i in range(len(faces)): top, right, bottom, left = faces[i] faceImage = image[top:bottom, left:right] final = Image.fromarray(faceImage) final.save("img%s.png" % (str(i)), "PNG")
使用ffmpeg >1.1將本地的a.mp4與b.mp4合并成output.mp4(無損合并)
先創(chuàng)建一個(gè)文本文件filelist.txt,并且在文本文件中添加如下信息:
file 'a.mp4'
file 'b.mp4'
ffmpeg -f concat -i filelist.txt -c copy output.mp4
視頻幀轉(zhuǎn)視頻
ffmpeg -f image2 -i /home/ttwang/images/image%d.jpg tt.mp4
到此這篇關(guān)于使用Python將視頻按照一定時(shí)間切割(比如:每10s進(jìn)行裁切)的文章就介紹到這了,更多相關(guān)Python視頻按照時(shí)間切割內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python數(shù)據(jù)分析pandas之布爾索引使用詳解
這篇文章主要為大家介紹了Python數(shù)據(jù)分析pandas之布爾索引使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07python 線性回歸分析模型檢驗(yàn)標(biāo)準(zhǔn)--擬合優(yōu)度詳解
今天小編就為大家分享一篇python 線性回歸分析模型檢驗(yàn)標(biāo)準(zhǔn)--擬合優(yōu)度詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-02-02Python+Pillow+Pytesseract實(shí)現(xiàn)驗(yàn)證碼識(shí)別
這篇文章主要為大家詳細(xì)介紹了如何利用pillow和pytesseract來實(shí)現(xiàn)驗(yàn)證碼的識(shí)別,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2022-05-05Python實(shí)現(xiàn)線性搜索算法的示例代碼
線性搜索算法,也稱為順序搜索算法,是一種簡(jiǎn)單但常用的搜索技術(shù),在本文中,將深入研究線性搜索算法,并演示如何在?Python?中實(shí)現(xiàn)它,需要的可以參考下2024-02-02Python實(shí)現(xiàn)的文本簡(jiǎn)單可逆加密算法示例
這篇文章主要介紹了Python實(shí)現(xiàn)的文本簡(jiǎn)單可逆加密算法,結(jié)合完整實(shí)例形式分析了Python自定義加密與解密算法具體實(shí)現(xiàn)與使用技巧,需要的朋友可以參考下2017-05-05