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.
What you need
Section titled “What you need”| 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 |
Tips for capturing
Section titled “Tips for capturing”- 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.
Try it
Section titled “Try it”-
Enter and save the program
Create a folder named
applicationsinsideC:\infinicam_projects\python, and save the following code in it asslow_motion.py.import threadingfrom datetime import datetimeimport cv2from pypuclib import CameraFactory, PUCExceptionFRAMERATE = 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 addresscam = 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 * SECONDSlatest = None # The newest frame, for displayrecording = False # Whether a recording is in progressrecorded = [] # (sequence number, compressed data) collected while recordingrecord_done = threading.Event()lock = threading.Lock()def on_frame(xfer):"""Called by pypuclib every time a frame arrives (a callback)"""global latest, recordingif xfer.isDamaged():return # Skip data that arrived incompletedata = xfer.data().copy() # The contents are overwritten after this function returns, so keep a copywith lock:latest = dataif 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 = Falserecord_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.")returnelapsed = 0 # Frames elapsed since the first framedropped = 0 # Frames that did not arriveprev_seq = frames[0][0]for i, (seq, data) in enumerate(frames):step = (seq - prev_seq) & 0xFFFF # The sequence number wraps from 65535 back to 0if i > 0:elapsed += stepdropped += step - 1prev_seq = seqimage = 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 framet_ms = elapsed * 1000 / FRAMERATEcv2.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 = latestlatest = Nonenow_recording = recordingif data is not None:# Decode and show only the newest frameimage = 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 filerecord_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) & 0xFFif key == ord(" "):with lock:if not recording:recorded.clear()recording = Trueprint(f"Recording... ({SECONDS} seconds)")elif key in (27, ord("q"), ord("Q")): # ESC or Qbreakfinally:# Stop continuous transfer, then close the cameracam.endXfer()cam.close()cv2.destroyAllWindows()print("Done.") -
Run it
Run the following 2 lines, one at a time, in Command Prompt (or PowerShell).
Terminal window cd C:\infinicam_projects\python\applicationsTerminal window python slow_motion.pyA live video window opens. Point the camera and adjust the focus so that what you want to capture is in the picture.
-
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 framesWriting... 1000 / 2000 framesWriting... 1500 / 2000 framesWriting... 2000 / 2000 framesSaved: 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
ESCorQ. -
Play it
Double-click the
slow_(date and time).mp4file created inC:\infinicam_projects\python\applicationsto 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.
How the program works
Section titled “How the program works”1. While recording, only collect the data
Section titled “1. While recording, only collect the data”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.
3. Time since the recording started
Section titled “3. Time since the recording started”step = (seq - prev_seq) & 0xFFFFelapsed += stept_ms = elapsed * 1000 / FRAMERATEThe 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.
4. The MP4 format
Section titled “4. The MP4 format”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.
Things to try
Section titled “Things to try”| 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 |
Troubleshooting
Section titled “Troubleshooting”| 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 |
Next applications
Section titled “Next applications”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.
