Recording the moment of motion
The INFINICAM GbE-2 keeps watching at 1,000 fps. When it detects motion in the picture, it saves the 1 second before the detection and the 1 second after it as an MP4 file you can play in slow motion.
You can keep moments that happen without warning (something falling, something colliding, an insect flying past, and so on) without missing them. Because the moments before the detection are saved too, you can look back in slow motion not only at “what happened” but also at “how it came to happen”.
How it works: the same idea as a dashcam
Section titled “How it works: the same idea as a dashcam”A dashcam always holds the last few tens of seconds, and when there is a collision, it keeps only the moments before and after it in a file. This program works the same way.
Always: keep the last 1 second of compressed data, dropping the oldest (a ring buffer) | motion detectedRecording: add the "1 second after" that is still arriving to the "1 second before" already held | completeSaving: write the 2 seconds (2,000 frames) to an MP4. Watching does not stop meanwhile| State | Shown on screen | What it is doing |
|---|---|---|
| Watching | WATCHING (green) |
Keeps holding the last 1 second while looking for motion in every frame |
| Recording | RECORDING (red) |
Motion was detected, so it is collecting the 1 second after it |
| Saving | SAVING (orange) |
Writing the collected 2 seconds to an MP4. Receiving and analysis continue |
When saving is finished, it goes back to watching. So that one event is not saved again and again, it does not accept the next trigger for 3 seconds after a save (COOLDOWN).
| Python version | C++ version | |
|---|---|---|
| Motion detection | DC components (100 × 75), every frame | DC components (100 × 75), every frame |
| Amount held (approximate) | The last 1,000 frames (about 120 MB) | The last 3,000 frames (about 360 MB: the frames before and after, plus a margin for the time it takes to prepare a save) |
| Saving | In a separate thread, at the same time as analysis | In a separate thread, at the same time as analysis |
Before you start
Section titled “Before you start”- Make sure the Python versions of Finding moving objects and Saving a slow-motion MP4 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 the C++ version of Finding moving objects works.
- Install OpenCV following Setting up OpenCV (C++).
- The project 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 | Something that moves in an instant, such as an object you drop or a rolling ball |
| Memory | At least 1 GB of free memory is a good idea (used for the frames held and for preparing a save) |
Try it
Section titled “Try it”-
Enter and save the program
Save the following code as
event_recorder.pyinC:\infinicam_projects\python\applications(create theapplicationsfolder if it does not exist).import collectionsimport queueimport threadingimport timefrom datetime import datetimeimport cv2from pypuclib import CameraFactory, PUCExceptionFRAMERATE = 1000 # Frame rate [fps]PRE_SECONDS = 1.0 # Time to keep before the trigger [s]POST_SECONDS = 1.0 # Time to keep after the trigger [s]PLAY_FPS = 30 # Playback speed of the MP4 [fps] (1000 / 30 = about 33x slow motion)COOLDOWN = 3.0 # Time after a save before the next trigger is accepted [s]GAP = 10 # Compare with the image this many frames earlier (10 frames = 10 ms at 1000 fps)THRESHOLD = 6 # Treat blocks whose brightness changed by at least this much as "moved"MIN_BLOCKS = 2 # Ignore smaller movements (number of blocks) as noiseSHOW_EVERY = 33 # Make an image for display once every this many frames (33 frames = about 30 fps)pre_frames = int(FRAMERATE * PRE_SECONDS)post_frames = int(FRAMERATE * POST_SECONDS)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 a DC component image, each 8 x 8 pixel block becomes 1 pixelblocks_x = reso.width // 8blocks_y = reso.height // 8# Prepare separate decoders for analysis and for saving (two threads decode at the same time)decoder = cam.decoder()decoder.setNumDecodeThread(4)save_decoder = cam.decoder()save_decoder.setNumDecodeThread(2)# Warm up by decoding one frame first (the first decode takes time to set up, which would drop frames)data = cam.grab()decoder.decode(data)decoder.decodeDC(data, 0, 0, blocks_x, blocks_y)save_decoder.decode(data)# Queue that hands received data over to the analysis side (up to 1000 frames = 1 second)frames = queue.Queue(maxsize=1000)# (sequence number, compressed data) for the last PRE_SECONDS. The oldest are dropped automatically (ring buffer)ring = collections.deque(maxlen=pre_frames)# Current state: WATCHING -> RECORDING (collecting after the trigger) -> SAVING -> WATCHINGstate = {"mode": "WATCHING", "pre": None, "post": [], "trigger_seq": None, "cooldown_until": 0.0, "saved": 0}lock = threading.Lock()# Queue that hands (list of frames, trigger sequence number) to the saving sidesave_jobs = queue.Queue()# Countersstats = {"received": 0, "gaps": 0, "overflow": 0, "processed": 0, "process_time": 0.0}last_seq = None# The newest image and the moving areas, for displayshown = {"image": None, "boxes": []}def on_frame(xfer):"""Called every time a frame arrives. Only keeps the compressed data and puts it in the analysis 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():returndata = xfer.data().copy()with lock:ring.append((seq, data)) # Always keep the last PRE_SECONDSif state["mode"] == "RECORDING":# Collect POST_SECONDS after the triggerstate["post"].append((seq, data))if len(state["post"]) >= post_frames:save_jobs.put((state["pre"] + state["post"], state["trigger_seq"]))state["mode"] = "SAVING"state["pre"] = Nonestate["post"] = []try:frames.put_nowait((seq, data))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) # Join neighboring blocks so 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 trigger(seq):"""Called when motion is found. If watching, take the frames before the trigger and start recording"""with lock:if state["mode"] != "WATCHING" or time.perf_counter() < state["cooldown_until"]:returnif len(ring) < pre_frames:return # Right after starting, the frames before the trigger have not been collected yet, so waitstate["pre"] = list(ring) # Take the last PRE_SECONDS up to this pointstate["post"] = []state["trigger_seq"] = seqstate["mode"] = "RECORDING"print("Motion detected. Recording before and after...")def analyze_worker():"""Takes frames out of the queue one at a time and looks for motion (runs in a separate thread)"""history = collections.deque(maxlen=GAP) # DC component images of the last GAP framescount = 0while True:item = frames.get()if item is None: # Signal to finishbreakseq, data = itemstart = time.perf_counter()dc = decoder.decodeDC(data, 0, 0, blocks_x, blocks_y)if dc.ndim == 3:dc = cv2.cvtColor(dc, cv2.COLOR_BGR2GRAY) # For a color camera, convert to grayscale before comparingboxes = []if len(history) == GAP:boxes = find_motion(dc, history[0]) # Compare with the image GAP frames earlierhistory.append(dc)if boxes:trigger(seq)stats["process_time"] += time.perf_counter() - startstats["processed"] += 1# Only once every SHOW_EVERY frames, decode the whole image and pass it on for displaycount += 1if count % SHOW_EVERY == 0:image = decoder.decode(data, reso)with lock:shown["image"] = imageshown["boxes"] = boxesdef save_mp4(clip, trigger_seq):"""Decode the collected compressed data one frame at a time and write it to an MP4 file"""filename = datetime.now().strftime("event_%Y%m%d_%H%M%S.mp4")fourcc = cv2.VideoWriter_fourcc(*"mp4v")writer = cv2.VideoWriter(filename, fourcc, PLAY_FPS, (reso.width, reso.height))if not writer.isOpened():print("Error: could not create the MP4 file.")returnfor seq, data in clip:image = save_decoder.decode(data, reso)if image.ndim == 2:image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR) # Write the MP4 in color# Time from the trigger frame (negative before, positive after). The sequence number wraps from 65535 to 0offset = ((seq - trigger_seq + 32768) & 0xFFFF) - 32768t_ms = offset * 1000 / FRAMERATEcv2.putText(image, f"{t_ms:+8.1f} ms", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2)if offset == 0:# Make the trigger frame stand out with a red border and textcv2.rectangle(image, (0, 0), (reso.width - 1, reso.height - 1), (0, 0, 255), 8)cv2.putText(image, "TRIGGER", (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)writer.write(image)writer.release()print(f"Saved: {filename} ({len(clip)} frames, plays for {len(clip) / PLAY_FPS:.0f} seconds)")def save_worker():"""The saving side (runs in a separate thread). Receiving and analysis keep running while saving"""while True:job = save_jobs.get()if job is None: # Signal to finishbreakclip, trigger_seq = jobsave_mp4(clip, trigger_seq)with lock:state["mode"] = "WATCHING"state["cooldown_until"] = time.perf_counter() + COOLDOWNstate["saved"] += 1window = "Event recorder (ESC or Q to quit)"cv2.namedWindow(window, cv2.WINDOW_AUTOSIZE)worker = threading.Thread(target=analyze_worker)saver = threading.Thread(target=save_worker)worker.start()saver.start()# Start continuous transfer (on_frame is called every time a frame arrives)cam.setRingBufferCount(64)cam.beginXfer(on_frame)print("Watching... When motion is detected, the moments before and after it are saved as an MP4. Select the video window and press ESC or Q to exit.")colors = {"WATCHING": (0, 255, 0), "RECORDING": (0, 0, 255), "SAVING": (0, 200, 255)}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"] = Nonemode = state["mode"]saved = state["saved"]# 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"{mode} saved: {saved}", (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.55, colors[mode], 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 and saving sides, then close the camera# (anything being saved is written to the end)cam.endXfer()frames.put(None)worker.join()save_jobs.put(None)saver.join()cam.close()cv2.destroyAllWindows()print(f"Done (received: {stats['received']}, analyzed: {stats['processed']}, "f"dropped: {stats['gaps']}, overflow: {stats['overflow']}, saved: {state['saved']}).") -
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 event_recorder.py -
Make something happen
When the video window opens and
WATCHINGappears in the top-left corner, it is watching. Drop something in front of the camera, or move your hand quickly. The display changes toRECORDINGand thenSAVING, and after a while the console shows the following.Motion detected. Recording before and after...Saved: event_20261023_101530.mp4 (2000 frames, plays for 67 seconds)Double-click the
event_(date and time).mp4file created inC:\infinicam_projects\python\applicationsto play it in slow motion. The number in the top-left corner is the time from the trigger frame (negative before, positive after). The trigger frame is marked with a red border and the textTRIGGER. -
Exit
Select the video window and press
ESCorQ. If something is being saved, the program exits after it finishes writing.
-
Create and set up the project
- Create a new project the same way as steps 1–7 of Creating the HelloWorld project. Save it in
C:\infinicam_projects\applicationsand name the projectEventRecorder. - Following step 3 of Setting up OpenCV (C++), add the OpenCV settings (include, library, and automatic DLL copy) to this project.
- Create a new project the same way as steps 1–7 of Creating the HelloWorld project. Save it in
-
Also copy the video-writing component (Post-Build Event)
In the project properties, under “Build Events” > “Post-Build Event”, add the following as the third line of “Command Line”.
xcopy /Y /D "C:\opencv\build\x64\vc16\bin\opencv_videoio_ffmpeg*.dll" "$(OutDir)" -
Write the source code
Open the main file (
EventRecorder.cpp) and replace it with the following code.#include <stdio.h>#include <stdlib.h>#include <time.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 PRE_FRAMES = 1000; // Frames to keep before the trigger (1 second at 1000 fps)const int POST_FRAMES = 1000; // Frames to keep after the trigger (1 second at 1000 fps)const double PLAY_FPS = 30.0; // Playback speed of the MP4 [fps] (1000 / 30 = about 33x slow motion)const double COOLDOWN = 3.0; // Time after a save before the next trigger is accepted [s]const int GAP = 10; // Compare with the image this many frames earlier (10 frames = 10 ms at 1000 fps)const int THRESHOLD = 6; // Treat blocks whose brightness changed by at least this much as "moved" (DC values)const int MIN_BLOCKS = 2; // Ignore smaller movements (number of blocks) as noiseconst int SHOW_EVERY = 33; // Make an image for display once every this many frames (33 frames = about 30 fps)// Number of slots for received compressed data: the frames before and after the trigger,// plus a margin for the frames that arrive while saving is being preparedconst int STORE = PRE_FRAMES + POST_FRAMES + 1000;enum Mode { WATCHING, RECORDING, SAVING };static const char* ModeName(Mode m) {return m == WATCHING ? "WATCHING" : (m == RECORDING ? "RECORDING" : "SAVING");}// Data shared between threadsstruct RecorderContext {UINT32 width;UINT32 height;UINT32 lineBytes;UINT32 blocksX;UINT32 blocksY;unsigned short qVals[PUC_Q_COUNT];// Slots for received compressed data (a ring buffer). Each frame goes in slot frameNo % STOREstd::vector<std::vector<unsigned char>> store;std::vector<int> storeSeq; // Sequence number of the data in each slot// Queue of the frame numbers waiting to be analyzedstd::deque<long> waiting;std::mutex queueLock;std::condition_variable queueReady;bool stopping;// State (protected by stateLock)std::mutex stateLock;std::condition_variable stateChanged;Mode mode;long triggerNo; // Number of the frame that triggered the recordingdouble cooldownUntil; // Do not accept the next trigger until this timeint saved; // Number of saves// Counters (protected by stateLock)long nextFrameNo; // Number given to each received frame, counting from 0long received;long processed;long gaps;long overflow;int lastSeq;double processSeconds;// The newest image and the moving areas, for display (protected by stateLock)cv::Mat shownImage;std::vector<cv::Rect> shownBoxes;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;}// Compare two DC component images and return the rectangles (in pixels) 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::dilate(mask, mask, cv::Mat()); // Join neighboring blocks so 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_BLOCKS) {boxes.push_back(cv::Rect(r.x * 8, r.y * 8, r.width * 8, r.height * 8)); // Convert from blocks to pixels}}}// Callback function that the SDK calls automatically every time an image arrives.// It does no heavy work: it only copies the compressed data into a slot and puts it in the queuevoid WINAPI ImageCallback(PPUC_XFER_DATA_INFO pXferData, void* pUserParam) {RecorderContext* c = (RecorderContext*)pUserParam;if (!pXferData || !pXferData->pData || !c) {return;}long frameNo = -1;{std::lock_guard<std::mutex> guard(c->stateLock);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;// Copy the compressed data into a slot (the last STORE frames are always kept)std::vector<unsigned char>& slot = c->store[frameNo % STORE];memcpy(slot.data(), pXferData->pData, std::min((size_t)pXferData->nDataSize, slot.size()));c->storeSeq[frameNo % STORE] = seq;c->nextFrameNo++;// When the POST_FRAMES frames after the trigger have arrived, tell the saving sideif (c->mode == RECORDING && frameNo >= c->triggerNo + POST_FRAMES) {c->mode = SAVING;c->stateChanged.notify_all();}}{std::lock_guard<std::mutex> guard(c->queueLock);if ((int)c->waiting.size() >= 1000) {std::lock_guard<std::mutex> stateGuard(c->stateLock);c->overflow++; // The analysis could not keep up and the queue overflowedreturn;}c->waiting.push_back(frameNo);}c->queueReady.notify_one();}// The analysis side (runs in a separate thread). Takes frames out of the queue one at a time// and looks for motion using the DC componentsstatic void AnalyzeWorker(RecorderContext* c) {std::vector<cv::Mat> history; // DC component images of the last GAP framesfor (int i = 0; i < GAP; i++) {history.push_back(cv::Mat((int)c->blocksY, (int)c->blocksX, CV_8UC1));}cv::Mat dc((int)c->blocksY, (int)c->blocksX, CV_8UC1);cv::Mat full((int)c->height, (int)c->lineBytes, CV_8UC1); // Where the whole image is decoded for displaylong count = 0;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();const unsigned char* data = c->store[frameNo % STORE].data();// Extract only the DC components (the average brightness of each 8 x 8 pixel block; very fast)PUC_DecodeDCData(dc.data, 0, 0, c->blocksX, c->blocksY, (PUINT8)data);// Compare with the image GAP frames earlier and look for areas that movedstd::vector<cv::Rect> boxes;if (count >= GAP) {FindMotion(dc, history[count % GAP], boxes);}dc.copyTo(history[count % GAP]);double elapsed = NowSeconds() - start;std::lock_guard<std::mutex> guard(c->stateLock);c->processed++;c->processSeconds += elapsed;// If motion is found while watching and the cooldown has passed, start recording// (right after starting, the frames before the trigger have not been collected yet,// so wait until PRE_FRAMES frames have been received)if (!boxes.empty() && c->mode == WATCHING && NowSeconds() >= c->cooldownUntil && frameNo >= PRE_FRAMES) {c->mode = RECORDING;c->triggerNo = frameNo;printf("Motion detected. Recording before and after...\n");}// Only once every SHOW_EVERY frames, decode the whole image and pass it on for displaycount++;if (count % SHOW_EVERY == 0) {PUC_DecodeDataMultiThread(full.data, 0, 0, c->width, c->height, c->lineBytes,(PUINT8)data, c->qVals, 4);full(cv::Rect(0, 0, (int)c->width, (int)c->height)).copyTo(c->shownImage);c->shownBoxes = boxes;c->isUpdated = true;}}}// Write the frames before and after the trigger frame to an MP4 filestatic void SaveMp4(RecorderContext* c, const std::vector<std::vector<unsigned char>>& clip,const std::vector<int>& seqs, int triggerSeq) {char filename[64];time_t t = time(NULL);struct tm local;localtime_s(&local, &t);strftime(filename, sizeof(filename), "event_%Y%m%d_%H%M%S.mp4", &local);cv::VideoWriter writer(filename, cv::VideoWriter::fourcc('m', 'p', '4', 'v'), PLAY_FPS,cv::Size((int)c->width, (int)c->height));if (!writer.isOpened()) {printf("Error: could not create the MP4 file.\n");return;}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));cv::Mat color;for (size_t i = 0; i < clip.size(); i++) {// Decode for saving with only 2 threads, leaving CPU for the analysis sidePUC_DecodeDataMultiThread(buffer.data, 0, 0, c->width, c->height, c->lineBytes,(PUINT8)clip[i].data(), c->qVals, 2);cv::cvtColor(image, color, cv::COLOR_GRAY2BGR); // Write the MP4 in color// Time from the trigger frame (negative before, positive after). The sequence number wraps from 65535 to 0int offset = ((seqs[i] - triggerSeq + 32768) & 0xFFFF) - 32768;char text[32];sprintf_s(text, "%+8.1f ms", offset * 1000.0 / FRAMERATE);cv::putText(color, text, cv::Point(10, 30), cv::FONT_HERSHEY_SIMPLEX, 0.8, cv::Scalar(255, 255, 255), 2);if (offset == 0) {// Make the trigger frame stand out with a red border and textcv::rectangle(color, cv::Rect(0, 0, (int)c->width, (int)c->height), cv::Scalar(0, 0, 255), 8);cv::putText(color, "TRIGGER", cv::Point(10, 60), cv::FONT_HERSHEY_SIMPLEX, 0.8, cv::Scalar(0, 0, 255), 2);}writer.write(color);}writer.release();printf("Saved: %s (%zu frames, plays for %.0f seconds)\n", filename, clip.size(), clip.size() / PLAY_FPS);}// The saving side (runs in a separate thread). Receiving and analysis keep running while savingstatic void SaveWorker(RecorderContext* c) {while (true) {long first, last;int triggerSeq;{std::unique_lock<std::mutex> guard(c->stateLock);c->stateChanged.wait(guard, [c] { return c->stopping || c->mode == SAVING; });if (c->mode != SAVING) {return; // Signal to finish}// Decide the range of frame numbers to save (only the frames still in the slots)first = std::max(c->triggerNo - PRE_FRAMES, c->nextFrameNo - STORE);first = std::max(first, 0L);last = c->triggerNo + POST_FRAMES;triggerSeq = c->storeSeq[c->triggerNo % STORE];}// Copy the frames before and after the trigger to our own buffer before the slots are overwritten.// The copy takes tens of ms, so do it without holding the lock (stateLock); holding it would stop receiving.// The slots have 1000 frames (1 second) more than the frames before and after, so they are not overwritten meanwhilestd::vector<std::vector<unsigned char>> clip;std::vector<int> seqs;for (long n = first; n < last; n++) {clip.push_back(c->store[n % STORE]);seqs.push_back(c->storeSeq[n % STORE]);}SaveMp4(c, clip, seqs, triggerSeq);std::lock_guard<std::mutex> guard(c->stateLock);c->mode = WATCHING;c->cooldownUntil = NowSeconds() + COOLDOWN;c->saved++;}}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 event recorder (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 dataRecorderContext 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 boundaryctx.blocksX = ctx.width / 8; // In a DC component image, each 8 x 8 pixel block becomes 1 pixelctx.blocksY = ctx.height / 8;printf("Capture settings: %u x %u pixels, %u fps\n", ctx.width, ctx.height, FRAMERATE);// 6. Prepare the slots for compressed datactx.store.assign(STORE, std::vector<unsigned char>(xferDataSize));ctx.storeSeq.assign(STORE, 0);printf("Slots for compressed data: %d frames (about %.0f MB)\n", STORE, (double)STORE * xferDataSize / 1e6);ctx.stopping = false;ctx.mode = WATCHING;ctx.triggerNo = -1;ctx.cooldownUntil = 0.0;ctx.saved = 0;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 and saving threadsstd::thread analyzer(AnalyzeWorker, &ctx);std::thread saver(SaveWorker, &ctx);const char* windowName = "Event recorder (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("Watching... When motion is detected, the moments before and after it are saved as an MP4. 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;Mode mode;int saved;{std::lock_guard<std::mutex> guard(ctx.stateLock);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;mode = ctx.mode;saved = ctx.saved;}// 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) dropped: %ld overflow: %ld",n / (now - lastTime), perFrame, 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);}cv::Scalar modeColor = mode == WATCHING ? cv::Scalar(0, 255, 0): (mode == RECORDING ? cv::Scalar(0, 0, 255) : cv::Scalar(0, 200, 255));char status[64];sprintf_s(status, "%s saved: %d", ModeName(mode), saved);cv::putText(color, info, cv::Point(10, 25), cv::FONT_HERSHEY_SIMPLEX, 0.55, cv::Scalar(0, 255, 0), 2);cv::putText(color, status, cv::Point(10, 50), cv::FONT_HERSHEY_SIMPLEX, 0.55, modeColor, 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 and saving threads, then close the camera// (anything being saved is written to the end before exiting)PUC_EndXferData(hDevice);{std::lock_guard<std::mutex> guard(ctx.queueLock);ctx.stopping = true;}ctx.queueReady.notify_all();analyzer.join();{std::lock_guard<std::mutex> guard(ctx.stateLock);ctx.stopping = true;}ctx.stateChanged.notify_all();saver.join();cv::destroyAllWindows();printf("Done (received: %ld, analyzed: %ld, dropped: %ld, overflow: %ld, saved: %d).\n",ctx.received, ctx.processed, ctx.gaps, ctx.overflow, ctx.saved);PUC_CloseDevice(hDevice);return EXIT_SUCCESS;} -
Set the configuration to “Release”, then build and run
In the toolbar at the top of the window, set the configuration to
Release, then pressCtrl+F5(with Debug, it may not keep up with 1,000 fps; see Finding moving objects). -
Make something happen
When the video window opens and
WATCHINGappears in the top-left corner, it is watching. Drop something in front of the camera, or move your hand quickly. After a while, the console shows the following.Motion detected. Recording before and after...Saved: event_20261023_101530.mp4 (2000 frames, plays for 67 seconds)The MP4 is created in the project folder (
C:\infinicam_projects\applications\EventRecorder) when you run it from Visual Studio withCtrl+F5. -
Exit
Select the video window and press
ESCorQ. If something is being saved, the program exits after it finishes writing.
What is shown in the top-left corner of the window:
| Display | Meaning |
|---|---|
process: 1000 fps |
Frames analyzed in the last second. Around 1000 means motion is checked in every frame |
ms/frame |
Time taken to analyze one frame |
dropped |
Frames that did not arrive (dropped frames) |
overflow |
Frames that overflowed the queue because the analysis could not keep up |
WATCHING and so on |
The current state (see the table in “How it works” above) |
saved |
Number of saves so far |
How the program works
Section titled “How the program works”1. Keep holding the last 1 second (a ring buffer)
ring = collections.deque(maxlen=pre_frames)...ring.append((seq, data))collections.deque(maxlen=…) is a container that automatically drops the oldest items when it goes over the set number. If you add each frame as it arrives, the “last 1 second (1,000 frames)” is always there. The contents stay compressed, so each frame is about 120 KB, and even 1,000 frames are only about 120 MB.
2. When motion is detected, take out the frames before it
state["pre"] = list(ring) # Take the last PRE_SECONDS up to this pointstate["mode"] = "RECORDING"When the analysis side detects motion, the trigger function takes out and keeps the contents of ring at that moment. The frames that arrive after that are collected in post by the receiving function (on_frame). When 1,000 frames are collected, the before and after are joined and handed to the saving side.
Right after the program starts, ring does not yet hold 1 second of frames, so the trigger function does not accept a trigger until it is full.
Motion is detected the same way as in the Python version of Finding moving objects (comparing the DC components with those 10 frames earlier).
3. Leave saving to a separate side
save_jobs.put((state["pre"] + state["post"], state["trigger_seq"]))Writing an MP4 takes several seconds. If watching stopped during that time, the next event would be missed. So writing is left to the saving side (save_worker, a separate thread), and receiving and analysis keep running. The saving side uses its own decoder (save_decoder), separate from the analysis side’s, because both sides decode at the same time.
4. Write the time from the trigger
offset = ((seq - trigger_seq + 32768) & 0xFFFF) - 32768From the difference with the sequence number of the trigger frame, the program works out how many ms before or after the trigger each frame is, and writes it on the frame. The difference is brought into the range -32768 to 32767 so that frames before the trigger become negative (the sequence number cycles through 0 to 65535).
1. Keep holding all the received compressed data
const int STORE = PRE_FRAMES + POST_FRAMES + 1000;...std::vector<unsigned char>& slot = c->store[frameNo % STORE];memcpy(slot.data(), pXferData->pData, ...);The receiving callback (ImageCallback) copies the arriving compressed data into slot “frame number % STORE” of the store (store). When the store goes all the way around, the oldest data is overwritten (a ring buffer). It holds 3,000 frames: the frames before and after (2,000) plus a margin (1,000) for the frames that arrive while a save is being prepared.
Right after the program starts, the store does not yet hold the frames before the trigger, so no trigger is accepted until PRE_FRAMES frames have been received.
2. Keep motion detection light with the DC components
PUC_DecodeDCData(dc.data, 0, 0, c->blocksX, c->blocksY, (PUINT8)data);The C++ version of Finding moving objects analyzed the full image with two threads. In this program, the saving side uses CPU to decode full images and write the MP4, so detection is kept light with the DC components (PUC_DecodeDCData), with a single analysis thread. To find out “whether something happened”, the DC components are enough.
3. The saving side copies without holding the lock
// Decide the range of frame numbers to save (with the lock held; finishes at once)first = std::max(c->triggerNo - PRE_FRAMES, c->nextFrameNo - STORE);...// Copy to our own buffer without the lock (takes tens of ms)for (long n = first; n < last; n++) { clip.push_back(c->store[n % STORE]);}When the 1,000 frames after the trigger have arrived, the receiving callback sets the state to SAVING and wakes the saving side (SaveWorker). The saving side copies the 2,000 frames from the store into its own buffer, then decodes them one at a time and writes them to the MP4.
Copying 2,000 frames (about 240 MB) takes tens of ms. If the state lock (stateLock) were held all that time, the receiving callback, which waits for the lock, would stop, and frames would be dropped. So the lock is held only for the moment it takes to decide which range to copy. The store has a margin of 1,000 frames (1 second), so nothing is overwritten while the copy is in progress.
4. Decode for saving with fewer threads
PUC_DecodeDataMultiThread(buffer.data, ..., c->qVals, 2);The saving side decodes with only 2 threads. This avoids using up the CPU, so the analysis side can keep up with 1,000 fps even while saving.
Things to try
Section titled “Things to try”| Change | Example | What happens |
|---|---|---|
PRE_SECONDS = 1.0 |
3.0 |
Keeps from 3 seconds before the trigger. The memory used to hold frames also triples (about 360 MB) |
POST_SECONDS = 1.0 |
0.5 |
Keeps only 0.5 seconds after the trigger |
COOLDOWN = 3.0 |
10.0 |
After a save, the next trigger is not accepted for 10 seconds |
THRESHOLD = 6 |
10 |
Small changes in brightness no longer trigger a save |
MIN_BLOCKS = 2 |
10 |
Only large moving objects trigger a save |
| Change | Example | What happens |
|---|---|---|
PRE_FRAMES = 1000 |
3000 |
Keeps from 3 seconds before the trigger. STORE grows automatically, and the store uses about 600 MB of memory |
POST_FRAMES = 1000 |
500 |
Keeps only 0.5 seconds after the trigger |
COOLDOWN = 3.0 |
10.0 |
After a save, the next trigger is not accepted for 10 seconds |
THRESHOLD = 6 |
10 |
Small changes in brightness no longer trigger a save |
MIN_BLOCKS = 2 |
10 |
Only large moving objects trigger a save |
Troubleshooting
Section titled “Troubleshooting”| Symptom | Likely cause | What to do |
|---|---|---|
| It saves again and again even though nothing happened | Flickering lights, or noise in the image | Increase THRESHOLD or MIN_BLOCKS. Use a battery-powered light or daylight |
| Nothing is saved even when something moves | The difference in brightness is small | Decrease THRESHOLD. Try with something whose color differs from the background |
| The C++ version shows “Error: could not create the MP4 file.” | opencv_videoio_ffmpeg500_64.dll is not next to the EXE |
Check the post-build event in step 2 of “Try it” |
overflow or dropped grows only while saving |
Saving is taking CPU time | Close other applications. Make sure the C++ version is built in Release |
dropped is not 0 |
Network settings | Check jumbo packets in PC requirements and network settings |
| The MP4 does not play | The video player does not support MPEG-4 (mp4v) | Open it in a free video player such as VLC |
Ideas for applications
Section titled “Ideas for applications”- If the trigger is a trigger signal input to the camera’s general-purpose input (General In) instead of “motion”, you can keep the moments before and after an external sensor or switch responds.
- Before saving, cropping only the area that moved (ROI) or drawing the path of the moving object makes the video easier to review later.
