Search code examples
pythonopencvvideo-capturechunksip-camera

How to create regular video chunks during recording?


I want to create regular multiple video chunks when capturing the camera. Video chunks should be 3s with .mp4 container. The capturing is fine but the chunks were not created.

import numpy as np
import cv2
import time
import os 

cap = cv2.VideoCapture(0)

try:
    if not os.path.exists('chunks'):
        os.makedirs('chunks')
except OSError:
    print ('Error: Creating directory of data')
    
next_time = time.time() + 3

while True:
    # Capture frame-by-frame
    ret, frame = cap.read() 
    
    if time.time() > next_time:
        fourcc = cv2.VideoWriter_fourcc(*'XVID')
        chunks = cv2.VideoWriter('/chunks/' + str(time.strftime('%d %m %Y - %H %M %S' )) + '.mp4', fourcc, 15, (640,480))
        next_time += 3

cap.release()
cv2.destroyAllWindows()

Solution

  • A few bugs in your code:

    1. Nowhere in your loop did you call the cv2.VideoWriter.write method on your chunks objects. In your code it would look like this: chunks.write(frame).

    2. For every video you want to generate, you'll need to call the cv2.VideoWriter.release method, like this chunks.release().

    3. The duration of your resulting videos does not rely on the amount of time it takes to generate one; it relies on the number of frames written to the video and the framerate of the video. In your code you chose the framerate 15, so every video would need 15 * 3 = 45 frames to be 3 seconds long.

    Corrected your code might look something like this:

    import os
    import time
    import cv2
    
    try:
        if not os.path.exists('chunks'):
            os.makedirs('chunks')
    except OSError:
        print('Error: Creating directory of data')
    
    cap = cv2.VideoCapture(0)
    fourcc = cv2.VideoWriter_fourcc(*"XVID")
    chunks = cv2.VideoWriter(f"chunks/{time.strftime('%d %m %Y - %H %M %S')}.mp4", fourcc, 15, (640, 480))
    i = 0
    while True:
        i += 1
        if i > 45:
            chunks.release()
            chunks = cv2.VideoWriter(f"chunks/{time.strftime('%d %m %Y - %H %M %S')}.mp4", fourcc, 15, (640, 480))
            i = 0
        ret, frame = cap.read()
        chunks.write(frame)
    
    cap.release()
    cv2.destroyAllWindows()
    

    Which works perfectly.