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 |
Before you start
Section titled “Before you start”- Make sure Continuous high-speed capture and SingleImage + DC component extraction in the Python sample programs work. This program combines the two.
- The only libraries used are
pypucliband 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.
- Make sure OpenCV LiveView in the C++ sample programs works.
- Install OpenCV following Setting up OpenCV (C++).
- 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 |
| Something that moves | A hand, a rolling ball, a pendulum, or anything else that moves in the picture |
Try it
Section titled “Try it”-
Enter and save the program
Save the following code as
motion_detection.pyinC:\infinicam_projects\python\applications(create theapplicationsfolder if it does not exist).import collectionsimport queueimport threadingimport timeimport cv2from pypuclib import CameraFactory, PUCExceptionFRAMERATE = 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 noiseSHOW_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 and the areas that moved, for displayshown = {"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_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(xfer.data().copy())except queue.Full:stats["overflow"] += 1 # The analysis could not keep up and the queue overfloweddef 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 onecontours, _ = 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 pixelsreturn boxesdef 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 framescount = 0while True:data = frames.get()if data is None: # Signal to finishbreakstart = 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 comparingboxes = []if len(history) == GAP:boxes = find_motion(dc, history[0]) # Compare with the image GAP frames agohistory.append(dc)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["boxes"] = boxeswindow = "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 = 0last_process_time = 0.0info = ""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 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 boxes can be coloredfor 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) & 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 motion_detection.py -
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: 0objects: 1 -
Exit
Select the video window and press
ESCorQ.Done (received: 8000, analyzed: 8000, dropped: 0, overflow: 0).If “received” and “analyzed” are the same, every frame was analyzed without skipping any.
-
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 projectMotionDetection. - 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 (
MotionDetection.cpp) and replace its contents with the following code.#include <stdio.h>#include <stdlib.h>#include <algorithm>#include <atomic>#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 GAP = 10; // How many frames back to compare with (10 frames = 10 ms at 1000 fps)const int THRESHOLD = 20; // Pixels whose brightness changed by at least this much are treated as "moved"const int MIN_AREA = 400; // Motion smaller than this (in pixels) is ignored as noiseconst 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 HISTORY = 64; // Number of slots for decoded images (make it much larger than GAP)// Data shared between the threadsstruct MotionContext {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::deque<long> waiting;std::mutex queueLock;std::condition_variable queueReady;bool stopping;// Slots for decoded images (a frame goes into slot frame number % HISTORY)std::vector<cv::Mat> history;std::vector<std::atomic<long>> historyNo; // The frame number of the image in each slot// Counters (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;// The newest image and the areas that moved, for display (protected by statsLock)cv::Mat shownImage;std::vector<cv::Rect> shownBoxes;bool isUpdated;MotionContext() : historyNo(HISTORY) {}};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;}// Compare two images and return the rectangles where something movedstatic void FindMotion(const cv::Mat& now, const cv::Mat& before, std::vector<cv::Rect>& boxes) {cv::Mat diff, mask;cv::absdiff(now, before, diff);cv::threshold(diff, mask, THRESHOLD - 1, 255, cv::THRESH_BINARY);cv::morphologyEx(mask, mask, cv::MORPH_OPEN, cv::Mat()); // Remove small dots (noise)cv::dilate(mask, mask, cv::Mat(), cv::Point(-1, -1), 5); // Connect nearby white areas so that one object is found as onestd::vector<std::vector<cv::Point>> contours;cv::findContours(mask, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);for (const auto& contour : contours) {cv::Rect r = cv::boundingRect(contour);if (r.area() >= MIN_AREA) {boxes.push_back(r);}}}// 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) {MotionContext* c = (MotionContext*)pUserParam;if (!pXferData || !pXferData->pData || !c) {return;}long frameNo = -1;{std::lock_guard<std::mutex> guard(c->statsLock);c->received++;// If the sequence number skips, the skipped frames were droppedint seq = pXferData->nSequenceNo;if (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->waiting.push_back(frameNo);}c->queueReady.notify_one();}// Analysis worker (runs in a separate thread). Takes frames out of the queue one by one, decodes them, and analyzes themstatic void AnalyzeWorker(MotionContext* c) {while (true) {long frameNo;{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();}double start = NowSeconds();// Decode the full image into the slot for decoded imagescv::Mat& now = c->history[frameNo % HISTORY];PUC_DecodeDataMultiThread(now.data, 0, 0, c->width, c->height, c->lineBytes,c->slots[frameNo % SLOTS].data(), c->qVals, DECODE_THREADS);c->historyNo[frameNo % HISTORY] = frameNo;// If the image GAP frames ago has already been decoded, compare with it and look for motionstd::vector<cv::Rect> boxes;long beforeNo = frameNo - GAP;if (beforeNo >= 0 && c->historyNo[beforeNo % HISTORY] == beforeNo) {FindMotion(now, c->history[beforeNo % HISTORY], boxes);}double elapsed = NowSeconds() - start;std::lock_guard<std::mutex> guard(c->statsLock);c->processed++;c->processSeconds += elapsed;// Once every SHOW_EVERY frames, hand over the image and the result for displayif (frameNo % SHOW_EVERY == 0) {now.copyTo(c->shownImage);c->shownBoxes = boxes;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 motion detection (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 dataMotionContext 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 decoded imagesctx.slots.assign(SLOTS, std::vector<unsigned char>(xferDataSize));for (int i = 0; i < HISTORY; i++) {cv::Mat buffer((int)ctx.height, (int)ctx.lineBytes, CV_8UC1);ctx.history.push_back(buffer(cv::Rect(0, 0, (int)ctx.width, (int)ctx.height))); // An image whose rows are lineBytes bytes longctx.historyNo[i] = -1;}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.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 = "Motion detection (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("Detecting motion... 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<cv::Rect> boxes;while (true) {bool updated = false;long processed, gaps, overflow;double processSeconds;{std::lock_guard<std::mutex> guard(ctx.statsLock);if (ctx.isUpdated) {ctx.isUpdated = false;ctx.shownImage.copyTo(image);boxes = ctx.shownBoxes;updated = true;}processed = ctx.processed;gaps = ctx.gaps;overflow = ctx.overflow;processSeconds = ctx.processSeconds;}// 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 boxes can be coloredfor (const auto& r : boxes) {cv::rectangle(color, r, cv::Scalar(0, 0, 255), 2);}char objects[32];sprintf_s(objects, "objects: %zu", boxes.size());cv::putText(color, info, cv::Point(10, 25), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 255, 0), 2);cv::putText(color, objects, cv::Point(10, 50), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 255, 0), 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.When you switch to Release, the project settings (include and library) may be separate from Debug. If the build fails, check that the settings from step 3 of Setting up OpenCV (C++) are also in Release (in Release, the library name is
opencv_world500.lib, without thed). -
Build and run
Press
Ctrl+F5. 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.86 ms/frame, 2 workers) dropped: 0 overflow: 0objects: 1 -
Exit
Select the video window and press
ESCorQ. The console shows the following.Done (received: 8007, analyzed: 8007, 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 |
objects |
Number of moving objects found |
How the program works
Section titled “How the program works”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 agoAt 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.
1. Decoding the full image takes time
The C++ version decodes the full image (800 × 600) every frame and compares those, instead of using DC components. It can find small movements at the original resolution. However, when measured, the processing time per frame was as follows (Release, decoding with 6 threads).
| Processing | Per frame |
|---|---|
Decoding the full image (PUC_DecodeDataMultiThread) |
About 0.6 ms |
| Finding the areas that moved (difference, threshold, noise removal, contours) | About 0.4 ms |
| Total | About 1.0 ms |
The total is right around 1 ms, so processing one frame after another in order only just fails to keep up with 1,000 fps.
2. Process two frames at the same time
So the program has two analysis workers (threads), which take turns handling the frames as they arrive. Even if one frame takes 1 ms, two workers running at the same time can process up to about 2,000 frames per second.
| Role | Function / place | What it does |
|---|---|---|
| Receiving | ImageCallback |
Only copies the received compressed data into a slot (slots) and puts the frame number in the queue (waiting) |
| Analysis × 2 | AnalyzeWorker (WORKERS threads) |
Takes frame numbers out of the queue one by one, decodes them, and looks for motion |
| Display | Inside the while loop in main |
Draws the boxes and numbers on the image handed over once every 33 frames, and shows it |
std::vector<std::thread> workers;for (int i = 0; i < WORKERS; i++) { workers.emplace_back(AnalyzeWorker, &ctx);}std::thread creates WORKERS threads that run AnalyzeWorker. The queue is protected by a std::mutex (a lock that lets only one thread touch it at a time), and a std::condition_variable tells the analysis workers that a new frame has arrived.
3. Get the image 10 frames earlier
cv::Mat& now = c->history[frameNo % HISTORY];...long beforeNo = frameNo - GAP;if (beforeNo >= 0 && c->historyNo[beforeNo % HISTORY] == beforeNo) { FindMotion(now, c->history[beforeNo % HISTORY], boxes);}Decoded images go into slots for the last 64 frames (history), at a position determined by the frame number. Because the two workers run at the same time, the image 10 frames earlier may still be being decoded. So the program records, for each slot, which frame number it holds (historyNo), and compares only when the image 10 frames earlier is ready.
4. Find the areas that moved
cv::absdiff(now, before, diff);cv::threshold(diff, mask, THRESHOLD - 1, 255, cv::THRESH_BINARY);cv::morphologyEx(mask, mask, cv::MORPH_OPEN, cv::Mat());cv::dilate(mask, mask, cv::Mat(), cv::Point(-1, -1), 5);cv::findContours(mask, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);The idea is the same as the Python version. Pixels of the full image are easily affected by noise, so cv::morphologyEx (MORPH_OPEN) first removes small dots of 1 or 2 pixels, and then cv::dilate is applied 5 times to join nearby white areas.
Things to try
Section titled “Things to try”| 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 |
| Change | Example | What happens |
|---|---|---|
THRESHOLD = 20 |
40 |
Small changes in brightness are ignored, so noise and flickering lights are less likely to produce boxes |
GAP = 10 |
2 / 50 |
Changes the interval being compared (same as the Python version) |
MIN_AREA = 400 |
2000 |
Small movements are ignored, and only large objects are found |
WORKERS = 2 |
1 |
Frames are processed one at a time in order, and it can no longer keep up with 1,000 fps (try it and watch overflow increase) |
WORKERS = 2 |
3 |
It can keep up even with heavier analysis. Try this when your PC’s CPU has cores to spare |
Troubleshooting
Section titled “Troubleshooting”| 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 |
Ideas for going further
Section titled “Ideas for going further”- 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.
