1. 程式人生 > 實用技巧 >python擷取視訊中的某一段

python擷取視訊中的某一段

# 功能:對視訊檔案進行剪下。
# 剪下指定長度的視訊,選擇要裁剪的視訊,選擇開始時間點和停止時間點即可。
# 將處理後的視訊儲存為output.avi檔案
import cv2 # OpenCV
import tkinter.filedialog # Python檔案對話方塊

def samllVideoGif(_videoPath,_videoGifPath):
# _videoPath = "C:\\Users\\sswc\\Desktop\\gai2\\public\\showPdf\\6f3db1f9-e247-4aa5-bca7-93bae62a0079.mp4"
# _videoGifPath = "C:\\Users\\sswc\\Desktop\\gai2\\public\\showPdf\\6f3db1f9-e247-4aa5-bca7-93bae62a0079.avi"
cap = cv2.VideoCapture(_videoPath) # 開啟視訊檔案
frames = cap.get(cv2.CAP_PROP_FRAME_COUNT) # 獲得視訊檔案的幀數
fps = cap.get(cv2.CAP_PROP_FPS) # 獲得視訊檔案的幀率
width = cap.get(cv2.CAP_PROP_FRAME_WIDTH) # 獲得視訊檔案的幀寬
height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT) # 獲得視訊檔案的幀高

# 建立儲存視訊檔案類物件
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter(_videoGifPath, fourcc, fps, (int(width), int(height)))

# 計算視訊長度/s
video_length = frames / fps
# print('start and stop must < %.1f' % video_length) # 提示使用者輸入變數的範圍
# start = float(input('Input an start time/s:'))
# stop = float(input('Input an stop time/s:'))
# print('start and stop must < %.1f' % video_length) # 提示使用者輸入變數的範圍
start = 0
stop = 10
# 設定幀讀取的開始位置
cap.set(cv2.CAP_PROP_POS_FRAMES, start * fps)
pos = cap.get(cv2.CAP_PROP_POS_FRAMES) # 獲得幀位置
while (pos <= stop * fps):
ret, frame = cap.read() # 捕獲一幀影象
out.write(frame) # 儲存幀
pos = cap.get(cv2.CAP_PROP_POS_FRAMES)

cap.release()
out.release()