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 |
Before you start
Section titled “Before you start”- 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.
- Make sure the C++ version of Finding moving objects works in Release. This program uses the same mechanism (two analysis workers).
- The program in the sample code bundle has Japanese comments. The code below is the same program with English comments and messages.
What you need
Section titled “What you need”| 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) |
Try it
Section titled “Try it”-
Enter and save the program
Save the following code as
ball_speed.pyinC:\infinicam_projects\python\applications(create theapplicationsfolder if it does not exist).import collectionsimport mathimport queueimport threadingimport timeimport cv2from pypuclib import CameraFactory, PUCExceptionFRAMERATE = 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 noiseWINDOW = 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 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 (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 pixelblocks_x = reso.width // 8blocks_y = reso.height // 8# Prepare the decoder and have it decode the full image with 4 threads in paralleldecoder = 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)# Countersstats = {"received": 0, "gaps": 0, "overflow": 0, "processed": 0, "process_time": 0.0}last_seq = None# The newest image, ball position, trail, and speed, for displayshown = {"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_seqstats["received"] += 1# If the sequence number skips, the skipped frames were droppedseq = xfer.sequenceNo()if last_seq is not None:stats["gaps"] += ((seq - last_seq) & 0xFFFF) - 1last_seq = seqif xfer.isDamaged():returntry:frames.put_nowait((seq, xfer.data().copy()))except queue.Full:stats["overflow"] += 1 # The analysis could not keep up and the queue overfloweddef 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 Nonebiggest = 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 Nonecx = x + m["m10"] / m["m00"]cy = y + m["m01"] / m["m00"]return ((cx + 0.5) * 8, (cy + 0.5) * 8) # Convert from blocks to pixelsdef 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 framestrail = collections.deque(maxlen=TRAIL) # Trail for display (None where the ball was lost)t_ms = 0.0prev_seq = Nonespeed = Nonecount = 0while True:item = frames.get()if item is None: # Signal to finishbreakseq, data = itemstart = 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 / FRAMERATEprev_seq = seqdc = 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 searchingball = find_ball(dc)if ball is None:track.clear() # When the ball is lost, start the speed calculation overspeed = Noneif 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 speedt0, 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() - startstats["processed"] += 1# Once every SHOW_EVERY frames, decode the full image and hand it over for displaycount += 1if count % SHOW_EVERY == 0:image = decoder.decode(data, reso)with lock:shown["image"] = imageshown["ball"] = ballshown["trail"] = list(trail)shown["speed"] = speeddef 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 = 0last_process_time = 0.0info = ""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 framenow = time.perf_counter()if now - last_time >= 1.0:n = stats["processed"] - last_processedt = stats["process_time"] - last_process_timeper_frame = t / n * 1000 if n else 0info = (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) & 0xFFif key in (27, ord("q"), ord("Q")): # ESC or Qbreakfinally:# Stop continuous transfer, finish the analysis thread, then close the cameracam.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']}).") -
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 ball_speed.py -
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: 0speed: 1520 px/s -
Exit
Select the video window and press
ESCorQ.Done (received: 8000, analyzed: 8000, dropped: 0, overflow: 0).
-
Create and set up the project
- Create a new project in the same way as steps 1 to 7 of Creating the HelloWorld Project. Save it in
C:\infinicam_projects\applicationsand name the projectBallSpeed. - Following step 3 of Setting up OpenCV (C++), add the OpenCV settings (include, libraries, and automatic DLL copy) to this project.
- Create a new project in the same way as steps 1 to 7 of Creating the HelloWorld Project. Save it in
-
Write the source code
Open the main file (
BallSpeed.cpp) and replace its contents with the following code.#include <stdio.h>#include <stdlib.h>#include <math.h>#include <algorithm>#include <condition_variable>#include <deque>#include <mutex>#include <thread>#include <vector>#include <windows.h>#include <PUCLIB.h> // PUCLIB header#include <opencv2/opencv.hpp> // OpenCV header#include <opencv2/core/utils/logger.hpp> // For setting which messages OpenCV prints#if CV_VERSION_MAJOR >= 5#include <opencv2/geometry.hpp> // In OpenCV 5, boundingRect and others moved here#endifconst UINT32 FRAMERATE = 1000; // Frame rate [fps]const int BRIGHT = 200; // Pixels at least this bright are treated as the "ball" (0 to 255)const int MIN_AREA = 50; // Bright blobs smaller than this (in pixels) are ignored as noiseconst int WINDOW = 10; // How many frames back to compare the position with to get the speed (10 frames = 10 ms at 1000 fps)const double 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)const int TRAIL = 300; // Length of the trail kept on screen (300 frames = 0.3 s)const int SHOW_EVERY = 33; // Hand over a display image once every this many frames (33 frames = about 30 fps)const int WORKERS = 2; // Number of analysis workers (threads). Two frames are processed at the same timeconst int DECODE_THREADS = 6; // Number of threads used to decode one frameconst int SLOTS = 256; // Number of slots for received compressed dataconst int RESULTS = 1024; // Number of slots for per-frame results (ball positions); make it larger than TRAIL// The result for one framestruct BallResult {long frameNo; // Which frame this result is for (-1 if empty)int seq; // The sequence number attached by the camerabool found; // Whether the ball was founddouble x; // Center of the ball [pixels]double y;};// Data shared between the threadsstruct BallContext {UINT32 width;UINT32 height;UINT32 lineBytes;unsigned short qVals[PUC_Q_COUNT];// Slots for received compressed data, and the queue of frame numbers waiting to be analyzedstd::vector<std::vector<unsigned char>> slots;std::vector<int> slotSeq;std::deque<long> waiting;std::mutex queueLock;std::condition_variable queueReady;bool stopping;// Counters and per-frame results (protected by statsLock)std::mutex statsLock;long nextFrameNo; // Number given to received frames, counting up from 0long received;long processed;long gaps;long overflow;int lastSeq;double processSeconds;std::vector<BallResult> results; // A result goes into slot frame number % RESULTSlong speedFrameNo; // The frame number the speed was calculated for (only overwritten by newer frames)double speed; // The newest speed [pixels/s] (-1 if it cannot be calculated)// The newest image, for display (protected by statsLock)cv::Mat shownImage;long shownFrameNo;bool isUpdated;};static double NowSeconds() {static LARGE_INTEGER freq = [] { LARGE_INTEGER f; QueryPerformanceFrequency(&f); return f; }();LARGE_INTEGER t;QueryPerformanceCounter(&t);return (double)t.QuadPart / freq.QuadPart;}// Find the largest bright blob in the image and work out its centroidstatic bool FindBall(const cv::Mat& image, double& x, double& y) {cv::Mat mask;cv::threshold(image, mask, BRIGHT - 1, 255, cv::THRESH_BINARY);std::vector<std::vector<cv::Point>> contours;cv::findContours(mask, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);if (contours.empty()) {return false;}// Choose the largest blobint best = -1;int bestArea = 0;for (int i = 0; i < (int)contours.size(); i++) {int area = cv::boundingRect(contours[i]).area();if (area > bestArea) {bestArea = area;best = i;}}if (bestArea < MIN_AREA) {return false;}// Find the centroid of the bright pixels inside the rectangle around the blobcv::Rect r = cv::boundingRect(contours[best]);cv::Moments m = cv::moments(mask(r), true);if (m.m00 == 0) {return false;}x = r.x + m.m10 / m.m00;y = r.y + m.m01 / m.m00;return true;}// Callback function called automatically from inside the SDK when an image arrives.// Do nothing heavy here: just copy the compressed data into a slot and put its number in the queuevoid WINAPI ImageCallback(PPUC_XFER_DATA_INFO pXferData, void* pUserParam) {BallContext* c = (BallContext*)pUserParam;if (!pXferData || !pXferData->pData || !c) {return;}int seq = pXferData->nSequenceNo;long frameNo = -1;{std::lock_guard<std::mutex> guard(c->statsLock);c->received++;// If the sequence number skips, the skipped frames were droppedif (c->lastSeq >= 0) {c->gaps += ((seq - c->lastSeq) & 0xFFFF) - 1;}c->lastSeq = seq;if (pXferData->isDamaged) {return; // Skip data that arrived incomplete}frameNo = c->nextFrameNo++;}{std::lock_guard<std::mutex> guard(c->queueLock);if ((int)c->waiting.size() >= SLOTS - WORKERS) {std::lock_guard<std::mutex> statsGuard(c->statsLock);c->overflow++; // The analysis could not keep up and the slots are fullreturn;}std::vector<unsigned char>& slot = c->slots[frameNo % SLOTS];memcpy(slot.data(), pXferData->pData, std::min((size_t)pXferData->nDataSize, slot.size()));c->slotSeq[frameNo % SLOTS] = seq;c->waiting.push_back(frameNo);}c->queueReady.notify_one();}// Analysis worker (runs in a separate thread). Takes frames out of the queue one by one and finds the ball's position and speedstatic void AnalyzeWorker(BallContext* c) {cv::Mat buffer((int)c->height, (int)c->lineBytes, CV_8UC1);cv::Mat image = buffer(cv::Rect(0, 0, (int)c->width, (int)c->height)); // Decode target used only by this workerwhile (true) {long frameNo;int seq;{std::unique_lock<std::mutex> guard(c->queueLock);c->queueReady.wait(guard, [c] { return c->stopping || !c->waiting.empty(); });if (c->waiting.empty()) {return; // Signal to finish}frameNo = c->waiting.front();c->waiting.pop_front();seq = c->slotSeq[frameNo % SLOTS];}double start = NowSeconds();// Decode the full image and look for the ballPUC_DecodeDataMultiThread(image.data, 0, 0, c->width, c->height, c->lineBytes,c->slots[frameNo % SLOTS].data(), c->qVals, DECODE_THREADS);BallResult result = { frameNo, seq, false, 0.0, 0.0 };result.found = FindBall(image, result.x, result.y);double elapsed = NowSeconds() - start;std::lock_guard<std::mutex> guard(c->statsLock);c->processed++;c->processSeconds += elapsed;c->results[frameNo % RESULTS] = result;// The two workers run at the same time, so frames can finish out of order.// So look up the result WINDOW frames earlier by frame number to work out the speedlong beforeNo = frameNo - WINDOW;if (result.found && beforeNo >= 0 && frameNo > c->speedFrameNo) {const BallResult& before = c->results[beforeNo % RESULTS];if (before.frameNo == beforeNo && before.found) {// Work out the time taken from the difference in sequence numbers (correct even if frames are dropped)double seconds = ((result.seq - before.seq) & 0xFFFF) / (double)FRAMERATE;double distance = hypot(result.x - before.x, result.y - before.y);c->speed = distance / seconds; // [pixels/s]c->speedFrameNo = frameNo;}}if (!result.found && frameNo > c->speedFrameNo) {c->speed = -1.0; // When the ball is lost, the speed cannot be calculatedc->speedFrameNo = frameNo;}// Once every SHOW_EVERY frames, hand over the image for displayif (frameNo % SHOW_EVERY == 0) {image.copyTo(c->shownImage);c->shownFrameNo = frameNo;c->isUpdated = true;}}}int main() {// Stop the notices (INFO) that OpenCV prints, and show only warnings and errorscv::utils::logging::setLogLevel(cv::utils::logging::LOG_LEVEL_WARNING);printf("INFINICAM GbE-2 ball speed measurement (C++) starting...\n");// 1. Initialize the SDKPUCRESULT ret = PUC_Initialize();if (ret != PUC_SUCCEEDED) {printf("Error: failed to initialize the SDK. ErrorCode: %d\n", ret);return EXIT_FAILURE;}// 2. Search the network for GbE-2 camerasPUC_DETECT_FILTER filter = { 0 };filter.nDeviceTypeFlags = PUC_DETECT_TARGET_GBE2;PUC_DETECT_INFO detectInfo = { 0 };ret = PUC_DetectDevice2(&filter, &detectInfo);if (ret != PUC_SUCCEEDED || detectInfo.nDeviceCount == 0) {printf("Error: no GbE-2 camera was found. ErrorCode: %d\n", ret);return EXIT_FAILURE;}// 3. Open the first camera foundPUC_HANDLE hDevice = NULL;ret = PUC_OpenDevice2(0, &hDevice);if (ret != PUC_SUCCEEDED) {printf("Error: could not open the camera. ErrorCode: %d\n", ret);return EXIT_FAILURE;}// 4. Set the frame rate and shutter speed (set here because the camera may still have the settings from its last use)ret = PUC_SetFramerateShutter(hDevice, FRAMERATE, FRAMERATE);if (ret != PUC_SUCCEEDED) {printf("Error: failed to set the frame rate. ErrorCode: %d\n", ret);PUC_CloseDevice(hDevice);return EXIT_FAILURE;}// 5. Get the resolution, the quantization table, and the size of one frame of compressed dataBallContext ctx;PUC_GetResolution(hDevice, &ctx.width, &ctx.height);PUC_GetQuantization2(hDevice, ctx.qVals);UINT32 xferDataSize = 0;PUC_GetXferDataSize(hDevice, &xferDataSize);ctx.lineBytes = (ctx.width + 3) & ~3; // Align to a 4-byte boundaryprintf("Capture settings: %u x %u pixels, %u fps\n", ctx.width, ctx.height, FRAMERATE);// 6. Prepare the slots for compressed data and for resultsctx.slots.assign(SLOTS, std::vector<unsigned char>(xferDataSize));ctx.slotSeq.assign(SLOTS, 0);ctx.results.assign(RESULTS, BallResult{ -1, 0, false, 0.0, 0.0 });ctx.stopping = false;ctx.nextFrameNo = 0;ctx.received = 0;ctx.processed = 0;ctx.gaps = 0;ctx.overflow = 0;ctx.lastSeq = -1;ctx.processSeconds = 0.0;ctx.speedFrameNo = -1;ctx.speed = -1.0;ctx.shownFrameNo = -1;ctx.isUpdated = false;// 7. Start the analysis workers (threads)std::vector<std::thread> workers;for (int i = 0; i < WORKERS; i++) {workers.emplace_back(AnalyzeWorker, &ctx);}const char* windowName = "Ball speed (ESC or Q to quit)";cv::namedWindow(windowName, cv::WINDOW_AUTOSIZE);// 8. Start continuous transferPUC_SetRingBufferCount(hDevice, 64);ret = PUC_BeginXferData(hDevice, ImageCallback, &ctx);if (ret != PUC_SUCCEEDED) {printf("Error: failed to start continuous transfer. ErrorCode: %d\n", ret);PUC_CloseDevice(hDevice);return EXIT_FAILURE;}printf("Measuring the ball speed... Select the video window and press ESC or Q to exit.\n");// 9. Main loop: show the results and watch for key pressesdouble lastTime = NowSeconds();long lastProcessed = 0;double lastProcessSeconds = 0.0;char info[160] = "";cv::Mat image;std::vector<BallResult> trail;while (true) {bool updated = false;long processed, gaps, overflow;double processSeconds, speed;{std::lock_guard<std::mutex> guard(ctx.statsLock);if (ctx.isUpdated) {ctx.isUpdated = false;ctx.shownImage.copyTo(image);updated = true;// Collect the positions of the last TRAIL frames up to the displayed image (the trail)trail.clear();for (long n = ctx.shownFrameNo - TRAIL + 1; n <= ctx.shownFrameNo; n++) {if (n < 0) {continue;}const BallResult& r = ctx.results[n % RESULTS];trail.push_back(r.frameNo == n ? r : BallResult{ n, 0, false, 0.0, 0.0 });}}processed = ctx.processed;gaps = ctx.gaps;overflow = ctx.overflow;processSeconds = ctx.processSeconds;speed = ctx.speed;}// Every second, work out how many frames were analyzed in the last second and the time per framedouble now = NowSeconds();if (now - lastTime >= 1.0) {long n = processed - lastProcessed;double perFrame = n > 0 ? (processSeconds - lastProcessSeconds) / n * 1000.0 : 0.0;sprintf_s(info, "process: %.0f fps (%.2f ms/frame, %d workers) dropped: %ld overflow: %ld",n / (now - lastTime), perFrame, WORKERS, gaps, overflow);lastTime = now;lastProcessed = processed;lastProcessSeconds = processSeconds;}if (updated) {cv::Mat color;cv::cvtColor(image, color, cv::COLOR_GRAY2BGR); // Convert to color so the lines can be colored// Join the trail with lines (break the line at frames where the ball was lost)for (size_t i = 1; i < trail.size(); i++) {if (trail[i - 1].found && trail[i].found) {cv::line(color, cv::Point((int)trail[i - 1].x, (int)trail[i - 1].y),cv::Point((int)trail[i].x, (int)trail[i].y), cv::Scalar(255, 128, 0), 2);}}if (!trail.empty() && trail.back().found) {cv::circle(color, cv::Point((int)trail.back().x, (int)trail.back().y), 10, cv::Scalar(0, 0, 255), 2);}char speedText[64];if (speed < 0) {sprintf_s(speedText, "speed: ---");}else if (MM_PER_PIXEL > 0) {sprintf_s(speedText, "speed: %.2f m/s", speed * MM_PER_PIXEL / 1000.0);}else {sprintf_s(speedText, "speed: %.0f px/s", speed);}cv::putText(color, info, cv::Point(10, 25), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 255, 0), 2);cv::putText(color, speedText, cv::Point(10, 60), cv::FONT_HERSHEY_SIMPLEX, 1.0, cv::Scalar(0, 255, 255), 2);cv::imshow(windowName, color);}int key = cv::waitKey(1);if (key == 27 || key == 'q' || key == 'Q') { // ESC or Qbreak;}}// 10. Clean up: stop continuous transfer, finish the analysis workers, then close the cameraPUC_EndXferData(hDevice);{std::lock_guard<std::mutex> guard(ctx.queueLock);ctx.stopping = true;}ctx.queueReady.notify_all();for (auto& worker : workers) {worker.join();}cv::destroyAllWindows();printf("Done (received: %ld, analyzed: %ld, dropped: %ld, overflow: %ld).\n",ctx.received, ctx.processed, ctx.gaps, ctx.overflow);PUC_CloseDevice(hDevice);return EXIT_SUCCESS;} -
Set the configuration to “Release”
In the toolbar at the top of the window, switch the configuration from
DebugtoRelease. -
Build and run
Press
Ctrl+F5. 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.90 ms/frame, 2 workers) dropped: 0 overflow: 0speed: 1520 px/s -
Exit
Select the video window and press
ESCorQ. The console shows the following.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 |
Showing the speed in m/s
Section titled “Showing the speed in m/s”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.
- Put a ruler where the ball moves, and get it in the camera’s picture.
- 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.
- 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.
- Calculate “real length ÷ number of pixels”. For example, if 100 mm is 250 pixels, 100 ÷ 250 = 0.4.
- Change
MM_PER_PIXEL = 0.0in the program toMM_PER_PIXEL = 0.4and run it again. The speed is shown likespeed: 0.61 m/s.
How the program works
Section titled “How the program works”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.
1. Find the bright blob in the full image
cv::threshold(image, mask, BRIGHT - 1, 255, cv::THRESH_BINARY);cv::findContours(mask, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);The idea is the same as the Python version. The C++ version uses the full image (800 × 600), so BRIGHT is given as the brightness of the original image (0 to 255). The centroid of the white pixels in the largest blob, found with cv::moments, is used as the ball’s position.
2. Work out the speed with two workers, even when the order changes
As in Finding moving objects, there are two analysis workers that process two frames at the same time. However, the speed is worked out from the difference with “the position 10 frames earlier”, so the order of the frames matters. With two workers running at the same time, a frame that arrived later may finish first.
c->results[frameNo % RESULTS] = result;
long beforeNo = frameNo - WINDOW;const BallResult& before = c->results[beforeNo % RESULTS];if (before.frameNo == beforeNo && before.found) { ...}So the result of each frame (its position and sequence number) is put in a slot determined by the frame number. When frame k has been analyzed, the program checks that the result for frame k - 10 is already there before calculating the speed. Because it looks results up by number, the pairs are correct even when frames finish out of order.
Also, so that the result of an older frame does not overwrite a newer speed, the speed is only updated for frames newer than the one it was last calculated for (speedFrameNo).
3. Draw the trail
The display role (inside the while loop in main) collects the results of the last 300 frames, counting back from the number of the image being shown, and joins the positions where the ball was found with lines.
Things to try
Section titled “Things to try”| 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) |
| Change | Example | What happens |
|---|---|---|
BRIGHT = 200 |
230 |
Only brighter things are treated as the ball. Increase it when the background is mistaken for the ball |
MIN_AREA = 50 |
200 |
Small bright spots are ignored, and only large balls are found |
WINDOW = 10 |
30 |
The speed display becomes steadier, but it reacts more slowly when the speed changes |
MM_PER_PIXEL = 0.0 |
0.4 |
Shows the speed in m/s (see “Showing the speed in m/s” above) |
Troubleshooting
Section titled “Troubleshooting”| 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 |
Ideas for going further
Section titled “Ideas for going further”- 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).
