Skip to content
⚡ Developer documentation for INFINICAM, the real-time high-speed camera (UC-1.1 / GbE-2)

Saving a slow-motion MP4

Capture 2 seconds at 1,000 fps with the INFINICAM GbE-2 and save it as an MP4 file that any video player can play. Because it plays back at 30 fps, you get about 33x slow motion.

You can aim while watching the live video, and record just by pressing the space bar. This is the simplest experiment for enjoying what a high-speed camera can capture.

Item Details
Camera INFINICAM GbE-2 (with a lens) and the PC it is connected to
Something to capture Something that moves fast. For example, a pen dropped on a desk, clapping hands, water drops falling from a tap, or a spinning fan
  • Adjust the focus before recording, while watching the live video.
  • A plain background (white paper, black cloth, and so on) makes the motion easier to see.
  1. Enter and save the program

    Create a folder named applications inside C:\infinicam_projects\python, and save the following code in it as slow_motion.py.

    import threading
    from datetime import datetime
    import cv2
    from pypuclib import CameraFactory, PUCException
    FRAMERATE = 1000 # Frame rate for capturing [fps]
    SECONDS = 2 # Length of one recording [s]
    PLAY_FPS = 30 # Playback speed of the MP4 [fps] (1000 / 30 = about 33x slow motion)
    print("Connecting to the camera...")
    try:
    # Connect to the GbE-2 at this IP address
    cam = CameraFactory().create(ip="192.168.0.10")
    except PUCException as e:
    print("Error: could not connect to the camera.", e)
    raise SystemExit(1)
    # Set the frame rate and shutter speed (set here because the camera may still have the settings from its last use)
    cam.setFramerateShutter(FRAMERATE, FRAMERATE)
    reso = cam.resolution()
    decoder = cam.decoder()
    # Warm up by decoding one frame first (the first decode takes time to set up,
    # which would cause dropped frames at the start of a recording)
    decoder.decode(cam.grab())
    frames_to_record = FRAMERATE * SECONDS
    latest = None # The newest frame, for display
    recording = False # Whether a recording is in progress
    recorded = [] # (sequence number, compressed data) collected while recording
    record_done = threading.Event()
    lock = threading.Lock()
    def on_frame(xfer):
    """Called by pypuclib every time a frame arrives (a callback)"""
    global latest, recording
    if xfer.isDamaged():
    return # Skip data that arrived incomplete
    data = xfer.data().copy() # The contents are overwritten after this function returns, so keep a copy
    with lock:
    latest = data
    if recording:
    # While recording, only collect the compressed data (heavy work here would drop frames)
    recorded.append((xfer.sequenceNo(), data))
    if len(recorded) >= frames_to_record:
    recording = False
    record_done.set()
    def white(image):
    """Return white for both monochrome and color images"""
    return 255 if image.ndim == 2 else (255, 255, 255)
    def save_mp4(frames):
    """Decode the collected compressed data one frame at a time and write it to an MP4 file"""
    filename = datetime.now().strftime("slow_%Y%m%d_%H%M%S.mp4")
    fourcc = cv2.VideoWriter_fourcc(*"mp4v")
    writer = cv2.VideoWriter(filename, fourcc, PLAY_FPS, (reso.width, reso.height))
    if not writer.isOpened():
    print("Error: could not create the MP4 file.")
    return
    elapsed = 0 # Frames elapsed since the first frame
    dropped = 0 # Frames that did not arrive
    prev_seq = frames[0][0]
    for i, (seq, data) in enumerate(frames):
    step = (seq - prev_seq) & 0xFFFF # The sequence number wraps from 65535 back to 0
    if i > 0:
    elapsed += step
    dropped += step - 1
    prev_seq = seq
    image = decoder.decode(data, reso)
    if image.ndim == 2:
    image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR) # Write the MP4 in color
    # Write the time since the recording started on each frame
    t_ms = elapsed * 1000 / FRAMERATE
    cv2.putText(image, f"{t_ms:7.1f} ms", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2)
    writer.write(image)
    if (i + 1) % 500 == 0:
    print(f" Writing... {i + 1} / {len(frames)} frames")
    writer.release()
    print(f"Saved: {filename} ({len(frames)} frames, {dropped} dropped)")
    print(f"It plays for {len(frames) / PLAY_FPS:.0f} seconds (about {FRAMERATE / PLAY_FPS:.0f}x slow motion).")
    window = "Slow motion (SPACE: record, ESC or Q: quit)"
    cv2.namedWindow(window, cv2.WINDOW_AUTOSIZE)
    # Start continuous transfer (on_frame is called every time a frame arrives)
    cam.setRingBufferCount(64)
    cam.beginXfer(on_frame)
    print(f"Live view running... Select the video window and press SPACE to record {SECONDS} seconds. Press ESC or Q to exit.")
    try:
    while True:
    with lock:
    data = latest
    latest = None
    now_recording = recording
    if data is not None:
    # Decode and show only the newest frame
    image = decoder.decode(data, reso)
    if now_recording:
    cv2.putText(image, "REC", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.8, white(image), 2)
    cv2.imshow(window, image)
    if record_done.is_set():
    # When the recording is finished, write the collected data to an MP4 file
    record_done.clear()
    with lock:
    frames = recorded[:]
    recorded.clear()
    print(f"Recorded {len(frames)} frames. Writing the MP4...")
    save_mp4(frames)
    print("To record again, press SPACE.")
    key = cv2.waitKey(1) & 0xFF
    if key == ord(" "):
    with lock:
    if not recording:
    recorded.clear()
    recording = True
    print(f"Recording... ({SECONDS} seconds)")
    elif key in (27, ord("q"), ord("Q")): # ESC or Q
    break
    finally:
    # Stop continuous transfer, then close the camera
    cam.endXfer()
    cam.close()
    cv2.destroyAllWindows()
    print("Done.")
  2. Run it

    Run the following 2 lines, one at a time, in Command Prompt (or PowerShell).

    Terminal window
    cd C:\infinicam_projects\python\applications
    Terminal window
    python slow_motion.py

    A live video window opens. Point the camera and adjust the focus so that what you want to capture is in the picture.

  3. Record

    Click the video window to select it, then press the space bar. After 2 seconds of recording, writing the MP4 file starts (it takes several seconds to over ten seconds). It worked if you see output like this.

    Connecting to the camera...
    Live view running... Select the video window and press SPACE to record 2 seconds. Press ESC or Q to exit.
    Recording... (2 seconds)
    Recorded 2000 frames. Writing the MP4...
    Writing... 500 / 2000 frames
    Writing... 1000 / 2000 frames
    Writing... 1500 / 2000 frames
    Writing... 2000 / 2000 frames
    Saved: slow_20261022_170812.mp4 (2000 frames, 0 dropped)
    It plays for 67 seconds (about 33x slow motion).
    To record again, press SPACE.

    The numbers in the file name are the date and time of the recording. Press the space bar again to record as many times as you like. To exit, select the video window and press ESC or Q.

  4. Play it

    Double-click the slow_(date and time).mp4 file created in C:\infinicam_projects\python\applications to play it in the Windows Media Player. Two seconds of action play as about 67 seconds of slow motion. The number in the top-left corner is the time since the recording started, in milliseconds.


if recording:
recorded.append((xfer.sequenceNo(), data))

At 1,000 fps, each frame must be handled within 1 ms, or the next one arrives. Writing an MP4 (decoding and video compression) takes several ms per frame, so it cannot be done while recording. So while recording, the program only collects the compressed data in memory, and writes the MP4 all at once after the recording ends.

The compressed data is about 120 KB per frame, so 2 seconds (2,000 frames) is only about 240 MB.

2. Playback speed and the slow-motion factor

Section titled “2. Playback speed and the slow-motion factor”
writer = cv2.VideoWriter(filename, fourcc, PLAY_FPS, (reso.width, reso.height))

The third value of cv2.VideoWriter is the playback speed (how many frames are shown per second). Images captured at 1,000 fps are played at 30 fps, so the motion is 1,000 / 30 = about 33x slower.

step = (seq - prev_seq) & 0xFFFF
elapsed += step
t_ms = elapsed * 1000 / FRAMERATE

The camera attaches a sequence number (sequenceNo) to each image. From the difference in sequence numbers, the program works out how many frames (and so how many ms) have passed since the recording started, and writes it on each frame. Even if a frame is dropped, the sequence number still gives the correct time. & 0xFFFF keeps the calculation correct when the sequence number wraps from 65535 back to 0.

fourcc = cv2.VideoWriter_fourcc(*"mp4v")

mp4v is the name of a video format called MPEG-4. OpenCV can write it on its own, with no extra software.


Change Example What happens
SECONDS = 2 SECONDS = 5 Records 5 seconds. The memory used also grows 2.5 times (about 600 MB)
PLAY_FPS = 30 PLAY_FPS = 10 Plays back more slowly, for about 100x slow motion
FRAMERATE = 1000 A smaller capture area and 5000, for example Captures even faster motion. For how to change the capture area, see Changing capture settings + SingleImage

Symptom Likely cause What to do
The brightness of the whole picture goes up and down Flickering lights Use a battery-powered light or daylight
Pressing the space bar does not start recording The black Command Prompt window is selected Click the video window first, then press the key
“dropped” is not 0 Network settings, or other heavy processing Check jumbo packets in PC requirements and network settings. Close other applications
The MP4 does not play The video player does not support MPEG-4 (mp4v) Open it in a free video player such as VLC

This page is about “capture first, view later”. The real strength of INFINICAM is that it can analyze on the spot while capturing. Under “Finding and measuring on the spot” in the list of applications, we will introduce ways to process images in real time.