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

Measuring the speed of a ball

This application finds the position of a white ball or light spot in every 1,000 fps image from the INFINICAM GbE-2 (every 1 ms) and keeps showing its speed on screen. It also draws the path the ball has taken (its trail) as a line.

Try it when you want to measure “speed” in science or physics experiments, such as a rolling ball, a falling ball, or the weight of a pendulum.

Python version C++ version
Image used to find the position DC components (a 100 × 75 scaled-down image) The full image (800 × 600)
Position resolution Finer than a block (8 pixels), using a brightness-weighted centroid Per pixel
Analysis time per frame (rough guide) About 0.3 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
  • Make sure the Python version of Finding moving objects works. This program uses the same mechanism (separate threads for receiving and analysis, made lighter with DC components).
  • 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
Ball Something brighter than the background. A white ping-pong ball, a white ball, a toy with an LED, and so on
Background Something darker than the ball, such as black cloth or black paper
Ruler Used when you want the speed in m/s (see “Showing the speed in m/s” below)
  1. Enter and save the program

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

    import collections
    import math
    import queue
    import threading
    import time
    import cv2
    from pypuclib import CameraFactory, PUCException
    FRAMERATE = 1000 # Frame rate [fps]
    BRIGHT = 160 # Blocks whose DC value is at least this are treated as the "ball" (DC values are roughly 64 to 191)
    MIN_BLOCKS = 2 # Bright blobs smaller than this (in blocks) are ignored as noise
    WINDOW = 10 # How many frames back to compare the position with to get the speed (10 frames = 10 ms at 1000 fps)
    MM_PER_PIXEL = 0.0 # How many mm one pixel corresponds to (find it by filming a ruler; 0 shows the speed in pixels/s)
    TRAIL = 300 # Length of the trail kept on screen (300 frames = 0.3 s)
    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, ball position, trail, and speed, for display
    shown = {"image": None, "ball": None, "trail": [], "speed": None}
    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((seq, xfer.data().copy()))
    except queue.Full:
    stats["overflow"] += 1 # The analysis could not keep up and the queue overflowed
    def find_ball(dc):
    """Find the largest bright blob in the DC-component image and return its centroid (in pixels)"""
    _, mask = cv2.threshold(dc, BRIGHT - 1, 255, cv2.THRESH_BINARY)
    contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    if not contours:
    return None
    biggest = max(contours, key=lambda c: cv2.boundingRect(c)[2] * cv2.boundingRect(c)[3])
    x, y, w, h = cv2.boundingRect(biggest)
    if w * h < MIN_BLOCKS:
    return None
    # Find the brightness-weighted centroid (brighter blocks pull the centroid more strongly)
    region = cv2.bitwise_and(dc[y:y + h, x:x + w], mask[y:y + h, x:x + w])
    m = cv2.moments(region)
    if m["m00"] == 0:
    return None
    cx = x + m["m10"] / m["m00"]
    cy = y + m["m01"] / m["m00"]
    return ((cx + 0.5) * 8, (cy + 0.5) * 8) # Convert from blocks to pixels
    def analyze_worker():
    """Take frames out of the queue one by one and find the ball's position and speed (runs in a separate thread)"""
    track = collections.deque(maxlen=WINDOW + 1) # (time [ms], x, y) for the last WINDOW + 1 frames
    trail = collections.deque(maxlen=TRAIL) # Trail for display (None where the ball was lost)
    t_ms = 0.0
    prev_seq = None
    speed = None
    count = 0
    while True:
    item = frames.get()
    if item is None: # Signal to finish
    break
    seq, data = item
    start = time.perf_counter()
    # Work out the time since the capture started [ms] from the sequence number (correct even if frames are dropped)
    if prev_seq is not None:
    t_ms += ((seq - prev_seq) & 0xFFFF) * 1000 / FRAMERATE
    prev_seq = seq
    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 searching
    ball = find_ball(dc)
    if ball is None:
    track.clear() # When the ball is lost, start the speed calculation over
    speed = None
    if trail and trail[-1] is not None:
    trail.append(None)
    else:
    track.append((t_ms, ball[0], ball[1]))
    trail.append(ball)
    if len(track) == WINDOW + 1:
    # The distance from the position WINDOW frames ago, divided by the time taken, is the speed
    t0, x0, y0 = track[0]
    distance = math.hypot(ball[0] - x0, ball[1] - y0)
    speed = distance / ((t_ms - t0) / 1000) # [pixels/s]
    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["ball"] = ball
    shown["trail"] = list(trail)
    shown["speed"] = speed
    def speed_text(speed):
    """Turn the speed into text for display"""
    if speed is None:
    return "speed: ---"
    if MM_PER_PIXEL > 0:
    return f"speed: {speed * MM_PER_PIXEL / 1000:.2f} m/s"
    return f"speed: {speed:.0f} px/s"
    window = "Ball speed (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("Measuring the ball speed... 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"]
    ball = shown["ball"]
    trail = shown["trail"]
    speed = shown["speed"]
    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 lines can be colored
    # Join the trail with lines (break the line where the ball was lost = None)
    for p, q in zip(trail, trail[1:]):
    if p is not None and q is not None:
    cv2.line(image, (int(p[0]), int(p[1])), (int(q[0]), int(q[1])), (255, 128, 0), 2)
    if ball is not None:
    cv2.circle(image, (int(ball[0]), int(ball[1])), 10, (0, 0, 255), 2)
    cv2.putText(image, info, (10, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (0, 255, 0), 2)
    cv2.putText(image, speed_text(speed), (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 255, 255), 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 ball_speed.py
  3. Move the ball

    When the video window opens, roll or drop the ball in front of the camera. The ball is surrounded by a red circle, and its path is drawn as a blue line. The top-left corner shows numbers like these.

    process: 1000 fps (0.30 ms/frame) dropped: 0 overflow: 0
    speed: 1520 px/s
  4. Exit

    Select the video window and press ESC or Q.

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

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
speed Speed of the ball. In pixels per second (px/s) when MM_PER_PIXEL is 0, in m/s once you set it. --- when the ball is not found

At first, the speed is shown as “how many pixels it moved per second (px/s)”. To get the real speed (m/s), find out how many mm one pixel corresponds to and put it in MM_PER_PIXEL.

  1. Put a ruler where the ball moves, and get it in the camera’s picture.
  2. With the program stopped, capture and save one image with SingleImage (saving as PNG) or similar, and open it in software that can open images, such as Paint.
  3. Read the positions of two marks on the ruler (for example 0 cm and 10 cm) in pixels. In Paint, the coordinates under the mouse pointer are shown at the bottom of the window.
  4. Calculate “real length ÷ number of pixels”. For example, if 100 mm is 250 pixels, 100 ÷ 250 = 0.4.
  5. Change MM_PER_PIXEL = 0.0 in the program to MM_PER_PIXEL = 0.4 and run it again. The speed is shown like speed: 0.61 m/s.

1. Find the bright blob

_, mask = cv2.threshold(dc, BRIGHT - 1, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
biggest = max(contours, key=lambda c: cv2.boundingRect(c)[2] * cv2.boundingRect(c)[3])

In the DC-component image, blocks whose brightness is at least BRIGHT are made white, and the largest of the white blobs is treated as the ball.

DC values are not the brightness of the original image (0 to 255) as it is; they are roughly “average brightness × 0.5 + 64”. So even pure black is about 64, and pure white is about 191. BRIGHT = 160 corresponds to a brightness of about 190 in the original image.

2. Find the position finely with the centroid

region = cv2.bitwise_and(dc[y:y + h, x:x + w], mask[y:y + h, x:x + w])
m = cv2.moments(region)
cx = x + m["m10"] / m["m00"]

One pixel of the DC image is 8 × 8 pixels of the original image. As it is, the position would come in steps of 8 pixels. So the program uses cv2.moments to find the brightness-weighted centroid of the blob (an average position where brighter blocks count more), which gives a position finer than a block. Finally, it multiplies by 8 to get the pixel position in the original image.

3. Work out the speed

t0, x0, y0 = track[0]
distance = math.hypot(ball[0] - x0, ball[1] - y0)
speed = distance / ((t_ms - t0) / 1000)

The program remembers the positions and times of the last WINDOW + 1 frames (11 frames), and divides the distance from the position 10 frames (10 ms) earlier by the time taken to get the speed. Comparing with the frame 1 ms earlier would make the speed jump around with tiny position errors, so it uses two positions a little further apart. The time is calculated from the sequence numbers attached by the camera, so it stays correct even if frames are dropped.

When the ball is lost, the remembered positions are cleared and the speed calculation starts over.


Change Example What happens
BRIGHT = 160 175 Only brighter things are treated as the ball. Increase it when the background is mistaken for the ball
BRIGHT = 160 140 Slightly darker balls are found too
WINDOW = 10 30 The speed display becomes steadier, but it reacts more slowly when the speed changes
TRAIL = 300 1000 A longer trail (1 second) stays on screen
MM_PER_PIXEL = 0.0 0.4 Shows the speed in m/s (see “Showing the speed in m/s” above)

Symptom Likely cause What to do
speed: --- stays even with the ball in view, and no red circle appears The ball is darker than BRIGHT Decrease BRIGHT. Make the background darker
A red circle appears somewhere other than the ball The background or the lighting is bright Increase BRIGHT. Make the background darker with black cloth or similar
The speed jumps around a lot The position is found with slight errors Increase WINDOW
The speed is slower or faster than it really is The MM_PER_PIXEL value, or the distance between the ball and the ruler, is wrong Put the ruler in the plane the ball moves in and measure again
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
dropped does not stay at 0 Network settings Check jumbo packets in PC operating environment and network settings

  • If you write the position and time to a CSV file every frame, you can graph them later in a spreadsheet. In a falling experiment, you can see the speed increase over time (gravitational acceleration).