import cv2
start_time, end_time = 0, 10
cap = cv2.VideoCapture(file_dir + name) # 讀取視訊
fourcc = cv2.VideoWriter_fourcc(*'mp4v') # 定義mp4編解碼器
name_new = 'test.mp4' # 儲存新視訊名字
cap.set(cv2.CAP_PROP_POS_MSEC, start_time * 1000) # 進行視訊定位播放,機關毫秒
out = cv2.VideoWriter(name_new, fourcc, cap.get(5), # ,建立VideoWriter 對象, get(5)是fps, 3是width, 4是height
(int(cap.get(3)), int(cap.get(4))))
if cap.isOpened():
ret, frame = cap.read()
while ret:
if cap.get(cv2.CAP_PROP_POS_MSEC) >= end_time*1000: # 超出結束時間的時候,結束
break
out.write(frame) # 寫入
ret, frame = cap.read() # 讀取下一幀
cap.release()
out.release()