SoFunction
Updated on 2024-11-17

Python OpenCV video capture and save implementation code

This article introduces the Python OpenCV video capture and save the realization of the code, the text through the sample code is very detailed, for everyone's learning or work has a certain reference learning value, you can refer to the next!

Before image processing, we need to sift through the data we get our hands on, and for video, we need to intercept the segment or segments we need from it

The overall idea is relatively simple, by setting the start and end time (number of frames) of the intercepted video, you can save the image within that time period as a new video

Straight to the code.

"""
[Function Name] Intercept Video
Parameters】 Input parameters Video file name
【Detailed Description】 Input different time periods to intercept splicing
[Created Date] 20191128 by wangxioabei
【Modified】 NOTE.1.
"""
def CutVideoFromFile(video_file_name,windows_name = 'videoShowing'):
  cap = (video_file_name) # Open the video file
  # Need to clarify the format in which the video will be saved
  fourcc = cv2.VideoWriter_fourcc(*'XVID')
  fps = (cv2.CAP_PROP_FPS)
  print('Frame rate: %d'%fps)
  size = (int((cv2.CAP_PROP_FRAME_WIDTH)),int((cv2.CAP_PROP_FRAME_HEIGHT)))
  out = ('',fourcc,fps, size)
  SaveTime = [[38*60+38,39*60+59],[42*60+54,44*60+11],[47*60+8,48*60+24],[51*60+20,52*60+39]]
  print(SaveTime[0][0])
  now_frame = 0
  while (()):
    ret, frame = () # Capture a frame
    img_h, img_w, img_ch = 
    # print()
    if ret:
      # [1] Can not directly save the grayscale or binarized images into video, need to be converted to color
      if img_ch==1:
        frame = (frame, cv2.COLOR_GRAY2BGR)
      # (windows_name, frame)
      for i in range(len(SaveTime)):
        if now_frame > SaveTime[i][0]*fps and now_frame < SaveTime[i][1]*fps:
          (frame)
          print(now_frame)
      now_frame += 1
      if now_frame > SaveTime[2][1]*fps:
        break;
      k = (1) & 0xFF
      if k == 27:
        break
      # (25)
    else:
      break
  ()
  ()
  ()

The SaveTime list nested in the list is the time s of the intercepted video, which can also be passed in as a parameter to encapsulate the entire function.

This is the whole content of this article.