Measuring rotation speed
Put a white mark on a fan blade or a motor shaft, and watch the spot the mark passes with the INFINICAM GbE-2. While capturing at 1,000 fps, the program counts each time the mark passes and keeps showing the revolutions per minute (rpm) on screen, like a meter.
Because it checks for the mark every 1 ms, it can count every pass without missing any, even for things that spin fast.
| Python version | C++ version | |
|---|---|---|
| Image used for analysis | Decodes only the watched area (16 x 16) | Decodes only the watched area (16 x 16) |
| Analysis time per frame (guide) | About 0.1 ms | About 0.01 ms |
| Analysis workers (threads) | 1 | 1 (to count frames in the order they arrive) |
Before you start
Section titled “Before you start”- Make sure the Python version of Finding moving objects works.
- Looking at how SingleImage + ROI decoding decodes only part of an image will also make this program easier to follow.
- The program in the sample code bundle has Japanese comments. The code below is the same program with English comments and messages.
- Make sure the C++ version of Finding moving objects works in Release.
- Looking at how SingleImage + ROI Decode decodes only part of an image will also make this program easier to follow.
- The program in the sample code bundle has Japanese comments. The code below is the same program with English comments and messages.
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 spins | A fan, a small motor, a bicycle wheel, and so on |
| Mark | A white sticker or white tape. Put it on only one spot of the spinning thing (on a fan with dark blades, put it on the tip of one blade) |
Try it
Section titled “Try it”-
Enter and save the program
Save the following code as
rotation_speed.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]ROI_X = 392 # X of the top-left corner of the area the mark passes (the watched area), a multiple of 8ROI_Y = 296 # Y of the top-left corner of the watched area (a multiple of 8)ROI_W = 16 # Width of the watched area (a multiple of 8)ROI_H = 16 # Height of the watched area (a multiple of 8)HIGH = 150 # When the brightness of the watched area reaches this, "the mark has arrived" (0-255)LOW = 100 # When the brightness falls back to this, "the mark has passed" (0-255)MARKS = 1 # How many times a mark passes per revolution (3 if you mark each of 3 fan blades)AVERAGE = 5 # How many intervals to average when calculating the rotation speedTIMEOUT_MS = 2000 # If no mark arrives for longer than this, treat it as stopped [ms]SHOW_EVERY = 33 # Make an image for display once every this many frames (33 frames = about 30 fps)print("Connecting to the camera...")try:# Connect to the GbE-2 at this IP 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()# Prepare the decoder and have it decode full frames 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.decode(data, ROI_X, ROI_Y, ROI_W, ROI_H)# Queue that hands received data over to the analysis side (up to 1000 frames = 1 second)frames = queue.Queue(maxsize=1000)# Countersstats = {"received": 0, "gaps": 0, "overflow": 0, "processed": 0, "process_time": 0.0}last_seq = None# For display: the newest image, brightness, rotation speed, and number of passesshown = {"image": None, "level": 0.0, "rpm": 0.0, "passes": 0, "above": False}lock = threading.Lock()def on_frame(xfer):"""Called every time a frame arrives. Do nothing heavy here: just put it in the queue"""global last_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 # Analysis could not keep up and the queue overfloweddef analyze_worker():"""Takes frames out of the queue one by one, checks whether the mark passed, and calculates the rotation speed (runs in a separate thread)"""intervals = collections.deque(maxlen=AVERAGE) # Intervals between passes of the mark [ms]t_ms = 0.0prev_seq = Noneabove = False # Whether the mark is in the watched area right nowlast_pass = None # Time the mark last arrived [ms]passes = 0rpm = 0.0count = 0while True:item = frames.get()if item is None: # Signal to finishbreakseq, data = itemstart = time.perf_counter()# Work out the time since capture started [ms] from the sequence number (correct even if frames are dropped)if prev_seq is not None:t_ms += ((seq - prev_seq) & 0xFFFF) * 1000 / FRAMERATEprev_seq = seq# Decode only the watched area and find its average brightnessroi = decoder.decode(data, ROI_X, ROI_Y, ROI_W, ROI_H)level = float(roi.mean())# Above HIGH means "the mark has arrived", below LOW means "it has passed"# (using two separate values keeps one pass from being counted many times when the brightness wobbles near HIGH)if not above and level >= HIGH:above = Truepasses += 1if last_pass is not None:intervals.append(t_ms - last_pass)last_pass = t_mselif above and level <= LOW:above = False# Calculate revolutions per minute from the average interval between passesif last_pass is None or t_ms - last_pass > TIMEOUT_MS:rpm = 0.0intervals.clear()elif intervals:average_ms = sum(intervals) / len(intervals)rpm = 60000 / (average_ms * MARKS)stats["process_time"] += time.perf_counter() - startstats["processed"] += 1# Only once every SHOW_EVERY frames, decode the full frame and hand it over for displaycount += 1if count % SHOW_EVERY == 0:image = decoder.decode(data, reso)with lock:shown["image"] = imageshown["level"] = levelshown["rpm"] = rpmshown["passes"] = passesshown["above"] = abovewindow = "Rotation speed (ESC or Q to quit)"cv2.namedWindow(window, cv2.WINDOW_AUTOSIZE)worker = threading.Thread(target=analyze_worker)worker.start()# Start continuous transfer (on_frame is called every time a frame arrives)cam.setRingBufferCount(64)cam.beginXfer(on_frame)print("Measuring the rotation speed... Select the video window and press ESC or Q to exit.")try:last_time = time.perf_counter()last_processed = 0last_process_time = 0.0info = ""while True:with lock:image = shown["image"]level = shown["level"]rpm = shown["rpm"]passes = shown["passes"]above = shown["above"]shown["image"] = None# Every second, work out how many frames were analyzed in the last second and the time per 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 box can be colored# Show the watched area with a box (green while the mark is in it, red otherwise)color = (0, 255, 0) if above else (0, 0, 255)cv2.rectangle(image, (ROI_X, ROI_Y), (ROI_X + ROI_W, ROI_Y + ROI_H), color, 2)cv2.putText(image, info, (10, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (0, 255, 0), 2)cv2.putText(image, f"{rpm:.0f} rpm", (10, 75), cv2.FONT_HERSHEY_SIMPLEX, 1.6, (0, 255, 255), 3)cv2.putText(image, f"level: {level:.0f} (HIGH {HIGH} / LOW {LOW}) passes: {passes}",(10, 105), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (0, 255, 0), 2)cv2.imshow(window, image)key = cv2.waitKey(1) & 0xFFif key in (27, ord("q"), ord("Q")): # ESC or Qbreakfinally:# Stop continuous transfer, let the analysis thread finish, 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 rotation_speed.py -
Line up the watched spot
A small red box appears in the middle of the video window. This is the watched area. Move the spinning thing and point the camera so that the mark passes over this box.
To move the box, change
ROI_XandROI_Yin the program (both must be multiples of 8). -
Spin it
When you spin it, the box turns green each time the mark passes over it, and the rotation speed is shown in large numbers.
process: 1000 fps (0.10 ms/frame) dropped: 0 overflow: 01200 rpmlevel: 85 (HIGH 150 / LOW 100) passes: 57 -
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 the same way as steps 1 to 7 of Creating the HelloWorld Project. Save it in
C:\infinicam_projects\applicationsand name the projectRotationSpeed. - 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 to 7 of Creating the HelloWorld Project. Save it in
-
Write the source code
Open the main file (
RotationSpeed.cpp) and replace its contents with the following code.#include <stdio.h>#include <stdlib.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 printsconst UINT32 FRAMERATE = 1000; // Frame rate [fps]const UINT32 ROI_X = 392; // X of the top-left corner of the area the mark passes (the watched area), a multiple of 8const UINT32 ROI_Y = 296; // Y of the top-left corner of the watched area (a multiple of 8)const UINT32 ROI_W = 16; // Width of the watched area (a multiple of 8)const UINT32 ROI_H = 16; // Height of the watched area (a multiple of 8)const double HIGH = 150.0; // When the brightness of the watched area reaches this, "the mark has arrived" (0-255)const double LOW = 100.0; // When the brightness falls back to this, "the mark has passed" (0-255)const int MARKS = 1; // How many times a mark passes per revolution (3 if you mark each of 3 fan blades)const int AVERAGE = 5; // How many intervals to average when calculating the rotation speedconst double TIMEOUT_MS = 2000.0; // If no mark arrives for longer than this, treat it as stopped [ms]const int SHOW_EVERY = 33; // Hand over an image for display once every this many frames (33 frames = about 30 fps)const int SLOTS = 256; // Number of places to keep received compressed dataconst int DECODE_THREADS = 6; // Number of threads used when decoding the full frame for display// Data shared between threadsstruct RotationContext {UINT32 width;UINT32 height;UINT32 lineBytes;unsigned short qVals[PUC_Q_COUNT];// Places 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 measurement 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;double level; // Brightness of the watched areadouble rpm; // Revolutions per minutelong passes; // Number of times the mark has passedbool above; // Whether the mark is in the watched area right now// For display: the newest image (protected by statsLock)cv::Mat shownImage;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;}// Callback function called automatically from inside the SDK every time an image arrives.// Do nothing heavy here: just copy the compressed data to a slot and put it in the queuevoid WINAPI ImageCallback(PPUC_XFER_DATA_INFO pXferData, void* pUserParam) {RotationContext* c = (RotationContext*)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 - 1) {std::lock_guard<std::mutex> statsGuard(c->statsLock);c->overflow++; // 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, in the order// they arrived, and checks whether the mark passedstatic void AnalyzeWorker(RotationContext* c) {// A small decode target, just for the watched areaconst UINT32 roiLineBytes = (ROI_W + 3) & ~3;std::vector<unsigned char> roi(roiLineBytes * ROI_H);// Decode target for the full frame, for displaycv::Mat buffer((int)c->height, (int)c->lineBytes, CV_8UC1);cv::Mat image = buffer(cv::Rect(0, 0, (int)c->width, (int)c->height));std::deque<double> intervals; // Intervals between passes of the mark [ms]double tMs = 0.0;int prevSeq = -1;bool above = false;double lastPass = -1.0; // Time the mark last arrived [ms] (-1 if not yet)long passes = 0;double rpm = 0.0;while (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();// Work out the time since capture started [ms] from the sequence number (correct even if frames are dropped)if (prevSeq >= 0) {tMs += ((seq - prevSeq) & 0xFFFF) * 1000.0 / FRAMERATE;}prevSeq = seq;// Decode only the watched area and find its average brightnessconst unsigned char* data = c->slots[frameNo % SLOTS].data();PUC_DecodeData(roi.data(), ROI_X, ROI_Y, ROI_W, ROI_H, roiLineBytes, (PUINT8)data, c->qVals);double sum = 0.0;for (UINT32 y = 0; y < ROI_H; y++) {for (UINT32 x = 0; x < ROI_W; x++) {sum += roi[y * roiLineBytes + x];}}double level = sum / (ROI_W * ROI_H);// Above HIGH means "the mark has arrived", below LOW means "it has passed"// (using two separate values keeps one pass from being counted many times when the brightness wobbles near HIGH)if (!above && level >= HIGH) {above = true;passes++;if (lastPass >= 0) {intervals.push_back(tMs - lastPass);if ((int)intervals.size() > AVERAGE) {intervals.pop_front();}}lastPass = tMs;}else if (above && level <= LOW) {above = false;}// Calculate revolutions per minute from the average interval between passesif (lastPass < 0 || tMs - lastPass > TIMEOUT_MS) {rpm = 0.0;intervals.clear();}else if (!intervals.empty()) {double total = 0.0;for (double ms : intervals) {total += ms;}rpm = 60000.0 / (total / intervals.size() * MARKS);}double elapsed = NowSeconds() - start;// Only once every SHOW_EVERY frames, decode the full frame and hand it over for displaybool show = (frameNo % SHOW_EVERY == 0);if (show) {PUC_DecodeDataMultiThread(image.data, 0, 0, c->width, c->height, c->lineBytes,(PUINT8)data, c->qVals, DECODE_THREADS);}std::lock_guard<std::mutex> guard(c->statsLock);c->processed++;c->processSeconds += elapsed;c->level = level;c->rpm = rpm;c->passes = passes;c->above = above;if (show) {image.copyTo(c->shownImage);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 rotation 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 for GbE-2 cameras on the networkPUC_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 dataRotationContext 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 places for compressed datactx.slots.assign(SLOTS, std::vector<unsigned char>(xferDataSize));ctx.slotSeq.assign(SLOTS, 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.level = 0.0;ctx.rpm = 0.0;ctx.passes = 0;ctx.above = false;ctx.isUpdated = false;// 7. Start one analysis worker (thread) (only one, so frames are processed in the order they arrived)std::thread worker(AnalyzeWorker, &ctx);const char* windowName = "Rotation 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 rotation 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;while (true) {bool updated = false;long processed, gaps, overflow, passes;double processSeconds, level, rpm;bool above;{std::lock_guard<std::mutex> guard(ctx.statsLock);if (ctx.isUpdated) {ctx.isUpdated = false;ctx.shownImage.copyTo(image);updated = true;}processed = ctx.processed;gaps = ctx.gaps;overflow = ctx.overflow;processSeconds = ctx.processSeconds;level = ctx.level;rpm = ctx.rpm;passes = ctx.passes;above = ctx.above;}// 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 (%.3f 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 box can be colored// Show the watched area with a box (green while the mark is in it, red otherwise)cv::Scalar boxColor = above ? cv::Scalar(0, 255, 0) : cv::Scalar(0, 0, 255);cv::rectangle(color, cv::Rect((int)ROI_X, (int)ROI_Y, (int)ROI_W, (int)ROI_H), boxColor, 2);char rpmText[32];sprintf_s(rpmText, "%.0f rpm", rpm);char levelText[96];sprintf_s(levelText, "level: %.0f (HIGH %.0f / LOW %.0f) passes: %ld", level, HIGH, LOW, passes);cv::putText(color, info, cv::Point(10, 25), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 255, 0), 2);cv::putText(color, rpmText, cv::Point(10, 75), cv::FONT_HERSHEY_SIMPLEX, 1.6, cv::Scalar(0, 255, 255), 3);cv::putText(color, levelText, cv::Point(10, 105), 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, let the analysis worker finish, then close the cameraPUC_EndXferData(hDevice);{std::lock_guard<std::mutex> guard(ctx.queueLock);ctx.stopping = true;}ctx.queueReady.notify_all();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. A small red box (the watched area) appears in the middle of the video window. Point the camera so that the mark passes over this box, then spin it. The box turns green each time the mark passes over it, and the rotation speed is shown in large numbers.process: 1000 fps (0.010 ms/frame) dropped: 0 overflow: 01200 rpmlevel: 85 (HIGH 150 / LOW 100) passes: 57 -
Exit
Select the video window and press
ESCorQ. The console window shows the following.Done (received: 8000, analyzed: 8000, dropped: 0, overflow: 0).
The numbers on the screen mean the following.
| Display | Meaning |
|---|---|
process: 1000 fps |
Number of frames analyzed in one second. Since capture is at 1,000 fps, around 1000 means every frame is being analyzed |
ms/frame |
Time taken to analyze one frame |
dropped |
Number of frames that did not arrive (dropped frames) |
overflow |
Number of frames that overflowed the queue because analysis could not keep up |
rpm |
Revolutions per minute. It becomes 0 if the mark does not come for 2 seconds or more |
level |
Current brightness of the watched area (0-255). It goes up when the mark comes |
passes |
Number of times the mark has passed so far |
How the program works
Section titled “How the program works”1. Decode only the watched area
roi = decoder.decode(data, ROI_X, ROI_Y, ROI_W, ROI_H)level = float(roi.mean())To find out whether the mark passed, it is enough to know the brightness of the small spot the mark passes. So instead of the full frame, the program decodes only the watched area (16 x 16 pixels) (ROI decoding). This is only about 1/2,000 of the pixels, so even in Python each frame takes only about 0.1 ms. The position and size must all be multiples of 8.
2. Count one pass as one with two thresholds
if not above and level >= HIGH: above = True passes += 1 ...elif above and level <= LOW: above = FalseWhen the brightness goes above HIGH (150), the program counts one pass (“the mark has arrived”); when it goes below LOW (100), it treats the mark as having passed. With only one threshold, a small wobble in brightness near the threshold would count one pass many times. Leaving a “neither” band between the two values prevents this (this is called hysteresis).
3. Calculate the rotation speed from the intervals between passes
average_ms = sum(intervals) / len(intervals)rpm = 60000 / (average_ms * MARKS)The program remembers the time intervals (ms) between the last AVERAGE (5) passes of the mark, and calculates the rotation speed from their average. If the mark passes once per revolution, dividing one minute (60,000 ms) by the time of one revolution gives the revolutions per minute. The times are calculated from the sequence numbers the camera attaches, so they are accurate to 1 ms.
4. The limit for things that spin fast
At 1,000 fps, one frame is captured every 1 ms, so at least one frame must be captured while the mark is passing over the watched area. Depending on the size of the mark and the rotation speed, the mark may pass in less than 1 ms and be missed. In that case, make the mark bigger, or make the resolution smaller to raise the frame rate (see Changing capture settings + SingleImage).
1. Decode only the watched area
PUC_DecodeData(roi.data(), ROI_X, ROI_Y, ROI_W, ROI_H, roiLineBytes, (PUINT8)data, c->qVals);The 2nd to 5th values of PUC_DecodeData give the area to decode (top-left position and size). Only the watched area (16 x 16 pixels) is decoded, so each frame takes only about 0.01 ms. Because the area is so small, the program uses plain PUC_DecodeData rather than PUC_DecodeDataMultiThread, which decodes with several threads in parallel.
2. Use one analysis worker
The rotation speed is calculated from “the order and times at which the mark passed”, so frames must be checked in the order they arrive. With two analysis workers, as in Finding moving objects, the order in which frames finish can change. In this program the analysis of each frame is very light and one worker easily keeps up with 1,000 fps, so it uses one worker to keep the order.
The full frame is decoded for display only once every 33 frames (about 0.6 ms). Only then does it take a little longer, but the queue holds the frames that arrive in the meantime, so none are missed.
3. Two thresholds, and calculating the rotation speed
The idea is the same as the Python version. When the brightness goes above HIGH, the program counts one pass, and when it goes below LOW, it waits for the next pass. The revolutions per minute are calculated from the average of the last 5 intervals between passes.
Things to try
Section titled “Things to try”| Change | Example | What happens |
|---|---|---|
ROI_X = 392, ROI_Y = 296 |
ROI_X = 600, ROI_Y = 200 |
The watched spot moves (give multiples of 8) |
ROI_W = 16, ROI_H = 16 |
ROI_W = 32, ROI_H = 32 |
The watched area gets bigger. When the mark is small, making the area smaller than the mark makes it easier to detect |
HIGH = 150, LOW = 100 |
HIGH = 180, LOW = 80 |
A wider gap makes miscounts from brightness wobble less likely. Watch the level display and choose values between the brightness with the mark and without it |
MARKS = 1 |
3 |
Use 3 when you put a mark on each of 3 blades |
AVERAGE = 5 |
20 |
The rotation speed display becomes steadier, but responds more slowly when the rotation changes |
| Change | Example | What happens |
|---|---|---|
ROI_X = 392, ROI_Y = 296 |
ROI_X = 600, ROI_Y = 200 |
The watched spot moves (give multiples of 8) |
ROI_W = 16, ROI_H = 16 |
ROI_W = 32, ROI_H = 32 |
The watched area gets bigger |
HIGH = 150.0, LOW = 100.0 |
HIGH = 180.0, LOW = 80.0 |
A wider gap makes miscounts from brightness wobble less likely |
MARKS = 1 |
3 |
Use 3 when you put a mark on each of 3 blades |
AVERAGE = 5 |
20 |
The rotation speed display becomes steadier, but responds more slowly when the rotation changes |
Troubleshooting
Section titled “Troubleshooting”| Symptom | Likely cause | What to do |
|---|---|---|
passes does not go up when it spins |
The mark is not passing over the box, or level does not reach HIGH when the mark comes |
Adjust the camera direction or ROI_X and ROI_Y while watching the level display. Lower HIGH |
passes goes up while it is stopped, or the rotation speed is too high |
Counting is triggered by flickering lights or bright things other than the mark | Widen the gap between HIGH and LOW. Change the background or direction so that everything except the mark is dark |
| The rotation speed is 2 or 3 times the real one | Something passes several times per revolution (for example, the blades have many white parts) | Make sure nothing but the mark goes above HIGH when passing the box. If you put on several marks, set MARKS to match |
| The rotation speed is lower than the real one at high speed | The mark passes in less than 1 ms and is missed | Make the mark bigger. Make the watched area smaller than the mark |
dropped does not stay at 0 |
Network settings | Check jumbo packets in PC operating environment and network settings |
Ideas for going further
Section titled “Ideas for going further”- If you write the time of each pass to a CSV file, you can graph later how the rotation speeds up or slows down. For example, you can look at how a motor gets up to a steady speed after it is switched on.
- With two watched areas, measuring the time difference between the marks passing each one lets you measure the offset (phase) between two rotations.
