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

Finding moving objects

This application analyzes every 1,000 fps image from the INFINICAM GbE-2 on the spot, without skipping a single one. It finds the areas of the picture that moved and draws red boxes around them.

The top-left corner of the screen shows the number of frames analyzed per second (fps), the analysis time per frame, and the number of dropped frames. You can see in numbers that every frame is processed in real time while capturing.

Python version C++ version
Image used for the analysis DC components (a 100 × 75 scaled-down image) The full image (800 × 600)
Analysis time per frame (measured) About 0.25 ms About 0.8 to 1.1 ms
How it keeps up with 1,000 fps Makes the analyzed image smaller Uses two analysis workers (threads) to process two frames at the same time
Item Details
Camera INFINICAM GbE-2 (with a lens) and the PC it is connected to
Something that moves A hand, a rolling ball, a pendulum, or anything else that moves in the picture
  1. Enter and save the program

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

    import collections
    import queue
    import threading
    import time
    import cv2
    from pypuclib import CameraFactory, PUCException
    FRAMERATE = 1000 # Frame rate [fps]
    GAP = 10 # How many frames back to compare with (10 frames = 10 ms at 1000 fps)
    THRESHOLD = 6 # Blocks whose brightness changed by at least this much are treated as "moved"
    MIN_BLOCKS = 2 # Motion smaller than this (in blocks) is ignored as noise
    SHOW_EVERY = 33 # Create a display image once every this many frames (33 frames = about 30 fps)
    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 the DC-component image, each 8 x 8 pixel block becomes one pixel
    blocks_x = reso.width // 8
    blocks_y = reso.height // 8
    # Prepare the decoder and have it decode the full image with 4 threads in parallel
    decoder = cam.decoder()
    decoder.setNumDecodeThread(4)
    # Warm up by decoding one frame first (the first decode takes time to set up, which causes dropped frames)
    data = cam.grab()
    decoder.decode(data)
    decoder.decodeDC(data, 0, 0, blocks_x, blocks_y)
    # Queue that hands received data over to the analysis side (up to 1000 frames = 1 second)
    frames = queue.Queue(maxsize=1000)
    # Counters
    stats = {"received": 0, "gaps": 0, "overflow": 0, "processed": 0, "process_time": 0.0}
    last_seq = None
    # The newest image and the areas that moved, for display
    shown = {"image": None, "boxes": []}
    lock = threading.Lock()
    def on_frame(xfer):
    """Called every time a frame arrives. Do nothing heavy here: just put it in the 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
    try:
    frames.put_nowait(xfer.data().copy())
    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) # Connect neighboring blocks so that 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 analyze_worker():
    """Take frames out of the queue one by one and look for motion (runs in a separate thread)"""
    history = collections.deque(maxlen=GAP) # DC-component images of the last GAP frames
    count = 0
    while True:
    data = frames.get()
    if data is None: # Signal to finish
    break
    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) # With 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 ago
    history.append(dc)
    stats["process_time"] += time.perf_counter() - start
    stats["processed"] += 1
    # Once every SHOW_EVERY frames, decode the full image and hand it over for display
    count += 1
    if count % SHOW_EVERY == 0:
    image = decoder.decode(data, reso)
    with lock:
    shown["image"] = image
    shown["boxes"] = boxes
    window = "Motion detection (ESC or Q to quit)"
    cv2.namedWindow(window, cv2.WINDOW_AUTOSIZE)
    worker = threading.Thread(target=analyze_worker)
    worker.start()
    # Start continuous transfer (on_frame is called every time a frame arrives)
    cam.setRingBufferCount(64)
    cam.beginXfer(on_frame)
    print("Detecting motion... Select the video window and press ESC or Q to exit.")
    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
    # 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"objects: {len(boxes)}", (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (0, 255, 0), 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 thread, then close the camera
    cam.endXfer()
    frames.put(None)
    worker.join()
    cam.close()
    cv2.destroyAllWindows()
    print(f"Done (received: {stats['received']}, analyzed: {stats['processed']}, "
    f"dropped: {stats['gaps']}, overflow: {stats['overflow']}).")
  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 motion_detection.py
  3. Move something

    When the video window opens, wave your hand or roll something in front of the camera. The areas that moved are surrounded by red boxes. The top-left corner shows numbers like these.

    process: 1000 fps (0.25 ms/frame) dropped: 0 overflow: 0
    objects: 1
  4. Exit

    Select the video window and press ESC or Q.

    Done (received: 8000, analyzed: 8000, dropped: 0, overflow: 0).

    If “received” and “analyzed” are the same, every frame was analyzed without skipping any.

The numbers in the top-left corner of the screen mean the following.

Display Meaning
process: 1000 fps Frames analyzed per second. Because the camera captures at 1,000 fps, a value around 1000 means every frame is being analyzed
ms/frame Time taken to analyze one frame
dropped Frames that did not arrive (dropped frames)
overflow Frames that overflowed from the queue because the analysis could not keep up
objects Number of moving objects found

1. Split the work into three roles

This program has three roles running at the same time.

Role Function / place What it does How often
Receiving on_frame Only puts the received data in the queue 1,000 times per second
Analysis analyze_worker (a separate thread) Takes out the DC components and looks for motion 1,000 times per second
Display Inside the while loop at the bottom Shows the analysis result on screen About 30 times per second

Receiving and analysis are split in the same way as in Continuous high-speed capture. The screen can only refresh a few dozen times per second, so a display image is created only once every 33 frames (about 30 fps) (SHOW_EVERY).

2. Make the analysis lighter with DC components

dc = decoder.decodeDC(data, 0, 0, blocks_x, blocks_y)

Decoding the full image (800 × 600) every time does not fit in 1 ms in Python. So the program takes only the DC components (the average brightness of each 8 × 8 pixel block) out of the compressed data. The result is a small 100 × 75 image, but that is enough to find “where something moved”. Taking them out is also very fast, so the analysis finishes in about 0.3 ms per frame. For DC components, see also SingleImage + DC component extraction.

3. Compare with the image 10 frames earlier

boxes = find_motion(dc, history[0]) # Compare with the image GAP frames ago

At 1,000 fps, there is only 1 ms between one frame and the next, and objects barely move in that time. Comparing with the previous frame gives differences that are too small to find. So the program compares with the image GAP frames earlier (10 frames = 10 ms earlier). collections.deque(maxlen=GAP) is a container that remembers only the last GAP images.

4. Find the areas that moved

diff = cv2.absdiff(dc_now, dc_before)
_, mask = cv2.threshold(diff, THRESHOLD - 1, 255, cv2.THRESH_BINARY)
mask = cv2.dilate(mask, None)
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
Step Function What it does
1 cv2.absdiff Works out the difference in brightness between the two images
2 cv2.threshold Makes places where the difference is at least THRESHOLD white (moved) and everything else black
3 cv2.dilate Thickens the white areas slightly so that neighboring white areas join up (so that one object is not found in pieces)
4 cv2.findContours Finds the outlines of the white areas
5 cv2.boundingRect Works out the rectangle around each outline. One pixel of the DC image is 8 × 8 pixels, so multiplying by 8 gives the position in the original image

Areas that are too small (smaller than MIN_BLOCKS) are ignored as noise.

5. Check that the processing keeps up in real time

Every second, the program works out how many frames it analyzed and the analysis time per frame, and shows them. If the analysis takes longer than 1 ms, data starts piling up in the queue and eventually overflow increases. When you add your own analysis, watch these numbers to check that it stays within 1 ms.


Change Example What happens
THRESHOLD = 6 10 Small changes in brightness are ignored, so noise and flickering lights are less likely to produce boxes
THRESHOLD = 6 3 Even slight movements are found
GAP = 10 2 Slow movements become harder to find, but fast movements are found in a shorter time
GAP = 10 50 Slow movements become easier to find
MIN_BLOCKS = 2 10 Small movements are ignored, and only large objects are found

Symptom Likely cause What to do
Boxes appear everywhere even though nothing is moving Flickering lights, or image noise Increase THRESHOLD. Use a battery-powered light or daylight
No boxes appear when something moves The difference in brightness is small Decrease THRESHOLD, or increase GAP. Try with something whose color differs from the background
One object is split into several boxes Parts of the object change little in brightness Increase the number of cv2.dilate / cv::dilate passes to join a wider area
process is below 1000, or overflow increases The PC cannot keep up For the C++ version, check that you built in Release. Close other applications. If you added your own analysis, check the time per frame
dropped does not stay at 0 Network settings Check jumbo packets in PC operating environment and network settings
The C++ version reports 'boundingRect': is not a member of 'cv' With OpenCV 5, geometry.hpp is not included Check that the #include <opencv2/geometry.hpp> line at the top of the program is still there

  • Recording the center of each rectangle every frame lets you draw the path of the moving object.
  • You can also keep a video of the moments before and after motion is found. That is shown in “Recording the moment of motion” in the list of applications.