clip_video.py 966 B

123456789101112131415161718192021222324252627282930313233343536
  1. import cv2
  2. def cut_video(video_path, frameToStart, frametoStop, saved_video_path):
  3. cap = cv2.VideoCapture(video_path)
  4. FPS = cap.get(cv2.CAP_PROP_FPS)
  5. TOTAL_FRAME = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) # 获取视频总帧数
  6. size = (cap.get(cv2.CAP_PROP_FRAME_WIDTH),
  7. cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
  8. videoWriter = cv2.VideoWriter(
  9. saved_video_path,
  10. apiPreference=0,
  11. fourcc=cv2.VideoWriter_fourcc(* 'mp4v'),
  12. fps=FPS,
  13. frameSize=(int(size[0]), int(size[1])))
  14. COUNT = 0
  15. while True:
  16. success, frame = cap.read()
  17. if success:
  18. COUNT += 1
  19. if COUNT <= frametoStop and COUNT > frameToStart: # 选取起始帧
  20. videoWriter.write(frame)
  21. else:
  22. print("cap.read failed!")
  23. break
  24. if COUNT > frametoStop:
  25. break
  26. cap.release()
  27. videoWriter.release()
  28. print(saved_video_path)