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

Measuring rotation speed

Put a white mark on a fan blade or a motor shaft, and watch the spot the mark passes with the INFINICAM GbE-2. While capturing at 1,000 fps, the program counts each time the mark passes and keeps showing the revolutions per minute (rpm) on screen, like a meter.

Because it checks for the mark every 1 ms, it can count every pass without missing any, even for things that spin fast.

Python version C++ version
Image used for analysis Decodes only the watched area (16 x 16) Decodes only the watched area (16 x 16)
Analysis time per frame (guide) About 0.1 ms About 0.01 ms
Analysis workers (threads) 1 1 (to count frames in the order they arrive)
  • Make sure the Python version of Finding moving objects works.
  • Looking at how SingleImage + ROI decoding decodes only part of an image will also make this program easier to follow.
  • 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 spins A fan, a small motor, a bicycle wheel, and so on
Mark A white sticker or white tape. Put it on only one spot of the spinning thing (on a fan with dark blades, put it on the tip of one blade)
  1. Enter and save the program

    Save the following code as rotation_speed.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]
    ROI_X = 392 # X of the top-left corner of the area the mark passes (the watched area), a multiple of 8
    ROI_Y = 296 # Y of the top-left corner of the watched area (a multiple of 8)
    ROI_W = 16 # Width of the watched area (a multiple of 8)
    ROI_H = 16 # Height of the watched area (a multiple of 8)
    HIGH = 150 # When the brightness of the watched area reaches this, "the mark has arrived" (0-255)
    LOW = 100 # When the brightness falls back to this, "the mark has passed" (0-255)
    MARKS = 1 # How many times a mark passes per revolution (3 if you mark each of 3 fan blades)
    AVERAGE = 5 # How many intervals to average when calculating the rotation speed
    TIMEOUT_MS = 2000 # If no mark arrives for longer than this, treat it as stopped [ms]
    SHOW_EVERY = 33 # Make an image for display 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()
    # Prepare the decoder and have it decode full frames 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.decode(data, ROI_X, ROI_Y, ROI_W, ROI_H)
    # 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
    # For display: the newest image, brightness, rotation speed, and number of passes
    shown = {"image": None, "level": 0.0, "rpm": 0.0, "passes": 0, "above": False}
    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 # Analysis could not keep up and the queue overflowed
    def analyze_worker():
    """Takes frames out of the queue one by one, checks whether the mark passed, and calculates the rotation speed (runs in a separate thread)"""
    intervals = collections.deque(maxlen=AVERAGE) # Intervals between passes of the mark [ms]
    t_ms = 0.0
    prev_seq = None
    above = False # Whether the mark is in the watched area right now
    last_pass = None # Time the mark last arrived [ms]
    passes = 0
    rpm = 0.0
    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 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
    # Decode only the watched area and find its average brightness
    roi = decoder.decode(data, ROI_X, ROI_Y, ROI_W, ROI_H)
    level = float(roi.mean())
    # Above HIGH means "the mark has arrived", below LOW means "it has passed"
    # (using two separate values keeps one pass from being counted many times when the brightness wobbles near HIGH)
    if not above and level >= HIGH:
    above = True
    passes += 1
    if last_pass is not None:
    intervals.append(t_ms - last_pass)
    last_pass = t_ms
    elif above and level <= LOW:
    above = False
    # Calculate revolutions per minute from the average interval between passes
    if last_pass is None or t_ms - last_pass > TIMEOUT_MS:
    rpm = 0.0
    intervals.clear()
    elif intervals:
    average_ms = sum(intervals) / len(intervals)
    rpm = 60000 / (average_ms * MARKS)
    stats["process_time"] += time.perf_counter() - start
    stats["processed"] += 1
    # Only once every SHOW_EVERY frames, decode the full frame and hand it over for display
    count += 1
    if count % SHOW_EVERY == 0:
    image = decoder.decode(data, reso)
    with lock:
    shown["image"] = image
    shown["level"] = level
    shown["rpm"] = rpm
    shown["passes"] = passes
    shown["above"] = above
    window = "Rotation 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 rotation 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"]
    level = shown["level"]
    rpm = shown["rpm"]
    passes = shown["passes"]
    above = shown["above"]
    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 box can be colored
    # Show the watched area with a box (green while the mark is in it, red otherwise)
    color = (0, 255, 0) if above else (0, 0, 255)
    cv2.rectangle(image, (ROI_X, ROI_Y), (ROI_X + ROI_W, ROI_Y + ROI_H), color, 2)
    cv2.putText(image, info, (10, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (0, 255, 0), 2)
    cv2.putText(image, f"{rpm:.0f} rpm", (10, 75), cv2.FONT_HERSHEY_SIMPLEX, 1.6, (0, 255, 255), 3)
    cv2.putText(image, f"level: {level:.0f} (HIGH {HIGH} / LOW {LOW}) passes: {passes}",
    (10, 105), 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, let the analysis thread finish, 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 rotation_speed.py
  3. Line up the watched spot

    A small red box appears in the middle of the video window. This is the watched area. Move the spinning thing and point the camera so that the mark passes over this box.

    To move the box, change ROI_X and ROI_Y in the program (both must be multiples of 8).

  4. Spin it

    When you spin it, the box turns green each time the mark passes over it, and the rotation speed is shown in large numbers.

    process: 1000 fps (0.10 ms/frame) dropped: 0 overflow: 0
    1200 rpm
    level: 85 (HIGH 150 / LOW 100) passes: 57
  5. Exit

    Select the video window and press ESC or Q.

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

The numbers on the screen mean the following.

Display Meaning
process: 1000 fps Number of frames analyzed in one second. Since capture is at 1,000 fps, around 1000 means every frame is being analyzed
ms/frame Time taken to analyze one frame
dropped Number of frames that did not arrive (dropped frames)
overflow Number of frames that overflowed the queue because analysis could not keep up
rpm Revolutions per minute. It becomes 0 if the mark does not come for 2 seconds or more
level Current brightness of the watched area (0-255). It goes up when the mark comes
passes Number of times the mark has passed so far

1. Decode only the watched area

roi = decoder.decode(data, ROI_X, ROI_Y, ROI_W, ROI_H)
level = float(roi.mean())

To find out whether the mark passed, it is enough to know the brightness of the small spot the mark passes. So instead of the full frame, the program decodes only the watched area (16 x 16 pixels) (ROI decoding). This is only about 1/2,000 of the pixels, so even in Python each frame takes only about 0.1 ms. The position and size must all be multiples of 8.

2. Count one pass as one with two thresholds

if not above and level >= HIGH:
above = True
passes += 1
...
elif above and level <= LOW:
above = False

When the brightness goes above HIGH (150), the program counts one pass (“the mark has arrived”); when it goes below LOW (100), it treats the mark as having passed. With only one threshold, a small wobble in brightness near the threshold would count one pass many times. Leaving a “neither” band between the two values prevents this (this is called hysteresis).

3. Calculate the rotation speed from the intervals between passes

average_ms = sum(intervals) / len(intervals)
rpm = 60000 / (average_ms * MARKS)

The program remembers the time intervals (ms) between the last AVERAGE (5) passes of the mark, and calculates the rotation speed from their average. If the mark passes once per revolution, dividing one minute (60,000 ms) by the time of one revolution gives the revolutions per minute. The times are calculated from the sequence numbers the camera attaches, so they are accurate to 1 ms.

4. The limit for things that spin fast

At 1,000 fps, one frame is captured every 1 ms, so at least one frame must be captured while the mark is passing over the watched area. Depending on the size of the mark and the rotation speed, the mark may pass in less than 1 ms and be missed. In that case, make the mark bigger, or make the resolution smaller to raise the frame rate (see Changing capture settings + SingleImage).


Change Example What happens
ROI_X = 392, ROI_Y = 296 ROI_X = 600, ROI_Y = 200 The watched spot moves (give multiples of 8)
ROI_W = 16, ROI_H = 16 ROI_W = 32, ROI_H = 32 The watched area gets bigger. When the mark is small, making the area smaller than the mark makes it easier to detect
HIGH = 150, LOW = 100 HIGH = 180, LOW = 80 A wider gap makes miscounts from brightness wobble less likely. Watch the level display and choose values between the brightness with the mark and without it
MARKS = 1 3 Use 3 when you put a mark on each of 3 blades
AVERAGE = 5 20 The rotation speed display becomes steadier, but responds more slowly when the rotation changes

Symptom Likely cause What to do
passes does not go up when it spins The mark is not passing over the box, or level does not reach HIGH when the mark comes Adjust the camera direction or ROI_X and ROI_Y while watching the level display. Lower HIGH
passes goes up while it is stopped, or the rotation speed is too high Counting is triggered by flickering lights or bright things other than the mark Widen the gap between HIGH and LOW. Change the background or direction so that everything except the mark is dark
The rotation speed is 2 or 3 times the real one Something passes several times per revolution (for example, the blades have many white parts) Make sure nothing but the mark goes above HIGH when passing the box. If you put on several marks, set MARKS to match
The rotation speed is lower than the real one at high speed The mark passes in less than 1 ms and is missed Make the mark bigger. Make the watched area smaller than the mark
dropped does not stay at 0 Network settings Check jumbo packets in PC operating environment and network settings

  • If you write the time of each pass to a CSV file, you can graph later how the rotation speeds up or slows down. For example, you can look at how a motor gets up to a steady speed after it is switched on.
  • With two watched areas, measuring the time difference between the marks passing each one lets you measure the offset (phase) between two rotations.