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);
optris_sdk_vec2 centre = {0.5F, 0.375F}; optris_sdk_vec2 size = {0.4F, 0.3F}; optris_sdk_vec2 radii = {0.2F, 0.1F}; optris_sdk_vec2 end = {0.8F, 0.5F}; optris_sdk_vec2 corners[] = {{0.4F, 0.3F}, {0.6F, 0.3F}, {0.5F, 0.5F}}; optris_sdk_region *rect = NULL; optris_sdk_region *circle = NULL; optris_sdk_region *ellipse = NULL; optris_sdk_region *line = NULL; optris_sdk_region *spot = NULL; optris_sdk_region *ring = NULL; optris_sdk_region *polygon = NULL; optris_sdk_region_create_rect(centre, size, 0.0F, &rect); optris_sdk_region_create_circle(centre, 0.1F, &circle); optris_sdk_region_create_ellipse(centre, radii, 3.14159F / 4, &ellipse); optris_sdk_region_create_line(centre, end, &line); optris_sdk_region_create_spot(centre, NULL, &spot); optris_sdk_region_create_ring(centre, 0.2F, 0.1F, &ring); optris_sdk_region_create_polygon(corners, 3, &polygon);
var centre = new Vector2(0.5f, 0.375f); using Region rect = Region.Rect(centre, new Vector2(0.4f, 0.3f)); using Region circle = Region.Circle(centre, 0.1f); using Region ellipse = Region.Ellipse(centre, new Vector2(0.2f, 0.1f), rotation: MathF.PI / 4); using Region line = Region.Line(centre, new Vector2(0.8f, 0.5f)); using Region spot = Region.Spot(centre); using Region ring = Region.Ring(centre, outerRadius: 0.2f, innerRadius: 0.1f); using Region polygon = Region.Polygon([ new Vector2(0.4f, 0.3f), new Vector2(0.6f, 0.3f), new Vector2(0.5f, 0.5f), ]);
import math centre = (0.5, 0.375) rect = optris_sdk.Region.rect(centre, (0.4, 0.3)) circle = optris_sdk.Region.circle(centre, 0.1) ellipse = optris_sdk.Region.ellipse(centre, (0.2, 0.1), rotation_rad=math.pi / 4) line = optris_sdk.Region.line(centre, (0.8, 0.5)) spot = optris_sdk.Region.spot(centre) ring = optris_sdk.Region.ring(centre, outer=0.2, inner=0.1) polygon = optris_sdk.Region.polygon([(0.4, 0.3), (0.6, 0.3), (0.5, 0.5)])
let centre = (0.5, 0.375); let rect = Region::rect(centre, (0.4, 0.3), 0.0)?; let circle = Region::circle(centre, 0.1)?; let ellipse = Region::ellipse(centre, (0.2, 0.1), std::f32::consts::FRAC_PI_4)?; let line = Region::line(centre, (0.8, 0.5))?; let spot = Region::spot(centre, None)?; let ring = Region::ring(centre, 0.2, 0.1)?; let polygon = Region::polygon(&[ Vec2 { x: 0.4, y: 0.3 }, Vec2 { x: 0.6, y: 0.3 }, Vec2 { x: 0.5, y: 0.5 }, ])?;
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);
optris_sdk_vec2 at = {0.3F, 0.3F}; optris_sdk_vec2 moved = {0.7F, 0.3F}; optris_sdk_region *shape = NULL; uint64_t inlet = 0; uint64_t outlet = 0; optris_sdk_region_create_circle(at, 0.1F, &shape); optris_sdk_region_set_name(shape, "inlet"); optris_sdk_imager_add_region(imager, shape, &inlet); optris_sdk_region_set_name(shape, "outlet"); optris_sdk_region_set_centre(shape, moved); optris_sdk_imager_add_region(imager, shape, &outlet); optris_sdk_region_free(shape);
using Region shape = Region.Circle(new Vector2(0.3f, 0.3f), 0.1f); shape.Name = "inlet"; ulong inlet = camera.AddRegion(shape); shape.Name = "outlet"; shape.Centre = new Vector2(0.7f, 0.3f); ulong outlet = camera.AddRegion(shape);
shape = optris_sdk.Region.circle((0.3, 0.3), 0.1) shape.set_name('inlet') inlet = camera.regions.add(shape) shape.set_name('outlet') shape.centre = (0.7, 0.3) outlet = camera.regions.add(shape)
let mut shape = Region::circle((0.3, 0.3), 0.1)?; shape.set_name("inlet")?; let inlet = camera.add_region(&shape)?; shape.set_name("outlet")?; shape.set_centre((0.7, 0.3))?; let outlet = camera.add_region(&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));
optris_sdk_region *zone = NULL; uint64_t id = 0; optris_sdk_region_create_rect((optris_sdk_vec2){0.5F, 0.375F}, (optris_sdk_vec2){0.4F, 0.3F}, 0.0F, &zone); optris_sdk_region_set_name(zone, "Furnace"); optris_sdk_imager_add_region(imager, zone, &id); optris_sdk_region_free(zone); /* the camera took a copy */
using Region zone = Region.Rect(centre: new Vector2(0.5f, 0.375f), size: new Vector2(0.4f, 0.3f)); zone.Name = "Furnace"; ulong id = camera.AddRegion(zone);
zone = optris_sdk.Region.rect((0.5, 0.375), (0.4, 0.3)) zone.set_name('Furnace') region_id = camera.regions.add(zone)
let mut zone = Region::rect((0.5, 0.375), (0.4, 0.3), 0.0)?; zone.set_name("Furnace")?; let id = camera.add_region(&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);
optris_sdk_region *seam = NULL; optris_sdk_region_create_rect((optris_sdk_vec2){0.3F, 0.4F}, (optris_sdk_vec2){0.25F, 0.06F}, 0.6F, &seam);
using Region seam = Region.Rect(new Vector2(0.3f, 0.4f), new Vector2(0.25f, 0.06f), rotation: 0.6f);
seam = optris_sdk.Region.rect((0.3, 0.4), (0.25, 0.06), rotation_rad=0.6)
let seam = Region::rect((0.3, 0.4), (0.25, 0.06), 0.6)?;
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);
optris_sdk_region *bearing = NULL; optris_sdk_region *oval = NULL; optris_sdk_region_create_circle((optris_sdk_vec2){0.75F, 0.4F}, 0.1F, &bearing); optris_sdk_region_create_ellipse((optris_sdk_vec2){0.5F, 0.375F}, (optris_sdk_vec2){0.2F, 0.1F}, 0.3F, &oval);
using Region bearing = Region.Circle(new Vector2(0.75f, 0.4f), radius: 0.1f); using Region oval = Region.Ellipse(new Vector2(0.5f, 0.375f), radii: new Vector2(0.2f, 0.1f), rotation: 0.3f);
bearing = optris_sdk.Region.circle((0.75, 0.4), 0.1) oval = optris_sdk.Region.ellipse((0.5, 0.375), (0.2, 0.1), rotation_rad=0.3)
let bearing = Region::circle((0.75, 0.4), 0.1)?; let oval = Region::ellipse((0.5, 0.375), (0.2, 0.1), 0.3)?;
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);
const optris_sdk_vec2 outline[4] = { {0.2F, 0.2F}, {0.6F, 0.2F}, {0.7F, 0.5F}, {0.3F, 0.55F}}; optris_sdk_region *region = NULL; optris_sdk_region_create_polygon(outline, 4, ®ion);
Vector2[] outline = [ new(0.2f, 0.2f), new(0.6f, 0.2f), new(0.7f, 0.5f), new(0.3f, 0.55f), ]; using Region polygon = Region.Polygon(outline);
outline = [(0.2, 0.2), (0.6, 0.2), (0.7, 0.5), (0.3, 0.55)] region = optris_sdk.Region.polygon(outline)
let outline = [ Vec2::new(0.2, 0.2), Vec2::new(0.6, 0.2), Vec2::new(0.7, 0.5), Vec2::new(0.3, 0.55), ]; let 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 } }
optris_sdk_region *profile = NULL; optris_sdk_region_sample samples[512]; uint64_t id = 0; size_t total = 0; size_t i = 0; uint32_t width = 0; optris_sdk_region_create_line((optris_sdk_vec2){0.2F, 0.3F}, (optris_sdk_vec2){0.8F, 0.3F}, &profile); optris_sdk_region_set_name(profile, "Weld seam"); optris_sdk_region_set_want_samples(profile, true); optris_sdk_imager_add_region(imager, profile, &id); optris_sdk_region_free(profile); /* ... a frame later */ optris_sdk_imager_get_width(imager, &width); if (optris_sdk_imager_read_region_samples( imager, id, samples, 512, sizeof samples[0], &total) == OPTRIS_SDK_OK) { for (i = 0; i < total && i < 512; ++i) { Plot(samples[i].position * (float)width, samples[i].value_c); } }
using Region profile = Region.Line(new Vector2(0.2f, 0.3f), new Vector2(0.8f, 0.3f)); profile.Name = "Weld seam"; profile.KeepSamples = true; // keep the pixels, not the statistics ulong id = camera.AddRegion(profile); // ... a frame later foreach (RegionSample s in camera.ReadRegionSamples(id)) { Plot(s.Position * camera.Width, s.Value); // NaN is a gap }
profile = optris_sdk.Region.line((0.2, 0.3), (0.8, 0.3)) profile.set_name('Weld seam') profile.want_samples = True # keep the pixels, not just the statistics region_id = camera.regions.add(profile) # ... a frame later for s in camera.regions.samples(region_id): plot(s.position * camera.width, s.value_c) # NaN is a gap
let mut profile = Region::line((0.2, 0.3), (0.8, 0.3))?; profile.set_name("Weld seam")?; profile.want_samples(true)?; let id = camera.add_region(&profile)?; // ... a frame later let width = camera.width()? as f32; for s in camera.region_samples(id)? { plot(s.position * width, 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));
optris_sdk_aperture aperture; optris_sdk_region *spot = NULL; uint64_t id = 0; optris_sdk_aperture_init(&aperture, sizeof(aperture)); aperture.shape = OPTRIS_SDK_APERTURE_SQUARE; aperture.radius_px = 2.0F; /* 5x5 */ aperture.min_coverage = 0.25F; optris_sdk_region_create_spot((optris_sdk_vec2){0.5F, 0.375F}, &aperture, &spot); optris_sdk_region_set_name(spot, "Reference"); optris_sdk_imager_add_region(imager, spot, &id); optris_sdk_region_free(spot);
var aperture = new Aperture(ApertureShape.Square, // Pixel, Square, Circle radiusPixels: 2.0f, // 5x5 minimumCoverage: 0.25f); using Region spot = Region.Spot(new Vector2(0.5f, 0.375f), aperture); spot.Name = "Reference"; ulong id = camera.AddRegion(spot);
aperture = optris_sdk.Aperture(shape=optris_sdk.APERTURE_SQUARE, radius_px=2.0, # 5x5 min_coverage=0.25) spot = optris_sdk.Region.spot((0.5, 0.375), aperture) spot.set_name('Reference') region_id = camera.regions.add(spot)
let aperture = Aperture::square(2.0).with_min_coverage(0.25); // 5x5 let mut spot = Region::spot((0.5, 0.375), Some(aperture))?; spot.set_name("Reference")?; let id = camera.add_region(&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); }
optris_sdk_region_stats stats; optris_sdk_region_stats_init(&stats, sizeof(stats)); if (optris_sdk_imager_get_region_stats(imager, id, &stats) == OPTRIS_SDK_OK && stats.valid) { printf("%.1f C over %.0f%% of the window\n", (double)stats.mean_c, (double)stats.coverage * 100.0); }
RegionStats stats = camera.GetRegionStats(regionId); if (stats.IsValid) { Console.WriteLine($"{stats.Mean:F1} C over {stats.Coverage:P0} " + $"of the window"); }
stats = camera.regions.stats(region_id) if stats.valid: print(f'{stats.mean_c:.1f} C over {stats.coverage * 100:.0f}% ' f'of the window')
let stats = camera.region_stats(region_id)?; if stats.valid { println!("{:.1} C over {:.0}% of the window", stats.mean_c, stats.coverage * 100.0); }
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));
/* Measure a flange without including the bore. */ optris_sdk_region *ring = NULL; uint64_t ring_id = 0; optris_sdk_region_create_ring((optris_sdk_vec2){0.5F, 0.375F}, 0.2F, 0.1F, &ring); optris_sdk_region_set_name(ring, "Flange"); optris_sdk_imager_add_region(imager, ring, &ring_id); optris_sdk_region_free(ring);
// Measure a flange without including the bore. using Region ring = Region.Ring(new Vector2(0.5f, 0.375f), outerRadius: 0.2f, innerRadius: 0.1f); ring.Name = "Flange"; camera.AddRegion(ring);
# Measure a flange without including the bore. ring = optris_sdk.Region.ring((0.5, 0.375), 0.2, 0.1) ring.set_name('Flange') camera.regions.add(ring)
// Measure a flange without including the bore. let mut ring = Region::ring((0.5, 0.375), 0.2, 0.1)?; ring.set_name("Flange")?; camera.add_region(&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));
optris_sdk_aperture aperture; optris_sdk_region *area = NULL; optris_sdk_region *hot = NULL; optris_sdk_region *cold = NULL; uint64_t area_id = 0; uint64_t hot_id = 0; uint64_t cold_id = 0; optris_sdk_aperture_init(&aperture, sizeof(aperture)); aperture.shape = OPTRIS_SDK_APERTURE_SQUARE; aperture.radius_px = 1.0F; optris_sdk_region_create_rect((optris_sdk_vec2){0.3F, 0.3F}, (optris_sdk_vec2){0.4F, 0.4F}, 0.0F, &area); optris_sdk_region_set_name(area, "Zone A"); optris_sdk_imager_add_region(imager, area, &area_id); optris_sdk_region_free(area); optris_sdk_region_create_spot((optris_sdk_vec2){0.0F, 0.0F}, &aperture, &hot); optris_sdk_region_set_kind(hot, OPTRIS_SDK_REGION_HOT_SPOT); optris_sdk_region_set_name(hot, "Zone A hot"); optris_sdk_imager_add_child_region(imager, area_id, hot, &hot_id); optris_sdk_region_free(hot); optris_sdk_region_create_spot((optris_sdk_vec2){0.0F, 0.0F}, &aperture, &cold); optris_sdk_region_set_kind(cold, OPTRIS_SDK_REGION_COLD_SPOT); optris_sdk_region_set_name(cold, "Zone A cold"); optris_sdk_imager_add_child_region(imager, area_id, cold, &cold_id); optris_sdk_region_free(cold);
var aperture = new Aperture(ApertureShape.Square, radiusPixels: 1.0f); using Region area = Region.Rect(new Vector2(0.3f, 0.3f), new Vector2(0.4f, 0.4f)); area.Name = "Zone A"; ulong areaId = camera.AddRegion(area); using Region hot = Region.Spot(new Vector2(0.0f, 0.0f), aperture); hot.Kind = RegionKind.HotSpot; hot.Name = "Zone A hot"; camera.AddRegion(hot, areaId); using Region cold = Region.Spot(new Vector2(0.0f, 0.0f), aperture); cold.Kind = RegionKind.ColdSpot; cold.Name = "Zone A cold"; camera.AddRegion(cold, areaId);
aperture = optris_sdk.Aperture(shape=optris_sdk.APERTURE_SQUARE, radius_px=1.0) area = optris_sdk.Region.rect((0.3, 0.3), (0.4, 0.4)) area.set_name('Zone A') area_id = camera.regions.add(area) hot = optris_sdk.Region.spot((0.0, 0.0), aperture) hot.kind = optris_sdk.HOT_SPOT hot.set_name('Zone A hot') camera.regions.add_child(area_id, hot) cold = optris_sdk.Region.spot((0.0, 0.0), aperture) cold.kind = optris_sdk.COLD_SPOT cold.set_name('Zone A cold') camera.regions.add_child(area_id, cold)
let aperture = Aperture::square(1.0); let mut area = Region::rect((0.3, 0.3), (0.4, 0.4), 0.0)?; area.set_name("Zone A")?; let area_id = camera.add_region(&area)?; let mut hot = Region::spot((0.0, 0.0), Some(aperture))?; hot.set_kind(RegionKind::HotSpot)?; hot.set_name("Zone A hot")?; camera.add_child_region(area_id, &hot)?; let mut cold = Region::spot((0.0, 0.0), Some(aperture))?; cold.set_kind(RegionKind::ColdSpot)?; cold.set_name("Zone A cold")?; camera.add_child_region(area_id, &cold)?;
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); } }
uint64_t children[8]; size_t count = 0; size_t i = 0; optris_sdk_region_stats stats; if (optris_sdk_imager_get_region_children(imager, id, children, 8, &count) == OPTRIS_SDK_OK) { for (i = 0; i < count && i < 8; ++i) { optris_sdk_region_stats_init(&stats, sizeof(stats)); if (optris_sdk_imager_get_region_stats(imager, children[i], &stats) != OPTRIS_SDK_OK || !stats.valid) { continue; } printf("%llu at (%.2f, %.2f) %.1f C\n", (unsigned long long)children[i], (double)stats.centre_loc.x, (double)stats.centre_loc.y, (double)stats.mean_c); } }
foreach (ulong childId in camera.GetRegionChildren(regionId)) { RegionStats stats = camera.GetRegionStats(childId); if (!stats.IsValid) continue; using Region child = camera.GetRegion(childId); Console.WriteLine($"{child.Name} at ({stats.Centre.X:F2}, " + $"{stats.Centre.Y:F2}) {stats.Mean:F1} C"); }
for child_id in camera.regions.children(region_id): stats = camera.regions.stats(child_id) if not stats.valid: continue child = camera.regions.copy(child_id) print(f'{child.name} at ({stats.centre_loc.x:.2f}, ' f'{stats.centre_loc.y:.2f}) {stats.mean_c:.1f} C')
for child_id in camera.region_children(region_id)? { let stats = camera.region_stats(child_id)?; if !stats.valid { continue; } let child = camera.region(child_id)?; println!("{} at ({:.2}, {:.2}) {:.1} C", child.name()?, stats.centre_loc.x, stats.centre_loc.y, 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()); } }
optris_sdk_region *group = NULL; optris_sdk_blob_config blobs; optris_sdk_blob found[8]; uint64_t group_id = 0; size_t count = 0; size_t i = 0; optris_sdk_region_create_rect((optris_sdk_vec2){0.5F, 0.375F}, (optris_sdk_vec2){0.9F, 0.6F}, 0.0F, &group); optris_sdk_region_set_kind(group, OPTRIS_SDK_REGION_BLOB_GROUP); optris_sdk_region_set_name(group, "Hot parts"); optris_sdk_blob_config_init(&blobs, sizeof(blobs)); blobs.threshold_c = 45.0F; blobs.min_size_pixels = 20; blobs.max_count = 8; blobs.render_mode = OPTRIS_SDK_BLOB_CONTOUR; optris_sdk_region_set_blob_config(group, &blobs); optris_sdk_imager_add_region(imager, group, &group_id); optris_sdk_region_free(group); /* Per frame. Blobs are results, not children: the array is rebuilt * every frame and carries no identity across them. */ if (optris_sdk_imager_read_region_blobs(imager, group_id, found, 8, sizeof found[0], &count) == OPTRIS_SDK_OK) { for (i = 0; i < count && i < 8; ++i) { printf("%u px, max %.1f C at (%.3f, %.3f), %u outline points\n", (unsigned)found[i].pixel_count, (double)found[i].max_c, (double)found[i].centre.x, (double)found[i].centre.y, (unsigned)found[i].contour_points); } }
using Region group = Region.Rect(new Vector2(0.5f, 0.375f), new Vector2(0.9f, 0.6f)); group.Kind = RegionKind.BlobGroup; group.Name = "Hot parts"; group.BlobDetection = BlobDetection.Default with { Threshold = 45.0f, MinSizePixels = 20, MaxCount = 8, RenderMode = BlobRenderMode.Contour, }; ulong groupId = camera.AddRegion(group); // Per frame. Blobs are results, not children: the array is rebuilt // every frame and carries no identity across them. foreach (RegionBlob blob in camera.ReadRegionBlobs(groupId)) { Console.WriteLine($"{blob.PixelCount} px, max {blob.Max:F1} C at " + $"({blob.Centre.X:F3}, {blob.Centre.Y:F3}), " + $"{blob.ContourPointCount} outline points"); }
group = optris_sdk.Region.rect((0.5, 0.375), (0.9, 0.6)) group.kind = optris_sdk.BLOB_GROUP group.set_name('Hot parts') blobs = group.blobs blobs.threshold_c = 45.0 blobs.min_size_pixels = 20 blobs.max_count = 8 blobs.render_mode = optris_sdk.BLOB_CONTOUR group.blobs = blobs group_id = camera.regions.add(group) # Per frame. Blobs are results, not children: the list is rebuilt every # frame and carries no identity across them. An unknown id raises; a # region that found nothing gives an empty list. for blob in camera.regions.blobs(group_id): print(f'{blob.pixel_count} px, max {blob.max_c:.1f} C at ' f'({blob.centre.x:.3f}, {blob.centre.y:.3f}), ' f'{len(blob.contour)} outline points')
let mut group = Region::rect((0.5, 0.375), (0.9, 0.6), 0.0)?; group.set_kind(RegionKind::BlobGroup)?; group.set_name("Hot parts")?; // BlobConfig::new() reads the SDK's own defaults out of the library // rather than restating them, so the two cannot drift. let mut blobs = BlobConfig::new()?; blobs.threshold_c = 45.0; blobs.min_size_pixels = 20; blobs.max_count = 8; blobs.render_mode = BlobRenderMode::Contour; group.set_blob_config(blobs)?; let group_id = camera.add_region(&group)?; // Per frame. Blobs are results, not children: the Vec is rebuilt every // frame and carries no identity across them. for blob in camera.region_blobs(group_id)? { println!("{} px, max {:.1} C at ({:.3}, {:.3}), {} outline points", blob.pixel_count, blob.max_c, blob.centre.x, blob.centre.y, blob.contour.len()); }
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);
optris_sdk_rule *rule = NULL; optris_sdk_signal_id input; optris_sdk_condition condition; uint64_t rule_id = 0; optris_sdk_rule_create(&rule); optris_sdk_rule_set_name(rule, "Too many hot parts"); optris_sdk_signal_id_init(&input, sizeof(input)); input.domain = OPTRIS_SDK_SIGNAL_DOMAIN_REGION; input.field = OPTRIS_SDK_FIELD_BLOB_COUNT; optris_sdk_rule_set_input(rule, &input); optris_sdk_condition_init(&condition, sizeof(condition)); condition.compare = OPTRIS_SDK_COMPARE_ABOVE; condition.alarm.high = 3.0F; optris_sdk_rule_set_condition(rule, &condition); optris_sdk_imager_add_rule(imager, id, rule, &rule_id); optris_sdk_rule_free(rule);
camera.AddRule(regionId, new AlarmRule { Name = "Too many hot parts", Input = SignalId.Region(SignalField.BlobCount), Condition = AlarmCondition.Above(3.0f), });
rule = optris_sdk.Rule( name='Too many hot parts', input=optris_sdk.SignalId.region(optris_sdk.FIELD_BLOB_COUNT), condition=optris_sdk.Condition(compare=optris_sdk.COMPARE_ABOVE, alarm=optris_sdk.Limits(high=3.0))) camera.alarms.add(rule, region_id=region_id)
let mut rule = Rule::new()?; rule.set_name("Too many hot parts")?; rule.set_input(SignalId::region(SignalField::BlobCount))?; rule.set_condition(Condition::above(3.0, 0.0))?; camera.add_rule(region_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)); });
optris_sdk_region *copy = NULL; if (optris_sdk_imager_copy_region(imager, id, ©) == OPTRIS_SDK_OK) { optris_sdk_region_set_centre(copy, cursor); optris_sdk_imager_update_region(imager, id, copy); optris_sdk_region_free(copy); }
using Region editing = camera.GetRegion(regionId); editing.Centre = new Vector2(0.4f, 0.3f); camera.UpdateRegion(regionId, editing);
editing = camera.regions.copy(region_id) editing.centre = (0.4, 0.3) camera.regions.update(region_id, editing)
let mut editing = camera.region(region_id)?; editing.set_centre((0.4, 0.3))?; camera.update_region(region_id, &editing)?;
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); });
optris_sdk_rule *hot = NULL; optris_sdk_signal_id input; optris_sdk_condition condition; uint64_t rule_id = 0; optris_sdk_rule_create(&hot); optris_sdk_rule_set_name(hot, "over temp"); optris_sdk_signal_id_init(&input, sizeof(input)); input.domain = OPTRIS_SDK_SIGNAL_DOMAIN_REGION; input.field = OPTRIS_SDK_FIELD_MAX; optris_sdk_rule_set_input(hot, &input); optris_sdk_condition_init(&condition, sizeof(condition)); condition.compare = OPTRIS_SDK_COMPARE_ABOVE; condition.alarm.high = 60.0F; condition.alarm.hysteresis = 2.0F; condition.has_warning = 1; condition.warning.high = 55.0F; condition.on_delay_ms = 100; /* milliseconds, not a duration type */ condition.latching = 1; /* stays raised until acknowledged */ optris_sdk_rule_set_condition(hot, &condition); optris_sdk_imager_add_rule(imager, region_id, hot, &rule_id); optris_sdk_rule_free(hot); optris_sdk_imager_set_alarm_callback(imager, OnAlarm, NULL);
ulong ruleId = camera.AddRule(regionId, new AlarmRule { Name = "over temp", Input = SignalId.Region(SignalField.Max), Condition = AlarmCondition.Above(60.0f, hysteresis: 2.0f) with { Warning = new AlarmLimits { High = 55.0f }, OnDelay = TimeSpan.FromMilliseconds(100), IsLatching = true, // stays raised until acknowledged }, }); // .NET hands transitions back as an async stream rather than a // callback, so nothing of yours runs on an SDK thread. await foreach (AlarmEvent e in camera.AlarmEventsAsync(CancellationToken.None)) { Console.WriteLine($"[{e.RegionName}] {e.Previous} -> {e.Current} " + $"{e.Value:F1} C"); break; }
rule = optris_sdk.Rule( name='over temp', input=optris_sdk.SignalId.region(optris_sdk.FIELD_MAX), condition=optris_sdk.Condition( compare=optris_sdk.COMPARE_ABOVE, alarm=optris_sdk.Limits(high=60.0, hysteresis=2.0), warning=optris_sdk.Limits(high=55.0), on_delay_s=0.1, latching=True)) # stays raised until acknowledged rule_id = camera.alarms.add(rule, region_id=region_id) def on_alarm(e): # state_name() spells a state out; `limit` is None when the # transition has none, so test has_limit before formatting it. limit = f' (limit {e.limit:.1f})' if e.has_limit else '' print(f'[{e.region_name}] {optris_sdk.state_name(e.previous)} -> ' f'{optris_sdk.state_name(e.current)} {e.value:.1f} C{limit}') camera.alarms.on_alarm(on_alarm)
let mut hot = Rule::new()?; hot.set_name("over temp")?; hot.set_input(SignalId::region(SignalField::Max))?; hot.set_condition( Condition::above(60.0, 2.0) .with_warning(Limits::above(55.0, 0.0)) .with_on_delay(Duration::from_millis(100)) .latching(true), // stays raised until acknowledged )?; let rule_id = camera.add_rule(region_id, &hot)?; camera.on_alarm(|e| { println!("[{}] {:?} -> {:?} {:.1} C", e.region_name, e.previous, e.current, e.value); })?;
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);
optris_sdk_imager_acknowledge_alarm(imager, rule_id);
camera.AcknowledgeAlarm(ruleId);
camera.alarms.acknowledge(rule_id)
camera.acknowledge_alarm(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
optris_sdk_rule *pressure = NULL; optris_sdk_signal_id input; optris_sdk_condition condition; uint32_t slot = 0; uint64_t rule_id = 0; optris_sdk_imager_register_signal(imager, "line pressure", &slot); optris_sdk_rule_create(&pressure); optris_sdk_rule_set_name(pressure, "pressure high"); optris_sdk_signal_id_init(&input, sizeof(input)); input.domain = OPTRIS_SDK_SIGNAL_DOMAIN_USER; input.index = slot; optris_sdk_rule_set_input(pressure, &input); optris_sdk_condition_init(&condition, sizeof(condition)); condition.compare = OPTRIS_SDK_COMPARE_ABOVE; condition.alarm.high = 4.0F; optris_sdk_rule_set_condition(pressure, &condition); /* Region id 0: the rule is not attached to a region. */ optris_sdk_imager_add_rule(imager, 0, pressure, &rule_id); optris_sdk_rule_free(pressure); optris_sdk_imager_publish_signal(imager, slot, 4.7); /* evaluated now */
uint slot = camera.RegisterSignal("line pressure"); camera.AddRule(new AlarmRule { Name = "pressure high", Input = SignalId.User(slot), Condition = AlarmCondition.Above(4.0f), }); camera.PublishSignal(slot, 4.7); // evaluated immediately
slot = camera.alarms.register_signal('line pressure') rule = optris_sdk.Rule( name='pressure high', input=optris_sdk.SignalId.user(slot), condition=optris_sdk.Condition(compare=optris_sdk.COMPARE_ABOVE, alarm=optris_sdk.Limits(high=4.0))) camera.alarms.add(rule) camera.alarms.publish_signal(slot, 4.7) # evaluated immediately
let slot = camera.register_signal("line pressure")?; let mut pressure = Rule::new()?; pressure.set_name("pressure high")?; pressure.set_input(SignalId::user(slot))?; pressure.set_condition(Condition::above(4.0, 0.0))?; // Region id 0: the rule is not attached to a region. camera.add_rule(0, &pressure)?; camera.publish_signal(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));
optris_sdk_rule *chip = NULL; optris_sdk_signal_id input; optris_sdk_condition condition; uint64_t rule_id = 0; optris_sdk_rule_create(&chip); optris_sdk_signal_id_init(&input, sizeof(input)); input.domain = OPTRIS_SDK_SIGNAL_DOMAIN_DEVICE; input.field = OPTRIS_SDK_FIELD_CHIP_TEMP; optris_sdk_rule_set_input(chip, &input); optris_sdk_condition_init(&condition, sizeof(condition)); condition.compare = OPTRIS_SDK_COMPARE_ABOVE; condition.alarm.high = 70.0F; optris_sdk_rule_set_condition(chip, &condition); optris_sdk_imager_add_rule(imager, 0, chip, &rule_id); optris_sdk_rule_free(chip);
camera.AddRule(new AlarmRule { Input = SignalId.Device(SignalField.ChipTemperature), Condition = AlarmCondition.Above(70.0f), });
chip = optris_sdk.Rule( input=optris_sdk.SignalId.device(optris_sdk.FIELD_CHIP_TEMP), condition=optris_sdk.Condition(compare=optris_sdk.COMPARE_ABOVE, alarm=optris_sdk.Limits(high=70.0))) camera.alarms.add(chip)
let mut chip = Rule::new()?; chip.set_input(SignalId::device(SignalField::ChipTemp))?; chip.set_condition(Condition::above(70.0, 0.0))?; camera.add_rule(0, &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);
optris_sdk_rule *rule = NULL; optris_sdk_signal_id signal; optris_sdk_condition inhibit; optris_sdk_rule_create(&rule); /* ... input and condition as above ... */ optris_sdk_signal_id_init(&signal, sizeof(signal)); signal.domain = OPTRIS_SDK_SIGNAL_DOMAIN_PIF; signal.field = OPTRIS_SDK_FIELD_DIGITAL_IN; signal.index = 2; /* the channel */ optris_sdk_condition_init(&inhibit, sizeof(inhibit)); inhibit.compare = OPTRIS_SDK_COMPARE_EQUAL; inhibit.alarm.high = 1.0F; /* The last argument is `invert`: non-zero inhibits while the * condition is *not* met. */ optris_sdk_rule_add_inhibit(rule, &signal, &inhibit, 0); optris_sdk_rule_free(rule);
var rule = new AlarmRule { // ... input and condition as above ... Condition = AlarmCondition.Above(60.0f), }; rule.Inhibits.Add(new AlarmInhibit( SignalId.ProcessInterface(channel: 2, SignalField.DigitalIn), new AlarmCondition { Compare = AlarmCompare.Equal, Alarm = new AlarmLimits { High = 1.0f }, }, // true inhibits while the condition is *not* met Invert: false));
rule = optris_sdk.Rule( # ... input and condition as above ... input=optris_sdk.SignalId.region(optris_sdk.FIELD_MAX), condition=optris_sdk.Condition(compare=optris_sdk.COMPARE_ABOVE, alarm=optris_sdk.Limits(high=60.0))) rule.add_inhibit( optris_sdk.SignalId.pif(optris_sdk.FIELD_DIGITAL_IN, 2), optris_sdk.Condition(compare=optris_sdk.COMPARE_EQUAL, alarm=optris_sdk.Limits(high=1.0)), invert=False) # True inhibits while the condition is *not* met camera.alarms.add(rule, region_id=region_id)
let mut rule = Rule::new()?; // ... input and condition as above ... rule.set_input(SignalId::region(SignalField::Max))?; rule.set_condition(Condition::above(60.0, 0.0))?; // `Condition`'s fields are public, so the comparisons that have no // named constructor are written out. let mut when_asserted = Condition::new(); when_asserted.compare = Compare::Equal; when_asserted.alarm = Limits::above(1.0, 0.0); rule.add_inhibit( SignalId::pif(SignalField::DigitalIn, 2), when_asserted, // true inhibits while the condition is *not* met false, )?; camera.add_rule(region_id, &rule)?;
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});
optris_sdk_rule *rule = NULL; optris_sdk_imager_set_output_directory(imager, "/var/log/thermal"); optris_sdk_rule_create(&rule); /* ... input and condition as above ... */ /* NULL directory means the imager's output directory. 5000 ms is the * least time between two stills from this action. */ optris_sdk_rule_add_snapshot_action(rule, OPTRIS_SDK_ACTION_ON_ACTIVATE, OPTRIS_SDK_SNAPSHOT_PNG, NULL, "{region}_{timestamp}", 5000); /* 0 ms of duration: WHILE_ACTIVE runs until the alarm clears. */ optris_sdk_rule_add_recording_action(rule, OPTRIS_SDK_ACTION_ON_ANY_CHANGE, OPTRIS_SDK_RECORDING_WHILE_ACTIVE, 0, NULL, NULL); /* channel 0, digital, 1.0 while raised and 0.0 once it clears. */ optris_sdk_rule_add_pif_output_action(rule, OPTRIS_SDK_ACTION_ON_ANY_CHANGE, 0, 1, 1.0F, 0.0F); optris_sdk_rule_free(rule);
camera.OutputDirectory = "/var/log/thermal"; var rule = new AlarmRule { // ... input and condition as above ... Input = SignalId.Region(SignalField.Max), Condition = AlarmCondition.Above(60.0f), }; rule.Actions.Add(new SnapshotAction( SnapshotFormat.Png, NamePattern: "{region}_{timestamp}", MinimumInterval: TimeSpan.FromSeconds(5)) { On = ActionTrigger.OnActivate, }); // WhileActive, or FixedDuration, or Stop. rule.Actions.Add(new RecordingAction(RecordingActionMode.WhileActive) { On = ActionTrigger.OnAnyChange, }); rule.Actions.Add(new PifOutputAction(Channel: 0, IsDigital: true, ActiveValue: 1.0f, InactiveValue: 0.0f) { On = ActionTrigger.OnAnyChange, });
camera.set_output_directory('/var/log/thermal') rule = optris_sdk.Rule( # ... input and condition as above ... input=optris_sdk.SignalId.region(optris_sdk.FIELD_MAX), condition=optris_sdk.Condition(compare=optris_sdk.COMPARE_ABOVE, alarm=optris_sdk.Limits(high=60.0))) # Durations are seconds, as floats, everywhere on this surface. rule.add_snapshot_action(trigger=optris_sdk.ON_ACTIVATE, format=optris_sdk.SNAPSHOT_PNG, name_pattern='{region}_{timestamp}', min_interval_s=5.0) rule.add_recording_action(trigger=optris_sdk.ON_ANY_CHANGE, mode=optris_sdk.RECORDING_WHILE_ACTIVE) rule.add_pif_output_action(channel=0, active_value=1.0, inactive_value=0.0, digital=True, trigger=optris_sdk.ON_ANY_CHANGE)
camera.set_output_directory("/var/log/thermal")?; let mut rule = Rule::new()?; // ... input and condition as above ... rule.set_input(SignalId::region(SignalField::Max))?; rule.set_condition(Condition::above(60.0, 0.0))?; // None for the directory means the camera's output directory; the // last argument is the minimum interval in milliseconds. rule.add_snapshot_action(ActionTrigger::OnActivate, SnapshotFormat::Png, None, Some("{region}_{timestamp}"), 5000)?; // 0 seconds of duration: WhileActive runs until the alarm clears. rule.add_recording_action(ActionTrigger::OnAnyChange, RecordingActionMode::WhileActive, 0, None, None)?; rule.add_pif_output_action(ActionTrigger::OnAnyChange, 0, true, 1.0, 0.0)?;
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; });
camera.SetAttachmentProvider(request => [ new Attachment("process.json", CaptureContext()) { Mime = "application/json", }, ]);
camera.set_attachment_provider(lambda request: [ optris_sdk.Attachment('process.json', capture_context(), mime='application/json'), ])
// The provider is handed a SINK rather than returning a list, so a // payload is written once and never held twice. camera.set_attachment_provider(|_request, sink| { let _ = sink.add("process.json", "application/json", &capture_context(), true); })?;
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));
optris_sdk_region *painted = NULL; uint64_t painted_id = 0; optris_sdk_region_create_rect((optris_sdk_vec2){0.3F, 0.3F}, (optris_sdk_vec2){0.2F, 0.2F}, 0.0F, &painted); /* 0 means "use the imager's global emissivity" */ optris_sdk_region_set_emissivity(painted, 0.95F); optris_sdk_imager_add_region(imager, painted, &painted_id); optris_sdk_region_free(painted);
using Region painted = Region.Rect(new Vector2(0.3f, 0.3f), new Vector2(0.2f, 0.2f)); painted.Emissivity = 0.95f; // 0 means "use the camera's global emissivity" camera.AddRegion(painted);
painted = optris_sdk.Region.rect((0.3, 0.3), (0.2, 0.2)) painted.emissivity = 0.95 # 0 means "use the camera's global emissivity" camera.regions.add(painted)
let mut painted = Region::rect((0.3, 0.3), (0.2, 0.2), 0.0)?; // 0 means "use the camera's global emissivity" painted.set_emissivity(0.95)?; camera.add_region(&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); }
optris_sdk_region_stats stats; optris_sdk_region_stats_init(&stats, sizeof(stats)); if (optris_sdk_imager_get_region_stats(imager, id, &stats) == OPTRIS_SDK_OK && stats.valid) { printf("%.1f..%.1f C, mean %.1f, %u px\n", (double)stats.min_c, (double)stats.max_c, (double)stats.mean_c, (unsigned)stats.pixel_count); }
RegionStats one = camera.GetRegionStats(regionId); if (one.IsValid) { Console.WriteLine($"{one.Minimum:F1}..{one.Maximum:F1} C, " + $"mean {one.Mean:F1}, {one.PixelCount} px"); }
one = camera.regions.stats(region_id) if one.valid: print(f'{one.min_c:.1f}..{one.max_c:.1f} C, mean {one.mean_c:.1f}, ' f'{one.pixel_count} px')
let one = camera.region_stats(region_id)?; if one.valid { println!("{:.1}..{:.1} C, mean {:.1}, {} px", one.min_c, one.max_c, one.mean_c, one.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); }
optris_sdk_region_state states[32]; size_t count = 0; size_t i = 0; for (i = 0; i < 32; ++i) { optris_sdk_region_state_init(&states[i], sizeof(states[i])); } if (optris_sdk_imager_read_region_states(imager, states, 32, sizeof states[0], &count) == OPTRIS_SDK_OK) { for (i = 0; i < count && i < 32; ++i) { if (!states[i].stats.valid) { continue; } Draw(states[i].region_id, states[i].stats.max_c, states[i].alarm); } }
foreach (RegionState state in camera.ReadRegionStates()) { if (!state.Stats.IsValid) continue; Draw(state.Id, state.Stats.Maximum, state.Alarm); }
for state in camera.regions.states(): if not state.stats.valid: continue draw(state.region_id, state.stats.max_c, state.alarm)
for state in camera.read_region_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());
optris_sdk_region_state buffer[32]; size_t written = 0; size_t i = 0; for (i = 0; i < 32; ++i) { optris_sdk_region_state_init(&buffer[i], sizeof(buffer[i])); } optris_sdk_imager_read_region_states(imager, buffer, 32, sizeof buffer[0], &written);
Span<RegionState> buffer = stackalloc RegionState[32]; int written = camera.ReadRegionStates(buffer);
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); }
optris_sdk_region_percentiles p; optris_sdk_region_set_want_percentiles(region, true); /* before adding */ /* ... a frame later */ optris_sdk_region_percentiles_init(&p, sizeof(p)); if (optris_sdk_imager_get_region_percentiles(imager, id, &p) == OPTRIS_SDK_OK && p.valid) { printf("95th percentile %.1f C\n", (double)p.p95_c); }
using Region wanted = Region.Rect(new Vector2(0.5f, 0.375f), new Vector2(0.4f, 0.3f)); wanted.ComputePercentiles = true; // before AddRegion() ulong wantedId = camera.AddRegion(wanted); // ... a frame later RegionPercentiles p = camera.GetRegionPercentiles(wantedId); if (p.IsValid) { Console.WriteLine($"95th percentile {p.NinetyFifthPercentile:F1} C"); }
wanted = optris_sdk.Region.rect((0.5, 0.375), (0.4, 0.3)) wanted.want_percentiles = True # before regions.add() wanted_id = camera.regions.add(wanted) # ... a frame later p = camera.regions.percentiles(wanted_id) if p is not None and p.valid: print(f'95th percentile {p.p95_c:.1f} C')
let mut wanted = Region::rect((0.5, 0.375), (0.4, 0.3), 0.0)?; wanted.want_percentiles(true)?; // before add_region() let wanted_id = camera.add_region(&wanted)?; // ... a frame later. None means the region did not ask for them, or // has not been measured yet -- there is no `valid` flag to test, // because the Option carries that answer. if let Some(p) = camera.region_percentiles(wanted_id)? { println!("95th percentile {:.1} 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; } }
optris_sdk_region_sample samples[4096]; uint64_t region_id = 0; uint32_t bins[32] = {0}; uint32_t measured = 0; uint32_t unmeasurable = 0; size_t total = 0; size_t n = 0; size_t i = 0; size_t b = 0; const float lo = 20.0F; const float hi = 40.0F; if (optris_sdk_imager_read_region_samples(imager, region_id, samples, 4096, sizeof samples[0], &total) == OPTRIS_SDK_OK) { n = total < 4096 ? total : 4096; for (i = 0; i < n; ++i) { const float v = samples[i].value_c; if (v != v) { /* a quiet NaN, see below */ ++unmeasurable; continue; } if (v < lo || v > hi) { continue; } b = (size_t)((v - lo) / (hi - lo) * 32.0F); ++bins[b < 31 ? b : 31]; ++measured; } }
int[] bins = new int[32]; int measured = 0; int unmeasurable = 0; const float lo = 20.0f; const float hi = 40.0f; // The allocating overload asks for the count and then reads them all; // there is a Span overload beside it that writes into a buffer you own. foreach (RegionSample s in camera.ReadRegionSamples(regionId)) { if (float.IsNaN(s.Value)) { unmeasurable++; continue; } // see below if (s.Value < lo || s.Value > hi) continue; int b = (int)((s.Value - lo) / (hi - lo) * bins.Length); bins[Math.Min(b, bins.Length - 1)]++; measured++; }
bins = [0] * 32 measured = 0 unmeasurable = 0 lo, hi = 20.0, 40.0 for s in camera.regions.samples(region_id): if math.isnan(s.value_c): # see below unmeasurable += 1 continue if not lo <= s.value_c <= hi: continue b = int((s.value_c - lo) / (hi - lo) * len(bins)) bins[min(b, len(bins) - 1)] += 1 measured += 1
let mut bins = [0u32; 32]; let mut measured = 0u32; let mut unmeasurable = 0u32; let (lo, hi) = (20.0f32, 40.0f32); for s in camera.region_samples(region_id)? { // Rust does not hand back a NaN to test: `value_c` is an // Option<f32> and None IS the unmeasurable pixel. See below for // why counting them matters. let Some(v) = s.value_c else { unmeasurable += 1; continue; }; if v < lo || v > hi { continue; } let b = ((v - lo) / (hi - lo) * bins.len() as f32) as usize; bins[b.min(bins.len() - 1)] += 1; measured += 1; }
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
/* regions, rules and camera settings */ optris_sdk_imager_save_config(imager, "setup.json"); /* replaces the regions and rules */ optris_sdk_imager_load_config(imager, "setup.json");
// regions, rules and camera settings camera.SaveConfiguration("setup.json"); // replaces the regions and rules, and says what it did ConfigurationLoadReport report = camera.LoadConfiguration("setup.json");
camera.save_config('setup.json') # regions, rules and camera settings camera.load_config('setup.json') # replaces the regions and rules
camera.save_config("setup.json")?; // regions, rules and settings camera.load_config("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));
# camera.from_pixels() does the division, which is the whole of it. centre = camera.from_pixels(10 + 40 / 2, 10 + 30 / 2) scale = 1.0 / camera.width from_pixels = optris_sdk.Region.rect(centre, (40 * scale, 30 * scale))
// A pixel rectangle at (10, 10), 40 x 30, on this camera. let scale = 1.0 / camera.width()? as f32; let from_pixels = Region::rect( ((10.0 + 40.0 / 2.0) * scale, (10.0 + 30.0 / 2.0) * scale), (40.0 * scale, 30.0 * scale), 0.0, )?;
And from a deprecated Roi, which applies the vertical coordinate change:
auto region = ToRegion(old_roi, imager->GetWidth(), imager->GetHeight());