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

Recording the moment of motion

The INFINICAM GbE-2 keeps watching at 1,000 fps. When it detects motion in the picture, it saves the 1 second before the detection and the 1 second after it as an MP4 file you can play in slow motion.

You can keep moments that happen without warning (something falling, something colliding, an insect flying past, and so on) without missing them. Because the moments before the detection are saved too, you can look back in slow motion not only at “what happened” but also at “how it came to happen”.

A dashcam always holds the last few tens of seconds, and when there is a collision, it keeps only the moments before and after it in a file. This program works the same way.

Always: keep the last 1 second of compressed data, dropping the oldest (a ring buffer)
| motion detected
Recording: add the "1 second after" that is still arriving to the "1 second before" already held
| complete
Saving: write the 2 seconds (2,000 frames) to an MP4. Watching does not stop meanwhile
State Shown on screen What it is doing
Watching WATCHING (green) Keeps holding the last 1 second while looking for motion in every frame
Recording RECORDING (red) Motion was detected, so it is collecting the 1 second after it
Saving SAVING (orange) Writing the collected 2 seconds to an MP4. Receiving and analysis continue

When saving is finished, it goes back to watching. So that one event is not saved again and again, it does not accept the next trigger for 3 seconds after a save (COOLDOWN).

Python version C++ version
Motion detection DC components (100 × 75), every frame DC components (100 × 75), every frame
Amount held (approximate) The last 1,000 frames (about 120 MB) The last 3,000 frames (about 360 MB: the frames before and after, plus a margin for the time it takes to prepare a save)
Saving In a separate thread, at the same time as analysis In a separate thread, at the same time as analysis
  • Make sure the Python versions of Finding moving objects and Saving a slow-motion MP4 work. This program combines the two.
  • The only libraries used are pypuclib and OpenCV (opencv-python).
  • The program in the sample code bundle has Japanese comments. The code below is the same program with English comments and messages.
Item Details
Camera INFINICAM GbE-2 (with a lens) and the PC it is connected to
Something that moves Something that moves in an instant, such as an object you drop or a rolling ball
Memory At least 1 GB of free memory is a good idea (used for the frames held and for preparing a save)
  1. Enter and save the program

    Save the following code as event_recorder.py in C:\infinicam_projects\python\applications (create the applications folder if it does not exist).

    import collections
    import queue
    import threading
    import time
    from datetime import datetime
    import cv2
    from pypuclib import CameraFactory, PUCException
    FRAMERATE = 1000 # Frame rate [fps]
    PRE_SECONDS = 1.0 # Time to keep before the trigger [s]
    POST_SECONDS = 1.0 # Time to keep after the trigger [s]
    PLAY_FPS = 30 # Playback speed of the MP4 [fps] (1000 / 30 = about 33x slow motion)
    COOLDOWN = 3.0 # Time after a save before the next trigger is accepted [s]
    GAP = 10 # Compare with the image this many frames earlier (10 frames = 10 ms at 1000 fps)
    THRESHOLD = 6 # Treat blocks whose brightness changed by at least this much as "moved"
    MIN_BLOCKS = 2 # Ignore smaller movements (number of blocks) as noise
    SHOW_EVERY = 33 # Make an image for display once every this many frames (33 frames = about 30 fps)
    pre_frames = int(FRAMERATE * PRE_SECONDS)
    post_frames = int(FRAMERATE * POST_SECONDS)
    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 (set here because the camera may still have the settings from its last use)
    cam.setFramerateShutter(FRAMERATE, FRAMERATE)
    reso = cam.resolution()
    # In a DC component image, each 8 x 8 pixel block becomes 1 pixel
    blocks_x = reso.width // 8
    blocks_y = reso.height // 8
    # Prepare separate decoders for analysis and for saving (two threads decode at the same time)
    decoder = cam.decoder()
    decoder.setNumDecodeThread(4)
    save_decoder = cam.decoder()
    save_decoder.setNumDecodeThread(2)
    # Warm up by decoding one frame first (the first decode takes time to set up, which would drop frames)
    data = cam.grab()
    decoder.decode(data)
    decoder.decodeDC(data, 0, 0, blocks_x, blocks_y)
    save_decoder.decode(data)
    # Queue that hands received data over to the analysis side (up to 1000 frames = 1 second)
    frames = queue.Queue(maxsize=1000)
    # (sequence number, compressed data) for the last PRE_SECONDS. The oldest are dropped automatically (ring buffer)
    ring = collections.deque(maxlen=pre_frames)
    # Current state: WATCHING -> RECORDING (collecting after the trigger) -> SAVING -> WATCHING
    state = {"mode": "WATCHING", "pre": None, "post": [], "trigger_seq": None, "cooldown_until": 0.0, "saved": 0}
    lock = threading.Lock()
    # Queue that hands (list of frames, trigger sequence number) to the saving side
    save_jobs = queue.Queue()
    # Counters
    stats = {"received": 0, "gaps": 0, "overflow": 0, "processed": 0, "process_time": 0.0}
    last_seq = None
    # The newest image and the moving areas, for display
    shown = {"image": None, "boxes": []}
    def on_frame(xfer):
    """Called every time a frame arrives. Only keeps the compressed data and puts it in the analysis queue"""
    global last_seq
    stats["received"] += 1
    # If the sequence number skips, the skipped frames were dropped
    seq = xfer.sequenceNo()
    if last_seq is not None:
    stats["gaps"] += ((seq - last_seq) & 0xFFFF) - 1
    last_seq = seq
    if xfer.isDamaged():
    return
    data = xfer.data().copy()
    with lock:
    ring.append((seq, data)) # Always keep the last PRE_SECONDS
    if state["mode"] == "RECORDING":
    # Collect POST_SECONDS after the trigger
    state["post"].append((seq, data))
    if len(state["post"]) >= post_frames:
    save_jobs.put((state["pre"] + state["post"], state["trigger_seq"]))
    state["mode"] = "SAVING"
    state["pre"] = None
    state["post"] = []
    try:
    frames.put_nowait((seq, data))
    except queue.Full:
    stats["overflow"] += 1 # The analysis could not keep up and the queue overflowed
    def find_motion(dc_now, dc_before):
    """Compare two DC component images and return a list of rectangles (in pixels) where something moved"""
    diff = cv2.absdiff(dc_now, dc_before)
    _, mask = cv2.threshold(diff, THRESHOLD - 1, 255, cv2.THRESH_BINARY)
    mask = cv2.dilate(mask, None) # Join neighboring blocks so one object is found as one
    contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    boxes = []
    for contour in contours:
    x, y, w, h = cv2.boundingRect(contour)
    if w * h >= MIN_BLOCKS:
    boxes.append((x * 8, y * 8, w * 8, h * 8)) # Convert from blocks to pixels
    return boxes
    def trigger(seq):
    """Called when motion is found. If watching, take the frames before the trigger and start recording"""
    with lock:
    if state["mode"] != "WATCHING" or time.perf_counter() < state["cooldown_until"]:
    return
    if len(ring) < pre_frames:
    return # Right after starting, the frames before the trigger have not been collected yet, so wait
    state["pre"] = list(ring) # Take the last PRE_SECONDS up to this point
    state["post"] = []
    state["trigger_seq"] = seq
    state["mode"] = "RECORDING"
    print("Motion detected. Recording before and after...")
    def analyze_worker():
    """Takes frames out of the queue one at a time and looks for motion (runs in a separate thread)"""
    history = collections.deque(maxlen=GAP) # DC component images of the last GAP frames
    count = 0
    while True:
    item = frames.get()
    if item is None: # Signal to finish
    break
    seq, data = item
    start = time.perf_counter()
    dc = decoder.decodeDC(data, 0, 0, blocks_x, blocks_y)
    if dc.ndim == 3:
    dc = cv2.cvtColor(dc, cv2.COLOR_BGR2GRAY) # For a color camera, convert to grayscale before comparing
    boxes = []
    if len(history) == GAP:
    boxes = find_motion(dc, history[0]) # Compare with the image GAP frames earlier
    history.append(dc)
    if boxes:
    trigger(seq)
    stats["process_time"] += time.perf_counter() - start
    stats["processed"] += 1
    # Only once every SHOW_EVERY frames, decode the whole image and pass it on for display
    count += 1
    if count % SHOW_EVERY == 0:
    image = decoder.decode(data, reso)
    with lock:
    shown["image"] = image
    shown["boxes"] = boxes
    def save_mp4(clip, trigger_seq):
    """Decode the collected compressed data one frame at a time and write it to an MP4 file"""
    filename = datetime.now().strftime("event_%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
    for seq, data in clip:
    image = save_decoder.decode(data, reso)
    if image.ndim == 2:
    image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR) # Write the MP4 in color
    # Time from the trigger frame (negative before, positive after). The sequence number wraps from 65535 to 0
    offset = ((seq - trigger_seq + 32768) & 0xFFFF) - 32768
    t_ms = offset * 1000 / FRAMERATE
    cv2.putText(image, f"{t_ms:+8.1f} ms", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2)
    if offset == 0:
    # Make the trigger frame stand out with a red border and text
    cv2.rectangle(image, (0, 0), (reso.width - 1, reso.height - 1), (0, 0, 255), 8)
    cv2.putText(image, "TRIGGER", (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)
    writer.write(image)
    writer.release()
    print(f"Saved: {filename} ({len(clip)} frames, plays for {len(clip) / PLAY_FPS:.0f} seconds)")
    def save_worker():
    """The saving side (runs in a separate thread). Receiving and analysis keep running while saving"""
    while True:
    job = save_jobs.get()
    if job is None: # Signal to finish
    break
    clip, trigger_seq = job
    save_mp4(clip, trigger_seq)
    with lock:
    state["mode"] = "WATCHING"
    state["cooldown_until"] = time.perf_counter() + COOLDOWN
    state["saved"] += 1
    window = "Event recorder (ESC or Q to quit)"
    cv2.namedWindow(window, cv2.WINDOW_AUTOSIZE)
    worker = threading.Thread(target=analyze_worker)
    saver = threading.Thread(target=save_worker)
    worker.start()
    saver.start()
    # Start continuous transfer (on_frame is called every time a frame arrives)
    cam.setRingBufferCount(64)
    cam.beginXfer(on_frame)
    print("Watching... When motion is detected, the moments before and after it are saved as an MP4. Select the video window and press ESC or Q to exit.")
    colors = {"WATCHING": (0, 255, 0), "RECORDING": (0, 0, 255), "SAVING": (0, 200, 255)}
    try:
    last_time = time.perf_counter()
    last_processed = 0
    last_process_time = 0.0
    info = ""
    while True:
    with lock:
    image = shown["image"]
    boxes = shown["boxes"]
    shown["image"] = None
    mode = state["mode"]
    saved = state["saved"]
    # Every second, work out how many frames were analyzed in the last second and the time per frame
    now = time.perf_counter()
    if now - last_time >= 1.0:
    n = stats["processed"] - last_processed
    t = stats["process_time"] - last_process_time
    per_frame = t / n * 1000 if n else 0
    info = (f"process: {n / (now - last_time):.0f} fps ({per_frame:.2f} ms/frame) "
    f"dropped: {stats['gaps']} overflow: {stats['overflow']}")
    last_time, last_processed, last_process_time = now, stats["processed"], stats["process_time"]
    if image is not None:
    if image.ndim == 2:
    image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR) # Convert to color so the boxes can be colored
    for x, y, w, h in boxes:
    cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2)
    cv2.putText(image, info, (10, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (0, 255, 0), 2)
    cv2.putText(image, f"{mode} saved: {saved}", (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.55, colors[mode], 2)
    cv2.imshow(window, image)
    key = cv2.waitKey(1) & 0xFF
    if key in (27, ord("q"), ord("Q")): # ESC or Q
    break
    finally:
    # Stop continuous transfer, finish the analysis and saving sides, then close the camera
    # (anything being saved is written to the end)
    cam.endXfer()
    frames.put(None)
    worker.join()
    save_jobs.put(None)
    saver.join()
    cam.close()
    cv2.destroyAllWindows()
    print(f"Done (received: {stats['received']}, analyzed: {stats['processed']}, "
    f"dropped: {stats['gaps']}, overflow: {stats['overflow']}, saved: {state['saved']}).")
  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 event_recorder.py
  3. Make something happen

    When the video window opens and WATCHING appears in the top-left corner, it is watching. Drop something in front of the camera, or move your hand quickly. The display changes to RECORDING and then SAVING, and after a while the console shows the following.

    Motion detected. Recording before and after...
    Saved: event_20261023_101530.mp4 (2000 frames, plays for 67 seconds)

    Double-click the event_(date and time).mp4 file created in C:\infinicam_projects\python\applications to play it in slow motion. The number in the top-left corner is the time from the trigger frame (negative before, positive after). The trigger frame is marked with a red border and the text TRIGGER.

  4. Exit

    Select the video window and press ESC or Q. If something is being saved, the program exits after it finishes writing.

What is shown in the top-left corner of the window:

Display Meaning
process: 1000 fps Frames analyzed in the last second. Around 1000 means motion is checked in every frame
ms/frame Time taken to analyze one frame
dropped Frames that did not arrive (dropped frames)
overflow Frames that overflowed the queue because the analysis could not keep up
WATCHING and so on The current state (see the table in “How it works” above)
saved Number of saves so far

1. Keep holding the last 1 second (a ring buffer)

ring = collections.deque(maxlen=pre_frames)
...
ring.append((seq, data))

collections.deque(maxlen=…) is a container that automatically drops the oldest items when it goes over the set number. If you add each frame as it arrives, the “last 1 second (1,000 frames)” is always there. The contents stay compressed, so each frame is about 120 KB, and even 1,000 frames are only about 120 MB.

2. When motion is detected, take out the frames before it

state["pre"] = list(ring) # Take the last PRE_SECONDS up to this point
state["mode"] = "RECORDING"

When the analysis side detects motion, the trigger function takes out and keeps the contents of ring at that moment. The frames that arrive after that are collected in post by the receiving function (on_frame). When 1,000 frames are collected, the before and after are joined and handed to the saving side.

Right after the program starts, ring does not yet hold 1 second of frames, so the trigger function does not accept a trigger until it is full.

Motion is detected the same way as in the Python version of Finding moving objects (comparing the DC components with those 10 frames earlier).

3. Leave saving to a separate side

save_jobs.put((state["pre"] + state["post"], state["trigger_seq"]))

Writing an MP4 takes several seconds. If watching stopped during that time, the next event would be missed. So writing is left to the saving side (save_worker, a separate thread), and receiving and analysis keep running. The saving side uses its own decoder (save_decoder), separate from the analysis side’s, because both sides decode at the same time.

4. Write the time from the trigger

offset = ((seq - trigger_seq + 32768) & 0xFFFF) - 32768

From the difference with the sequence number of the trigger frame, the program works out how many ms before or after the trigger each frame is, and writes it on the frame. The difference is brought into the range -32768 to 32767 so that frames before the trigger become negative (the sequence number cycles through 0 to 65535).


Change Example What happens
PRE_SECONDS = 1.0 3.0 Keeps from 3 seconds before the trigger. The memory used to hold frames also triples (about 360 MB)
POST_SECONDS = 1.0 0.5 Keeps only 0.5 seconds after the trigger
COOLDOWN = 3.0 10.0 After a save, the next trigger is not accepted for 10 seconds
THRESHOLD = 6 10 Small changes in brightness no longer trigger a save
MIN_BLOCKS = 2 10 Only large moving objects trigger a save

Symptom Likely cause What to do
It saves again and again even though nothing happened Flickering lights, or noise in the image Increase THRESHOLD or MIN_BLOCKS. Use a battery-powered light or daylight
Nothing is saved even when something moves The difference in brightness is small Decrease THRESHOLD. Try with something whose color differs from the background
The C++ version shows “Error: could not create the MP4 file.” opencv_videoio_ffmpeg500_64.dll is not next to the EXE Check the post-build event in step 2 of “Try it”
overflow or dropped grows only while saving Saving is taking CPU time Close other applications. Make sure the C++ version is built in Release
dropped is not 0 Network settings Check jumbo packets in PC requirements and network settings
The MP4 does not play The video player does not support MPEG-4 (mp4v) Open it in a free video player such as VLC

  • If the trigger is a trigger signal input to the camera’s general-purpose input (General In) instead of “motion”, you can keep the moments before and after an external sensor or switch responds.
  • Before saving, cropping only the area that moved (ROI) or drawing the path of the moving object makes the video easier to review later.