溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

怎么在python項(xiàng)目中利用openCV實(shí)現(xiàn)一個(gè)截取視頻功能

發(fā)布時(shí)間:2020-11-30 16:29:06 來源:億速云 閱讀:219 作者:Leah 欄目:開發(fā)技術(shù)

怎么在python項(xiàng)目中利用openCV實(shí)現(xiàn)一個(gè)截取視頻功能?相信很多沒有經(jīng)驗(yàn)的人對(duì)此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。

使用cv2對(duì)視頻進(jìn)行切割

import cv2


def clip_video(source_video, target_video, start_time, end_time):
  cap = cv2.VideoCapture(source_video)
  if not cap.isOpened():
    logger_warning('video is not opened')
  else:
    success, frame = cap.read()
    f_shape = frame.shape
    f_height = f_shape[0] # 原視頻圖片的高度
    f_width = f_shape[1]
    fps = cap.get(5) # 幀速率
    frame_number = cap.get(7) # 視頻文件的幀數(shù)
    duration = frame_number / fps # 視頻總幀數(shù)/幀速率 是時(shí)間/秒【總共有多少秒的視頻時(shí)間】
    if start_time > duration or end_time > duration:
      return
    start_time = fps * float(start_time)
    end_time = fps * float(end_time)
    # AVI格式編碼輸出 XVID
    four_cc = cv2.VideoWriter_fourcc(*'H264')
    video_writer = cv2.VideoWriter(target_video, four_cc, fps, (int(f_width), int(f_height)))
    num = 0
    while True:
      success, frame = cap.read()
      if int(start_time) <= int(num) <= int(end_time):
        if success:
          video_writer.write(frame)
        else:
          break
      num += 1
      if num > frame_number:
        break
    cap.release()

VideoWriter_fourcc編碼格式:

fourcc意為四字符代碼(Four-Character Codes),顧名思義,該編碼由四個(gè)字符組成,下面是VideoWriter_fourcc對(duì)象一些常用的參數(shù),注意:字符順序不能弄混
cv2.VideoWriter_fourcc('I', '4', '2', '0'),該參數(shù)是YUV編碼類型,文件名后綴為.avi
cv2.VideoWriter_fourcc('P', 'I', 'M', 'I'),該參數(shù)是MPEG-1編碼類型,文件名后綴為.avi
cv2.VideoWriter_fourcc('X', 'V', 'I', 'D'),該參數(shù)是MPEG-4編碼類型,文件名后綴為.avi
cv2.VideoWriter_fourcc('T', 'H', 'E', 'O'),該參數(shù)是Ogg Vorbis,文件名后綴為.ogv
cv2.VideoWriter_fourcc('F', 'L', 'V', '1'),該參數(shù)是Flash視頻,文件名后綴為.flv

看完上述內(nèi)容,你們掌握怎么在python項(xiàng)目中利用openCV實(shí)現(xiàn)一個(gè)截取視頻功能的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI