python利用ffmpeg將一段大視頻等份的切成多個小視頻段


在剪輯視頻的過程中發現部分手機拍攝的視頻是帶有rotate旋轉矯正參數的,一般的opencv腳本剪輯出來的視頻是歪的。查詢了大量的資料找到一種使用ffmpeg剪輯的方法,將opencv和ffmpeg結合使用可以剪輯目前絕大多數的手機視頻。

def cutVideo(path,filename):
    video_full_path = path + r'\\' +filename
    video_full_path_new = path + r'\\' +'new_'+filename
    cap = cv2.VideoCapture(video_full_path)
    cap.isOpened()
    width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
    height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)

    print(width, height)

    if cap.isOpened():  # 當成功打開視頻時cap.isOpened()返回True,否則返回False
        # get方法參數按順序對應下表(從0開始編號)
        rate = cap.get(5)  # 幀速率
        FrameNumber = int(cap.get(7))  # 視頻文件的幀數
        duration = FrameNumber / rate  # 幀速率/視頻總幀數 是時間,除以60之后單位是分鍾
        len = int(duration)
        fps = int(rate)
        print(rate, FrameNumber)

        if (width > height):

            for i in range(0,len):
                video_full_path_new = path + r'\\' + str(i) + filename
                print(i)
                cmd = 'ffmpeg -i {0} -vcodec copy -acodec copy -ss 00:00:0{1} -to 00:00:0{2} {3} -y'.format(video_full_path,str(i),str(i+1),video_full_path_new)
                os.system(cmd)

        else:
            i = 0
            while (True):
                success, frame = cap.read()
                if success:
                    i += 1
                    # print('i = ', i)
                    if (i % fps == 1):
                        videoWriter = cv2.VideoWriter(path + '/' + str(i) + filename,
                                                      cv2.VideoWriter_fourcc('D', 'I', 'V', 'X'), fps,
                                                      (int(width), int(height)))
                        videoWriter.write(frame)
                    else:
                        videoWriter.write(frame)
                else:
                    print('end')
                    break



    cap.release()

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM