OptrisOptrisDocumentation

Documentation/OTC SDK/Overviewv12.0

Region Examples

Worked examples for measuring areas and their alarms. All use the optris::sdk namespace, and reach the regions and alarms through Imager::Regions() and Imager::Alarms(). For the concepts, see Regions and Alarms.

In Fahrenheit: with the SDK switched to Fahrenheit (SetTemperatureUnit() and its counterparts, see Temperatures in Fahrenheit), every temperature on this page is read and written in Fahrenheit, and every difference in Fahrenheit degrees; the samples are unchanged.

Runnable versions live in examples/cpp/: the seven examples in measurement/, plus alarms/threshold_alarm.cc and patterns/dependency_injection.cc.

Note: Region coordinates divide both axes by the frame width, so y runs 0 … height/width: 0.75 on a 4:3 camera. A centred region therefore sits at {0.5f, 0.375f}, not {0.5f, 0.5f}.

Every Shape In One Place

The seven kinds built one after another, for a reader who wants the whole constructor set before the sections below take them one at a time.

const optris::sdk::Vec2 centre{0.5f, 0.375f};

auto rect    = Region::Rect(centre, {0.4f, 0.3f});
auto circle  = Region::Circle(centre, 0.1f);
auto ellipse = Region::Ellipse(centre, {0.2f, 0.1f},
                               /*rotation_rad=*/3.14159f / 4);
auto line    = Region::Line(centre, {0.8f, 0.5f});
auto spot    = Region::Spot(centre);
auto ring    = Region::Ring(centre, /*outer=*/0.2f, /*inner=*/0.1f);
const optris::sdk::Vec2 corners[] = {
    {0.4f, 0.3f}, {0.6f, 0.3f}, {0.5f, 0.5f}};
auto polygon = Region::Polygon(corners);

A builder copies when it is added, so the same one can be moved and added again:

auto shape = Region::Circle({0.3f, 0.3f}, 0.1f);

shape.name = "inlet";
const auto inlet = imager->Regions().Add(shape);

shape.name = "outlet";
shape.SetCentre({0.7f, 0.3f});
const auto outlet = imager->Regions().Add(shape);

Rectangle

auto zone = Region::Rect(/*centre=*/{0.5f, 0.375f}, /*size=*/{0.4f, 0.3f});
zone.name = "Furnace";
const auto id = imager->Regions().Add(std::move(zone));

Rotated, by an angle in radians; no separate rotated-rectangle type:

auto seam = Region::Rect({0.3f, 0.4f}, {0.25f, 0.06f}, /*rotation=*/0.6f);

Circle and ellipse

auto bearing = Region::Circle({0.75f, 0.4f}, /*radius=*/0.1f);
auto oval = Region::Ellipse({0.5f, 0.375f}, /*radii=*/{0.2f, 0.1f}, 0.3f);

Both are round in pixels: the coordinate space makes a radius mean the same thing on either axis.

Polygon

const std::vector<Vec2> outline = {
    {0.2f, 0.2f}, {0.6f, 0.2f}, {0.7f, 0.5f}, {0.3f, 0.55f}};
auto region = Region::Polygon(outline);

Fewer than three vertices is not a polygon; Regions().Add() returns 0.

Line profile

auto profile = Region::Line({0.2f, 0.3f}, {0.8f, 0.3f});
profile.name = "Weld seam";
profile.want_samples = true;  // keep the pixels, not just the statistics
const auto id = imager->Regions().Add(std::move(profile));

// ... a frame later
if (auto samples = imager->Regions().Samples(id)) {
  for (const RegionSample &s : *samples) {
    Plot(s.position * imager->GetWidth(), s.value_c);  // NaN is a gap
  }
}

A line measures exactly one pixel per step along its longer axis. See examples/cpp/measurement/line_profile.cc and Regions for the details.

Point with a sampling aperture

A single pixel is noisy. Average a small neighbourhood instead:

Aperture aperture;
aperture.shape = ApertureShape::kSquare;  // kPixel, kSquare or kCircle
aperture.radius_px = 2.0f;                // 5x5
aperture.min_coverage = 0.25f;

auto spot = Region::Spot({0.5f, 0.375f}, aperture);
spot.name = "Reference";
const auto id = imager->Regions().Add(std::move(spot));

Check how much of the window was actually used; it is clipped to the region and to the image:

const auto region = imager->Regions().Get(id);
if (region && region->stats.valid) {
  std::println("{:.1f} C over {:.0f}% of the window",
               region->stats.mean_c, region->stats.coverage * 100.0f);
}

This changes the reported temperature; see Regions for the rule.

Ring and boolean shapes

// Measure a flange without including the bore.
auto ring = Region::Ring(/*centre=*/{0.5f, 0.375f},
                         /*outer=*/0.2f, /*inner=*/0.1f);
ring.name = "Flange";
imager->Regions().Add(std::move(ring));

For anything more involved, combine the regions you already have. Subtracted(), United() and Intersected() take another region, not raw geometry, and return a new region. The operands are untouched, which is what lets an editor preview a combination and undo it:

auto plate  = Region::Rect({0.5f, 0.375f}, {0.3f, 0.2f});
auto hole_a = Region::Circle({0.42f, 0.375f}, 0.04f);
auto hole_b = Region::Circle({0.58f, 0.375f}, 0.04f);

auto region = plate.Subtracted(hole_a).Subtracted(hole_b);
region.name = "Plate";
imager->Regions().Add(std::move(region));

The result is the receiver, reshaped: it keeps the plate's name, style, emissivity, alarms and children, and each hole contributes only its shape. Anything attached to the operand (its own rules, its own children) stays with the operand, so nothing is tracked or alarmed twice. Readings and the id are cleared, because the result is a new region that has not been measured. See Region::United() in optris::sdk::Region for the full merge rules, including the emissivity caveat.

Region::Ring(centre, outer, inner) is exactly Region::Circle(centre, outer).Subtracted(Region::Circle(centre, inner)), kept because it is the name people look for.

Or built from raw geometry, when you want the tree itself:

auto plate = MakeShape(Primitive::kRect, MakeTrs({0.5f, 0.375f},
                                                 {0.3f, 0.2f}, 0.0f));
auto hole_a = MakeShape(Primitive::kEllipse, MakeTrs({0.42f, 0.375f},
                                                     {0.04f, 0.04f}, 0.0f));
auto hole_b = MakeShape(Primitive::kEllipse, MakeTrs({0.58f, 0.375f},
                                                     {0.04f, 0.04f}, 0.0f));

Region region;
region.name = "Plate";
region.geometry = Subtract(Subtract(plate, hole_a), hole_b);
imager->Regions().Add(std::move(region));

Union(), Intersect() and Subtract() nest, so Union(rect, Intersect(a, b)) is expressible directly.

Hot and cold spot tracking

A child tracks the extreme within its parent, and clips its aperture to that parent:

Note: C++ nests the children into the parent before adding it; the other four add the parent first and then hang children off its id, because the C ABI's entry point is optris_sdk_imager_add_child_region(parent_id, child). The result is the same tree.

Aperture aperture;
aperture.shape = ApertureShape::kSquare;
aperture.radius_px = 1.0f;

auto area = Region::Rect({0.3f, 0.3f}, {0.4f, 0.4f});
area.name = "Zone A";

auto hot = Region::Spot({0.0f, 0.0f}, aperture);
hot.kind = RegionKind::kHotSpot;
hot.name = "Zone A hot";
area.children.push_back(std::move(hot));

auto cold = Region::Spot({0.0f, 0.0f}, aperture);
cold.kind = RegionKind::kColdSpot;
cold.name = "Zone A cold";
area.children.push_back(std::move(cold));

const auto id = imager->Regions().Add(std::move(area));

Read the children back, including where they currently sit:

Region::tracked_loc is a C++ field with no ABI entry point. The other four read the same number out of the child's own statistics: centre_loc is where a tracked spot currently sits, measured on the simulated camera at (0.49, 0.11) for a child declared at (0, 0).

if (const auto region = imager->Regions().Get(id)) {
  for (const auto &child : region->children) {
    if (!child.stats.valid) continue;
    std::println("{} at ({:.2f}, {:.2f})  {:.1f} C",
                 child.name, child.tracked_loc.x, child.tracked_loc.y,
                 child.stats.mean_c);
  }
}

Blob detection

auto group = Region::Rect({0.5f, 0.375f}, {0.9f, 0.6f});
group.kind = RegionKind::kBlobGroup;
group.name = "Hot parts";
group.blobs.threshold = 45.0f;
group.blobs.min_size = 20;
group.blobs.max_count = 8;
group.blobs.render_mode = BlobRenderMode::kContour;
const auto id = imager->Regions().Add(std::move(group));

// Per frame. Blobs are results, not children: the vector is rebuilt
// every frame and carries no identity across them.
//
// Blobs() returns nullopt for an unknown id and an empty vector for a
// region that found nothing, so test it rather than dereferencing.
if (const auto blobs = imager->Regions().Blobs(id)) {
  for (const auto &blob : *blobs) {
    std::printf("%u px, max %.1f C at (%.3f, %.3f), %zu outline points\n",
                blob.pixel_count, blob.max_c, blob.centre.x, blob.centre.y,
                blob.contour.size());
  }
}

Alarm on the count rather than on a blob, because a blob has no identity from one frame to the next:

Rule rule;
rule.name = "Too many hot parts";
rule.input = SignalId::Region(0, SignalField::kBlobCount);
rule.condition.compare = Compare::kAbove;
rule.condition.alarm.high = 3.0f;
imager->Alarms().Add(id, rule);

To react to movement rather than temperature, use a motion zone (imager->Motion().SetZone()) and a rule on SignalField::kMotionBlobCount, see examples/cpp/measurement/motion_zones.cc.

Drag to create, drag to edit

// Mouse pressed at drag_start, released at cursor (pixels).
auto region = Region::FromDrag(Primitive::kRect,
                               FromPixels(drag_start, w, h),
                               FromPixels(cursor, w, h));
const auto id = imager->Regions().Add(std::move(region));

Dragging in any direction gives the same region. Editing afterwards is in place, so the id and any alarm on it survive:

Editing in place keeps the id, and with it any alarm attached to it. C++ has an Edit() that hands you the region under the measuring lock; the other four read a copy, change it and hand it back through UpdateRegion, the same entry point optris_sdk_imager_update_region that C++'s Edit() is a convenience over.

imager->Regions().Edit(id, [&](Region &r) {
  r.SetCentre(FromPixels(cursor, w, h));
});

Alarms

Rule hot;
hot.name = "over temp";
hot.input = SignalId::Region(SignalField::kMax);
hot.condition.compare = Compare::kAbove;
hot.condition.alarm = {.high = 60.0f, .hysteresis = 2.0f};
hot.condition.warning = Limits{.high = 55.0f};
hot.condition.on_delay = std::chrono::milliseconds(100);
hot.condition.latching = true;   // stays raised until acknowledged
const auto rule_id = imager->Alarms().Add(region_id, std::move(hot));

imager->Alarms().SetCallback([](const AlarmEvent &e) {
  std::println("[{}] {} -> {}  {:.1f} C (limit {:.1f})",
               e.region_name, ToString(e.previous), ToString(e.current),
               e.value, e.limit);
});

SignalId::Region(field) names whichever region the rule is attached to, and Alarms().Add(region_id, rule) fills the slot in. The two-argument SignalId::Region(slot, field) is for naming a different region (an inhibit that silences a rule while some other area is hot), and the slot comes from Regions().SignalSlot(id).

Releasing a latch:

imager->Alarms().Acknowledge(rule_id);

Acknowledging a rule whose condition still holds does not silence it: the alarm stays active and the latch re-arms. Alarms().StatusOf(rule_id) says in advance which of the two will happen: when AlarmStatus::held_by_latch is true the value is back inside the limits and acknowledging releases the alarm; when it is false the value is still outside them and acknowledging changes nothing.

Free alarms on your own values

The same machinery, on a value the SDK never measured:

const auto slot = imager->Alarms().RegisterSignal("line pressure");

Rule pressure;
pressure.name = "pressure high";
pressure.input = SignalId::User(slot);
pressure.condition.compare = Compare::kAbove;
pressure.condition.alarm.high = 4.0f;
imager->Alarms().Add(std::move(pressure));

imager->Alarms().PublishSignal(slot, 4.7);  // evaluated immediately

On the camera itself:

Rule chip;
chip.input = SignalId::Device(SignalField::kChipTemp);
chip.condition.compare = Compare::kAbove;
chip.condition.alarm.high = 70.0f;
imager->Alarms().Add(std::move(chip));

Suppressing alarms from a PIF input

Rule rule;
// ... condition as above ...

Inhibit inhibit;
inhibit.signal = SignalId::Pif(2, SignalField::kDigitalIn);
inhibit.condition.compare = Compare::kEqual;
inhibit.condition.alarm.high = 1.0f;
inhibit.invert = false;   // true inhibits while the condition is *not* met
rule.inhibit.push_back(inhibit);

While the input is asserted the rule reports kInhibited, distinct from kDisabled, so an operator display can tell the two apart. An inhibit signal that stops being produced does not suppress: if the input stops arriving, the alarm rings. A latch survives an inhibit, so an alarm that was raised and latched before the inhibit is still raised when it lifts.

Alarm actions

imager->Recorder().SetOutputDirectory("/var/log/thermal");

Rule rule;
// ... condition as above ...

SnapshotAction snapshot;
snapshot.format = SnapshotFormat::kPng;
snapshot.name_pattern = "{region}_{timestamp}";
snapshot.min_interval = std::chrono::seconds{5};
rule.actions.push_back({ActionTrigger::kOnActivate, snapshot});

RecordingAction recording;
recording.mode = RecordingAction::Mode::kWhileActive;  // or kFixedDuration, kStop
rule.actions.push_back({ActionTrigger::kOnAnyChange, recording});

PifOutputAction relay;
relay.channel = 0;
relay.digital = true;
relay.active_value = 1.0f;     // driven while raised
relay.inactive_value = 0.0f;   // driven once it clears
rule.actions.push_back({ActionTrigger::kOnAnyChange, relay});

An action that could not be carried out (a directory that cannot be written, a PIF that is not there) is reported through Alarms().SetActionErrorCallback(), and does not change the alarm state.

Attaching your own files to whatever the alarm produces:

Note: C++ spells this AddAttachmentProvider; the ABI entry point is optris_sdk_imager_set_attachment_provider and the other four follow it. Set, not add: one provider at a time, and a second call replaces the first.

imager->Recorder().AddAttachmentProvider([&](const rec::AttachmentRequest &ctx) {
  std::vector<rec::Attachment> out;
  out.push_back({"process.json", "application/json", CaptureContext(), true});
  return out;
});

This works for a recording an alarm started, where your code never calls Recorder().Start().

Per-region emissivity

auto painted = Region::Rect({0.3f, 0.3f}, {0.2f, 0.2f});
painted.emissivity = 0.95f;   // 0 means "use the imager's global emissivity"
imager->Regions().Add(std::move(painted));

Reading statistics

One region:

if (const auto region = imager->Regions().Get(id); region && region->stats.valid) {
  std::println("{:.1f}..{:.1f} C, mean {:.1f}, {} px",
               region->stats.min_c, region->stats.max_c,
               region->stats.mean_c, region->stats.pixel_count);
}

The valid test is not optional. When it is false every temperature is NaN and min_loc / max_loc collapse to centre_loc, so a marker drawn without the test lands on the region's centre reading NaN rather than anywhere meaningful. pixel_count and coverage stay truthful either way, which is how to find out why the reading was refused.

All of them, for a live display (one lock and one copy):

for (const auto &state : imager->Regions().States()) {
  if (!state.stats.valid) continue;
  Draw(state.region_id, state.stats.max_c, state.alarm);
}

Without allocating, which is only a question in the two languages that let you choose. The C ABI's reader takes a buffer and an element size, so ReadRegionStates in C# has an overload that writes into a span you own, while Python and Rust return an owned list either way:

std::array<RegionState, 32> buffer;
const size_t n = imager->Regions().ReadStates(buffer.data(), buffer.size());

Percentiles cost extra work on every frame, so ask for them explicitly:

region.want_percentiles = true;   // before Regions().Add()
// ... a frame later
if (auto p = imager->Regions().Percentiles(id); p && p->valid) {
  std::println("95th percentile {:.1f} C", p->p95_c);
}

Histogram of a region

The SDK measures a region down to the individual pixel but it does not bin anything, so a histogram is yours to build. Region::want_samples is what makes it cheap to do; the binning loop is ten lines.

There is a histogram in view/, and it is not this. That one is the auto-scale's: a display histogram over the whole frame, used to choose a colour mapping. It is not a measurement of a region and must not be read as one.

Ask for the per-pixel readings, then read them back without allocating:

#include <cmath>

std::vector<RegionSample> samples(4096);
size_t total = 0;
if (imager->Regions().ReadSamples(region_id, samples.data(), samples.size(),
                                  &total)) {
  const size_t n = std::min(total, samples.size());
  std::array<uint32_t, 32> bins{};
  uint32_t measured = 0;
  uint32_t unmeasurable = 0;
  const float lo = 20.0f;
  const float hi = 40.0f;
  for (size_t i = 0; i < n; ++i) {
    const float v = samples[i].value_c;
    if (!std::isfinite(v)) { ++unmeasurable; continue; }   // see below
    if (v < lo || v > hi) continue;
    const auto b = static_cast<size_t>((v - lo) / (hi - lo) * bins.size());
    ++bins[std::min(b, bins.size() - 1)];
    ++measured;
  }
}

total is how many the region has, which can exceed what you asked for; the first capacity are written. Passing nullptr asks only for the count.

Three things will quietly give you a wrong plot.

An unmeasurable pixel arrives as a quiet NaN, not a sentinel. RegionSample::value_c says so. A loop that neither tests nor counts them either drops them silently (reporting a clean distribution over a region that was half unreadable) or lets one poison a bucket through a comparison that is false either way. Count them, and show the count.

coverage is the denominator, and it is not in the plot. "30 % at 30 C" means 30 % of the pixels that were measured. RegionStats::coverage is measured pixels over the pixels the region nominally covers, and it falls below 1.0 when a region hangs off the sensor, when a Canvas pans or zooms it, or where the distortion correction left no data. A percentage shown without it is a number that will be believed and should not be. Put it beside the plot.

Both flags cost, which is why they are opt-in. A full-frame region is 307 200 readings per frame, and at 50 Hz that is 15 million. Bin them as they arrive and let the buffer go; do not keep a vector per frame. If only the tails interest you, percentiles are far cheaper: p01, p05, p95, p99 and the median for one pass.

A line region measures a one-pixel path, so its histogram has few samples and that is correct rather than a bug. RegionStyle::line_width is how thick the line is drawn, a screen quantity with no effect on what is measured.

Trying it in the showcase

The showcase has this wired up. Run it with --histogram, or turn Histogram on in the menu, and the plot appears bottom-left.

showcase --sim --roi 02_rects --histogram

Ten menu rows configure it, and each one changes what the bars mean: which region, bin count or width (one or the other, never both), the range auto from the region or fixed so two captures compare, the count axis linear or log, and live or frozen.

The log axis is not a nicety. A hot spot in a cold scene is a handful of pixels against tens of thousands: measured on the simulated camera's moving spot, the peak bin holds 97 % of 9216 pixels and the whole 20–45 C tail is invisible on a linear axis and legible on a log one.

The selection skips to the first region that actually measures something, because a preset's first entry is often a caption (a named region with no geometry and so no pixels), and a plot of it is empty for a camera that is working perfectly well. Rows for such a region say (no pixels).

Saving and loading

imager->SaveConfig("setup.json");   // regions, rules and camera settings
imager->LoadConfig("setup.json");   // replaces the regions and rules

Loading replaces the regions and rules already on the camera. Ids are reassigned on load and each region's rules are re-attached to the id it receives.

From pixel geometry

If you have pixel coordinates (from a config file, or a UI that works in pixels), convert rather than porting by hand:

auto region = RegionFromGeometry(Rectangle{10, 10, 40, 30},
                                 imager->GetWidth(), imager->GetHeight());

In the other four languages there is no v11 geometry type to convert from, so the conversion is the division itself. Python carries it on the camera; the rest is two lines of arithmetic, and it is the same two lines in every language:

// A pixel rectangle at (10, 10), 40 x 30, on this camera.
float scale = 1.0f / camera.Width;
using Region fromPixels = Region.Rect(
    centre: new Vector2((10 + 40 / 2.0f) * scale, (10 + 30 / 2.0f) * scale),
    size: new Vector2(40 * scale, 30 * scale));

And from a deprecated Roi, which applies the vertical coordinate change:

auto region = ToRegion(old_roi, imager->GetWidth(), imager->GetHeight());