Using the API
The v12 C++ API: what the types are, how to construct one, and what each area is called. For an exact declaration, use API Reference.
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.
On this page
- Two APIs
- Architecture
- Construction
- Frames
- Processing backends
- Visualisation
- Measuring
- Camera control
- Other languages
Two APIs
The SDK ships two public C++ APIs out of one shared library (libotcsdk.so / otcsdk-34.dll).
| API | Namespace | Style | Include |
|---|---|---|---|
| v12 | optris::sdk |
Concrete classes, std::function callbacks, typed exceptions |
optrissdk.h for everything, or the individual headers under optris/sdk/ |
| Legacy | optris |
Abstract interfaces, observer pattern | otcsdk/IRImager.h |
One include covers the whole v12 C++ API, the rec:: recording layer and the view:: layer included:
#include <optrissdk.h>
Existing code against the legacy optris::IRImager keeps working, unchanged. New projects use optris::sdk. Everything below is the v12 API. Migration Guide: v11 to v12 maps the old entry points onto the new ones method by method, and Public Headers lists every installed header.
What differs from the legacy API:
| Legacy | v12 |
|---|---|
| Factories and singletons | Imager::Create() static factory returning std::unique_ptr<Imager>; enumeration and hotplug monitoring are free functions |
IRImagerClient observer base class |
Registered callbacks. Subclassing still works, see Subclassing |
| Push only | Push or pull: AcquireFrame() gets the next frame synchronously |
| Error codes | Typed exceptions under optris::sdk::SdkException. The process interface returns failure instead of throwing |
| One flat list of setters | Settings grouped by area behind accessors |
| Measurement fields and alarm channels | One model: regions, with rules attached to them |
| Recording, playback, snapshots, simulation and visualisation as separate components | All in the library |
The public headers compile at C++17: the SDK's CMake targets export cxx_std_17 on their interface, while the library itself is built with C++23.
Architecture
| Type | Is | Derives from |
|---|---|---|
optris::sdk::Imager |
a camera | FrameSource |
optris::sdk::Player |
a recording being played back | FrameSource |
optris::sdk::StillSource |
a reopened snapshot | FrameSource |
FrameSource carries what all three share: starting and stopping, thermal and BGRA frames (pushed or pulled), palettes and colour scaling, regions and alarm rules. Code written against FrameSource works on any of them.
Everything camera-specific is on Imager, in sub-interfaces reached through accessors:
| Accessor | Covers |
|---|---|
Regions() |
measuring areas and their readings |
Alarms() |
the rules over those areas |
Radiometry() |
emissivity, transmissivity, ambient temperature, reference correction |
Detector() |
shutter-correction schedule, chip heating |
Display() |
colour windows, overlays, GPU surface rendering |
Canvas() |
where the frame sits in view space |
Processing() |
which outputs are produced, filters, picture corrections, which backend ran |
Optics() |
focus |
Device() |
network settings, fail-safe, the camera's user-assigned name |
GetPif() |
the process interface |
Recorder() |
recordings and snapshots |
Buffers() |
memory the SDK writes each frame into |
Motion() |
temperature-band motion zones |
The accessors on a camera repeats this list with each accessor's type and header. The handle an accessor returns refers to the imager and is valid only for as long as the imager is.
Design rules: no singletons for cameras; frames by callback or by pull; RAII, so destroying an Imager disconnects and there is no separate disconnect call; and frames, configuration records and regions are value types that copy and store.
The picture
v12_overview.dot "The v12 public API: frame sources, the sub-interfaces under Imager, the recording and view layers, and the bindings over the flat C ABI"
Every box is a type in include/optris/sdk/. Solid arrows are inheritance, dashed arrows are "reached through this accessor", dotted arrows are "built on". StillSource, the third FrameSource, is not on it.
Construction
| Factory | Opens |
|---|---|
Imager::Create() |
the first camera found. Throws DeviceException if there is none |
Imager::Create(ImagerConfig) |
with specific settings (serial, transport, range, calibration directory, ...) |
Imager::Create(DeviceInfo) |
a camera returned by enumeration |
Imager::Create(DeviceInfo, ImagerConfig) |
an enumerated camera, every other setting from the config. The DeviceInfo wins over the config's serial, transport and network address |
Imager::Create(SimulatedConfig) |
a simulated camera, no hardware needed |
All return std::unique_ptr<Imager>. A recording is not opened through Imager; see Playback.
DeviceInfo, ImagerConfig and SimulatedConfig have overloads taking an OpenProgressCallback, called one phase at a time. Not on the calling thread: a real camera publishes its phases on the SDK's event thread, the same notification queue the connection callbacks use, and only a simulated camera reports them on the thread performing the open. Synchronise any handler that touches shared state. The callback is finished with by the time Create() returns, and an open cannot be cancelled once begun. open_progress.h has the whole contract.
Every factory can raise DeviceBusyException, not only DeviceException. A camera is claimed exclusively across the machine, so an open can meet a claim another program holds, or one this application holds and has not handed back. Both are a busy refusal rather than a missing camera. reason() says which, and one of its values means nothing holds the camera at all; see Error handling. Reconnect() raises it for the same reasons.
#include "optris/sdk.h" #include <print> int main() { // First camera found. auto imager = optris::sdk::Imager::Create(); const auto &info = imager->GetDeviceInfo(); std::println("Connected: {} S/N {} ({}x{} @ {} Hz)", info.model, info.serial, imager->GetWidth(), imager->GetHeight(), info.frame_rate); // Simulated: no hardware needed. Width and height of 0 take the // device type's own resolution (a PI 160 by default). optris::sdk::SimulatedConfig sim; sim.framerate = 30; sim.pattern = optris::sdk::TestPattern::kGradient; auto test = optris::sdk::Imager::Create(sim); }
#include "optris/sdk_c.h" #include <stdio.h> int main(void) { optris_sdk_imager *imager = NULL; optris_sdk_imager *test = NULL; optris_sdk_simulated_config sim; char model[OPTRIS_SDK_MAX_MODEL]; char serial[OPTRIS_SDK_MAX_SERIAL]; size_t written = 0; uint32_t width = 0; uint32_t height = 0; uint32_t frame_rate = 0; /* First camera found. Every entry point returns a status; nothing * throws, because C has nothing to throw. */ if (optris_sdk_imager_create(&imager) != OPTRIS_SDK_OK) { fprintf(stderr, "%s\n", optris_sdk_last_error_message()); return 1; } /* There is no device-info struct on an open imager: each fact has * its own getter, and a string getter takes a buffer and its size * so the library never writes by its own idea of how big one is. */ optris_sdk_imager_get_model(imager, model, sizeof model, &written); optris_sdk_imager_get_serial(imager, serial, sizeof serial, &written); optris_sdk_imager_get_width(imager, &width); optris_sdk_imager_get_height(imager, &height); optris_sdk_imager_get_frame_rate(imager, &frame_rate); printf("Connected: %s S/N %s (%ux%u @ %u Hz)\n", model, serial, (unsigned)width, (unsigned)height, (unsigned)frame_rate); /* Simulated: no hardware needed. Width and height of 0 take the * device type's own resolution. */ optris_sdk_simulated_config_init(&sim, sizeof(sim)); sim.framerate = 30; sim.pattern = OPTRIS_SDK_PATTERN_GRADIENT; optris_sdk_imager_create_simulated(&sim, &test); optris_sdk_imager_destroy(test); optris_sdk_imager_destroy(imager); return 0; }
using Optris.Sdk; // First camera found. await using ThermalCamera camera = ThermalCamera.Open(); Console.WriteLine($"Connected: {camera.Model} S/N {camera.Serial} " + $"({camera.Width}x{camera.Height} @ " + $"{camera.FrameRate} Hz)"); // Simulated: no hardware needed. Width and height left unset take the // device type's own resolution. await using ThermalCamera test = ThermalCamera.OpenSimulated( new SimulatedCameraOptions { FrameRate = 30, Pattern = TestPattern.Gradient, });
import optris_sdk # First camera found. with optris_sdk.Camera.open() as camera: print(f'Connected: {camera.model} S/N {camera.serial} ' f'({camera.width}x{camera.height} @ {camera.frame_rate} Hz)') # Simulated: no hardware needed. Width and height left unset take the # device type's own resolution. The config type is SimulatedCamera -- # it describes the camera, not a configuration of one. config = optris_sdk.SimulatedCamera(framerate=30, pattern=optris_sdk.PATTERN_GRADIENT) with optris_sdk.Camera.simulated(config) as test: pass
use optris_sdk::{Camera, SimulatedConfig, TestPattern}; fn main() -> optris_sdk::Result<()> { // First camera found. let camera = Camera::open()?; println!("Connected: {} S/N {} ({}x{} @ {} Hz)", camera.model()?, camera.serial()?, camera.width()?, camera.height()?, camera.frame_rate()?); // Simulated: no hardware needed. A resolution left unset takes the // device type's own. let config = SimulatedConfig::new() .framerate(30) .pattern(TestPattern::Gradient); let _test = Camera::simulated(&config)?; Ok(()) }
GetWidth() and GetHeight() are the frame dimensions as oriented: after a 90 or 270 degree SetOrientation() they are the sensor's, swapped. GetSensorWidth() and GetSensorHeight() are unaffected by orientation.
A camera calibrates before it streams, so the first frame can take seconds. SkipStartupCalibration() ends that calibration. It does not have to be called before Start(); called while the calibration is running it ends it there, which is how a "skip" button works. It costs more than it buys: the first frame marked as a measurement arrives later, not sooner. imager.h has the measured figures.
Subclassing instead of callbacks
Imager is polymorphic and its default constructor is protected, so it can be subclassed into the observer shape the legacy IRImagerClient had. The protected constructor leaves the imager unattached: a subclass must call the protected Connect() with an ImagerConfig or a SimulatedConfig before Start(), which otherwise throws.
This whole section is C++ only, and not because nobody has written the others. The C ABI hands out an opaque optris_sdk_imager * and has no protected constructor to reach, so there is nothing for a binding to derive from: ThermalCamera, Camera and Rust's Camera are all final/sealed/concrete by construction. In those four, the shape below is composition: hold a camera, and register the callbacks in your own type's constructor. That is what examples/csharp/patterns/, examples/python/ and the Rust examples all do.
class ImagerClient : public optris::sdk::Imager { public: explicit ImagerClient(const optris::sdk::ImagerConfig& config) { Connect(config); } void Start() override { Imager::SetThermalCallback( [this](const optris::sdk::ThermalFrame& f) { OnFrame(f); }); Imager::SetBgraCallback( [this](const optris::sdk::BgraFrame& f) { OnBgraFrame(f); }); Imager::SetConnectionCallback( [this](bool c) { OnConnection(c); }); Imager::SetVideoFormatCallback( [this](uint32_t w, uint32_t h, float fps) { OnVideoFormatChanged(w, h, fps); }); Imager::Start(); } protected: virtual void OnFrame(const optris::sdk::ThermalFrame&) {} virtual void OnBgraFrame(const optris::sdk::BgraFrame&) {} virtual void OnConnection(bool) {} virtual void OnVideoFormatChanged(uint32_t, uint32_t, float) {} };
Override what you need:
class MyCamera : public ImagerClient { public: using ImagerClient::ImagerClient; protected: void OnFrame(const optris::sdk::ThermalFrame& frame) override { float center = frame.GetTemperature( frame.GetWidth() / 2, frame.GetHeight() / 2); std::cout << "Center: " << center << " C, " << "Max: " << frame.GetMaxTemperature() << " C\r" << std::flush; } void OnConnection(bool connected) override { std::cout << (connected ? "Connected" : "Disconnected") << "\n"; } };
The subclass is usable anywhere the base type is expected:
std::unique_ptr<optris::sdk::Imager> imager = std::make_unique<MyCamera>(optris::sdk::ImagerConfig{}); imager->Start(); std::cout << "Press Enter to quit...\n"; std::cin.get(); imager->Stop();
examples/cpp/patterns/subclass.cc is the compiled version.
Frames
Push delivery
Register std::function callbacks. Each setter replaces the previous callback; passing an empty function removes it. Callbacks run on the SDK's own threads: keep them short and hand anything slow to a thread of your own, because a blocked callback holds up the stream behind it. No callback may destroy the Imager; do that from your own thread.
Register before Start() if you want the first frame of the run. A registration carries the frames delivered after it, so the order of the two calls decides whether the first one is yours. A simulated camera and a replay both deliver a frame inside Start(), so registering afterwards loses it; a live camera is slower to produce its first frame and usually hides the difference. The same holds for the alarm, action and device-change streams.
using var stopping = new CancellationTokenSource(TimeSpan.FromSeconds(5)); // Subscribe first. FramesAsync registers the callback when you call // it, and the stream carries what arrives after that -- so calling it // before Start() is how the first frame of the run is yours. IAsyncEnumerable<ThermalFrame> frames = camera.FramesAsync(stopping.Token); camera.Start(); try { await foreach (ThermalFrame frame in frames) { using (frame) { Process(frame); } } } catch (OperationCanceledException) { }
| Callback setter | Frame type | Contents |
|---|---|---|
SetThermalCallback |
ThermalFrame |
Calibrated temperatures. Stored as int16 internally; GetTemperature(x, y) returns Celsius |
SetBgraCallback |
BgraFrame |
BGRA8 false-colour picture |
SetRgbCallback |
RgbFrame |
The visual-camera image, on models that have one. Not a false-colour frame |
SetRawCallback |
RawFrame |
uint16 sensor values before radiometry, in sensor coordinates (never rotated or mirrored) |
SetEnergyCallback |
EnergyFrame |
int32 radiometric energy before the temperature lookup, in sensor coordinates |
Registering a raw or energy callback turns that output on; clearing it turns it off. Nothing else has to be configured.
| Event setter | Fires when |
|---|---|
SetConnectionStatusCallback |
The connection status changes (Connecting, Connected, Stalled, Lost, ...). Prefer this to SetConnectionCallback, which reduces it to a bool and cannot tell a stalled stream from a healthy one |
SetConnectionCallback |
Connected or disconnected, as a bool |
SetVideoFormatCallback |
Stream geometry or frame rate changed: a mode switch, or a quarter-turn of orientation |
SetShutterCallback |
The internal shutter changed position. The only way to get the transitions with timestamps, and the only way to tell a shutter on its way from one that has arrived, since a camera reports Closing and Opening too. For a per-frame answer read ThermalFrame::flag_open |
SetPifValueCallback |
A process-interface reading arrives, with its name and unit |
SetErrorCallback |
A non-fatal problem worth surfacing. Fatal ones throw instead |
SetReconnectCallback |
An automatic reconnection attempt succeeds or fails |
Alarms().SetCallback |
An alarm rule changes state |
Note: Three of the four bindings do not take a callback for frames, and that is deliberate. .NET hands them back as an IAsyncEnumerable; Python's handler runs on an SDK thread holding the GIL, so the pull loop below is usually the better trade; Rust's closure must be Send and is retained until the camera is dropped. The events (connection status, shutter, errors, alarms) are callbacks everywhere.
#include "optris/sdk.h" #include <iostream> #include <print> int main() { auto imager = optris::sdk::Imager::Create(); imager->SetThermalCallback( [](const optris::sdk::ThermalFrame &f) { // Frames from before the startup calibration has finished arrive // too, and are not measurements. if (!f.GetMetadata().thermal_data_reliable) return; std::print("{}x{} min={:.1f} max={:.1f} C\r", f.GetWidth(), f.GetHeight(), f.GetMinTemperature(), f.GetMaxTemperature()); }); imager->SetBgraCallback( [](const optris::sdk::BgraFrame &f) { // f.GetData() is BGRA8, ready for display. }); imager->SetErrorCallback( [](const std::string &msg) { std::println(stderr, "SDK error: {}", msg); }); imager->Start(); std::cin.get(); imager->Stop(); // Callbacks have returned by the time this does. }
#include "optris/sdk_c.h" #include <stdio.h> static void OnThermalFrame(const optris_sdk_frame *frame, void *user) { optris_sdk_frame_info info; optris_sdk_frame_info_init(&info, sizeof(info)); /* Frames from before the startup calibration has finished arrive * too, and are not measurements. */ if (optris_sdk_frame_get_info(frame, &info) != OPTRIS_SDK_OK || !info.thermal_data_reliable) { return; } printf("%ux%u min=%.1f max=%.1f C\r", (unsigned)info.width, (unsigned)info.height, (double)info.min_temp_c, (double)info.max_temp_c); (void)user; } static void OnError(const char *message, void *user) { fprintf(stderr, "SDK error: %s\n", message); (void)user; } int main(void) { optris_sdk_imager *imager = NULL; optris_sdk_imager_create(&imager); /* Every callback setter takes a function pointer and a user-data * pointer: C has no closures, so the context travels beside the * function and has to outlive the registration. */ optris_sdk_imager_set_thermal_callback(imager, OnThermalFrame, NULL); optris_sdk_imager_set_error_callback(imager, OnError, NULL); optris_sdk_imager_start(imager); WaitForEnter(); /* Callbacks have returned by the time this does. */ optris_sdk_imager_stop(imager); optris_sdk_imager_destroy(imager); return 0; }
using Optris.Sdk; await using ThermalCamera camera = ThermalCamera.Open(); // .NET hands frames back as an async stream rather than a callback, so // nothing of yours runs on an SDK thread and the "no callback may // destroy the camera" rule cannot be broken. camera.Start(); await foreach (ThermalFrame frame in camera.FramesAsync(CancellationToken.None)) { using (frame) { // Frames from before the startup calibration has finished // arrive too, and are not measurements. if (frame.Metadata.IsThermalDataReliable) { Console.Write($"{frame.Width}x{frame.Height} " + $"min={frame.MinTemperature:F1} " + $"max={frame.MaxTemperature:F1} C\r"); } } }
import optris_sdk with optris_sdk.Camera.open() as camera: # The handler runs on an SDK thread HOLDING THE GIL, so nothing # else in the process runs while it does, the frame is borrowed and # dies when the handler returns, and closing the camera from inside # one deadlocks. From Python the pull loop is usually the better # trade; see the next section. def on_frame(frame): # Frames from before the startup calibration has finished # arrive too, and are not measurements. if not frame.thermal_data_reliable: return print(f'{frame.width}x{frame.height} min={frame.min_c:.1f} ' f'max={frame.max_c:.1f} C', end='\r') camera.on_thermal_frame(on_frame) camera.start() input() camera.stop() # the handler has returned by the time this does
use optris_sdk::Camera; fn main() -> optris_sdk::Result<()> { let mut camera = Camera::open()?; // The closure runs on an SDK thread, so what it touches has to be // shared properly. A panic inside it is caught at the boundary // rather than unwinding into C, which would be undefined // behaviour; the crate does that for every callback. camera.on_thermal_frame(|frame| { let Ok(info) = frame.info() else { return }; // Frames from before the startup calibration has finished // arrive too, and are not measurements. if !info.thermal_data_reliable { return; } print!("{}x{} min={:.1} max={:.1} C\r", info.width, info.height, info.min_temp_c, info.max_temp_c); })?; camera.start()?; wait_for_enter(); camera.stop()?; // the closure has returned by the time this does Ok(()) }
Raw and energy frames
SetRawCallback() delivers the detector's own uncalibrated uint16 samples. SetEnergyCallback() delivers the pipeline's linear int32 energy, the stage after the corrections and before the temperature lookup. One call of each per thermal frame.
Both are in sensor coordinates and are never rotated or mirrored by SetOrientation(), because the calibration maps and dead-pixel indices they would be compared against are in sensor coordinates too. RawFrame::GetBitDepth() reports the width of the samples (16), not how many of those bits the detector fills. Nothing on the frame path carries the sensor's own depth.
Warning: On a simulated camera these are computed, not measured. A simulation has no detector, so the simulated imager publishes the image its drawn scene would have had, through a fixed linear model: adu = 2048 + internal and energy = 16 * internal, where internal is the thermal frame's own (celsius * 10) + 1000. The result is exact, repeatable and matches the temperature frame pixel for pixel, which is enough to write and test a consumer against. It is not radiometry and must not be used as a calibration reference.
Note: A recording carries neither. Playback stores the corrected thermal frame, so the detector samples and the energy behind them are not in the file; both callbacks report unsupported rather than delivering a substitute.
Pull delivery
#include "optris/sdk.h" #include <chrono> #include <print> int main() { auto imager = optris::sdk::Imager::Create(); imager->Start(); using namespace std::chrono_literals; for (int i = 0; i < 100; ++i) { // Throws CaptureException on timeout. auto frame = imager->AcquireFrame(1000ms); // Frames from before the startup calibration has finished arrive // too, and are not measurements. if (frame.GetMetadata().thermal_data_reliable) std::println("Frame {} max={:.1f} C", frame.GetMetadata().sequence, frame.GetMaxTemperature()); } // Non-blocking variant. if (auto opt = imager->TryAcquireFrame()) { std::println("Got frame: {}x{}", opt->GetWidth(), opt->GetHeight()); } imager->Stop(); }
optris_sdk_imager *imager = NULL; optris_sdk_frame *pulled = NULL; optris_sdk_frame_info info; int i = 0; optris_sdk_simulated_config sim; optris_sdk_simulated_config_init(&sim, sizeof(sim)); optris_sdk_imager_create_simulated(&sim, &imager); optris_sdk_imager_start(imager); for (i = 0; i < 100; ++i) { /* Returns OPTRIS_SDK_ERROR_TIMEOUT rather than throwing. The first * deadline is longer because the first frame takes longer to arrive * than any frame after it. */ if (optris_sdk_imager_acquire_frame(imager, i == 0 ? 15000 : 1000, &pulled) != OPTRIS_SDK_OK) { break; } optris_sdk_frame_info_init(&info, sizeof(info)); optris_sdk_frame_get_info(pulled, &info); /* Frames from before the startup calibration has finished arrive * too, and are not measurements. */ if (info.thermal_data_reliable) { printf("Frame %llu max=%.1f C\n", (unsigned long long)info.sequence, (double)info.max_temp_c); } /* A pulled frame is yours and has to be freed; a callback's is * borrowed and must not be. */ optris_sdk_frame_free(pulled); pulled = NULL; } optris_sdk_imager_stop(imager); optris_sdk_imager_destroy(imager);
camera.Start(); // FramesAsync is the pull loop: it yields a frame you own, on your own // thread, and the token is how it ends. using var stopping = new CancellationTokenSource(); int seen = 0; await foreach (ThermalFrame frame in camera.FramesAsync(stopping.Token)) { using (frame) { // Frames from before the startup calibration has finished // arrive too, and are not measurements. if (frame.Metadata.IsThermalDataReliable) { Console.WriteLine($"Frame {frame.Metadata.Sequence} " + $"max={frame.MaxTemperature:F1} C"); } } if (++seen == 100) break; } camera.Stop();
camera.start() # 15 s rather than a frame period: the first frame takes longer to # arrive than any frame after it, so a deadline sized for the steady # state expires on the first frame and only on the first frame. Frames # from before the startup calibration has finished arrive too, and are # not measurements. for frame in camera.frames(100, timeout_ms=15000): if frame.thermal_data_reliable: print(f'Frame {frame.sequence} max={frame.max_c:.1f} C') camera.stop()
camera.start()?; for i in 0..100 { // Ok(None) is a timeout, not an error: the first deadline is // longer because the first frame takes longer to arrive. let Some(frame) = camera.acquire_frame(if i == 0 { 15000 } else { 1000 })? else { break; }; let info = frame.info()?; // Frames from before the startup calibration has finished arrive // too, and are not measurements. if info.thermal_data_reliable { println!("Frame {} max={:.1} C", info.sequence, info.max_temp_c); } } camera.stop()?;
"No frame yet" on a running camera is routine, so the non-blocking form answers false rather than raising: a poll loop should not have to be a try block. Anything genuinely wrong still raises.
if (auto waiting = imager->TryAcquireFrame()) { Draw(*waiting); }
optris_sdk_frame *waiting = NULL; /* A zero timeout asks rather than waits: OPTRIS_SDK_ERROR_WOULD_BLOCK * means no frame yet, which on a running camera is routine. */ if (optris_sdk_imager_acquire_frame(imager, 0, &waiting) == OPTRIS_SDK_OK) { Draw(waiting); optris_sdk_frame_free(waiting); }
if (camera.TryAcquireFrame(out ThermalFrame? frame)) { using (frame) { Draw(frame); } }
# None means no frame yet, which on a running camera is routine. waiting = camera.try_acquire() if waiting is not None: draw(waiting)
// A zero timeout asks rather than waits: Ok(None) means no frame // yet, which on a running camera is routine. if let Some(waiting) = camera.acquire_frame(0)? { draw(&waiting); }
The acquisition queue is four frames deep. When a consumer falls behind, FrameQueuePolicy::kDropOldest (the default) evicts the oldest frame so a pull always gets one of the most recent; kDropNewest keeps a contiguous run and discards arrivals instead. Set it with SetFrameQueuePolicy(). GetDroppedFrameCount() counts the frames this queue discarded, and nothing else.
A shutter cycle is not a gap in the stream. Frames keep arriving while the shutter is in the way: the SDK holds the last frame taken with it open and delivers that. Those frames carry is_repeated_frame, and flag_open is false on them. A watchdog, or anything else inferring a cycle from frames stopping, reads flag_open, is_repeated_frame or SetShutterCallback() instead.
Reading temperatures out of a frame
ThermalFrame stores temperatures as int16_t in the SDK's internal format, internal = (celsius * 10) + 1000. That is where the 0.1 °C step in every reported temperature comes from. GetTemperature(x, y) converts one pixel.
For a whole frame as temperatures, ask the SDK rather than converting the samples yourself: it answers NaN for a pixel it could not measure, which the bare formula turns into a plausible-looking -3376.8 °C.
std::vector<float> celsius(frame.GetPixelCount()); frame.CopyTemperaturesTo(celsius);
float *celsius = NULL; size_t pixels = 0; size_t written = 0; optris_sdk_frame_get_pixel_count(frame, &pixels); celsius = (float *)malloc(pixels * sizeof(float)); optris_sdk_frame_read_temperatures(frame, celsius, pixels, &written); free(celsius);
float[] celsius = new float[frame.PixelCount]; frame.CopyTemperaturesTo(celsius);
# A list of floats, length width * height, NaN where a pixel was not # measured. frame.to_numpy() is the same data as an array when numpy is # installed; the binding itself does not require it. celsius = frame.temperatures()
let celsius: Vec<f32> = frame.temperatures()?;
The scalar helpers are for a single sample you already hold. InternalToCelsius() applies the formula to whatever it is given, including the unmeasured sentinel:
Note: These are static inline in the C header, so they export no symbol and no ctypes binding can call them: not this one, and not any other. Python therefore transcribes them, and the package pins each against the SDK's own answer rather than against a remembered formula (PythonBindingTest.InternalToCelsiusAgreesWithTheSdk). One of those transcriptions was measurably wrong once: C, .NET and Rust compute in float32 and Python's arithmetic is float64, which cost a whole 0.1 K quantum on 885 of 2,000,000 temperatures. See What Python cannot reach.
float c = optris::sdk::InternalToCelsius(raw_value); int16_t raw = optris::sdk::CelsiusToInternal(37.5f);
float c = optris_sdk_internal_to_celsius(raw_value); int16_t raw = optris_sdk_celsius_to_internal(37.5F);
float c = ThermalFrame.ToCelsius(rawValue); short raw = ThermalFrame.FromCelsius(37.5f);
c = optris_sdk.internal_to_celsius(1375) raw = optris_sdk.celsius_to_internal(37.5)
let c = optris_sdk::internal_to_celsius(1375); let raw = optris_sdk::celsius_to_internal(37.5);
Working in raw units is often better than converting. To count pixels above a threshold, convert the threshold once rather than the frame once per pixel:
int16_t threshold = optris::sdk::CelsiusToInternal(60.0f); int hot = 0; const int16_t *raw = frame.GetData(); for (uint32_t i = 0; i < frame.GetPixelCount(); ++i) { if (raw[i] >= threshold) { ++hot; } }
int16_t threshold = optris_sdk_celsius_to_internal(60.0F); const int16_t *raw = NULL; size_t pixels = 0; size_t i; int hot = 0; optris_sdk_frame_get_data(frame, &raw, &pixels); for (i = 0; i < pixels; ++i) { if (raw[i] >= threshold) { ++hot; } }
short threshold = ThermalFrame.FromCelsius(60.0f); int hot = 0; foreach (short raw in frame.Pixels) { if (raw >= threshold) { hot++; } }
threshold = optris_sdk.celsius_to_internal(60.0) hot = sum(1 for raw in frame.samples() if raw >= threshold)
let threshold = celsius_to_internal(60.0); let hot = frame .data()? .iter() .filter(|&&raw| raw >= threshold) .count();
CelsiusToInternal() refuses rather than wraps:
| Input | Result |
|---|---|
| NaN, or at or below absolute zero | kInvalidPixel |
| Hotter than 3176.7 °C | saturates at 32767 |
| Anything else | the internal format, truncated |
// InternalToCelsius answers NaN for an unmeasured pixel, so the round // trip has to give the sentinel back rather than an ordinary reading. int16_t back = optris::sdk::CelsiusToInternal( optris::sdk::InternalToCelsius(optris::sdk::kInvalidPixel)); bool fits = optris::sdk::IsEncodableTemperature(3200.0f);
/* The conversion answers NaN for an unmeasured pixel, so the round * trip has to give the sentinel back rather than an ordinary * reading. */ int16_t back = optris_sdk_celsius_to_internal( optris_sdk_internal_to_celsius(OPTRIS_SDK_INVALID_PIXEL)); int fits = optris_sdk_celsius_is_encodable(3200.0F);
// ToCelsius answers NaN for an unmeasured pixel, so the round trip // has to give the sentinel back rather than an ordinary reading. short back = ThermalFrame.FromCelsius( ThermalFrame.ToCelsius(ThermalFrame.InvalidPixel)); bool fits = ThermalFrame.IsEncodable(3200.0f);
# The conversion answers NaN for an unmeasured pixel, so the round # trip has to give the sentinel (-32768) back rather than an ordinary # reading. back = optris_sdk.celsius_to_internal( optris_sdk.internal_to_celsius(-32768)) fits = optris_sdk.celsius_is_encodable(3200.0)
// The conversion answers NaN for an unmeasured pixel, so the round // trip has to give the sentinel (-32768) back rather than an // ordinary reading. let back = celsius_to_internal(internal_to_celsius(-32768)); let fits = celsius_is_encodable(3200.0);
IsEncodableTemperature() says which of the three you got, and IsMeasurablePixel() is the usual guard on the result: in C optris_sdk_pixel_is_measured(), in C# ThermalFrame.IsMeasured(), in Python optris_sdk.pixel_is_measured(), which also takes a NumPy array, and in Rust pixel_is_measured(). The round trip is exact for a pixel that was never measured. GetTemperature() answers NaN for such a pixel by design; turning that NaN into 0 would make it an ordinary -100.0 °C reading.
The two clocks on a shutter event
A shutter transition carries two times and they are not interchangeable. Both are read at the transition, one immediately after the other, and neither is computed from the other.
| Is | Use it to | |
|---|---|---|
| the monotonic stamp | a stopwatch reading on the same clock a frame's timestamp uses | measure: subtract two of them for the length of a cycle |
| the host time | the machine's wall clock at the moment the shutter moved | display and log |
Measure with the monotonic one, because a time server can step the wall clock in either direction and a user can set it, so two host times can jump or run backwards. That is exactly the wrong failure at the worst moment, which is why timing a cycle with the wall clock is wrong even though it usually looks right.
camera.OnShutterState(change => log.WriteLine($"{change.HostTime:O},{change.Previous},{change.Current}"));
A transition also reports the state before it as well as the state now, so a handler can tell a shutter on its way from one that has arrived: a camera reports Closing and Opening and not only Open and Closed, where its firmware distinguishes them. Register before Start() to also see the startup calibration's own transition.
Processing output control
Which outputs the pipeline produces is part of the processing record. Read it, change what you need, and write it back. Set() writes the whole record:
The setter writes all five flags, so this is a read-modify-write in every language: what you did not mean to change has to come from the getter.
auto processing = imager->Processing().Get(); processing.outputs.bgra_frames = false; // Measuring only: skip colorization. imager->Processing().Set(processing);
optris_sdk_processing_outputs outputs; optris_sdk_processing_outputs_init(&outputs, sizeof(outputs)); optris_sdk_imager_get_processing_outputs(imager, &outputs); outputs.bgra_frames = false; /* Measuring only: skip colorization. */ optris_sdk_imager_set_processing_outputs(imager, &outputs);
ProcessingOutputs outputs = camera.GetProcessingOutputs(); // Measuring only: skip colorization. camera.SetProcessingOutputs(outputs with { BgraFrames = false });
outputs = camera.processing.outputs outputs.bgra_frames = False # Measuring only: skip colorization camera.processing.outputs = outputs
let mut outputs = camera.processing_outputs()?; outputs.bgra_frames = false; // Measuring only: skip colorization camera.set_processing_outputs(outputs)?;
outputs.thermal_frames = false suppresses the entire frame dispatch: no callbacks, no external buffers, no recording, and no region, alarm or motion evaluation. To save work, turn off bgra_frames instead.
Frame statistics
| Method | Returns |
|---|---|
GetFrameCount() |
Frames delivered |
GetDroppedFrameCount() |
Frames the acquisition queue discarded because a pull consumer did not keep up |
ResetStatistics() |
Zeroes both counters; safe while streaming |
There is no processing-latency getter in the C++ API, because the SDK does not measure processing latency; v11's getProcessingLatency() returned a hardcoded zero on every camera. The C ABI keeps optris_sdk_imager_get_processing_latency_us() declared so existing code still links, but it always fails with OPTRIS_SDK_ERROR_NOT_SUPPORTED and writes nothing, and the .NET ThermalCamera.ProcessingLatency property always throws FeatureNotSupportedException. Measure latency in your application instead. Do not subtract GetMetadata().timestamp_us from your own clock to get one: that timestamp comes from the streaming transport, it is not a date, and which clock it is on differs between transports. Only the differences between frames are meaningful on every platform.
Processing backends
Two pipelines turn sensor data into temperatures, held to bit-exact agreement: the CPU pipeline, always available, and the GPU pipeline, compute shaders on the graphics card. Both are always built.
There is no API to pick one. The SDK chooses per camera while it opens, applying these rules in order, the first that fires deciding:
- A camera with a sample-point calibration always runs on the CPU pipeline, because only the CPU pipeline implements it.
OTC_FORCE_CPUin the environment forces the CPU pipeline.- A measured table of camera and mode combinations names a pipeline for the modes it covers.
- Otherwise the size rule: frames smaller than 65536 pixels (or
OTC_GPU_MIN_PIXELS) go to the CPU, where a GPU dispatch costs more than the work; larger ones go to the GPU. - If the GPU was chosen but no usable GPU exists (no adapter, only a software adapter, or a device that could not be created), the camera runs on the CPU pipeline.
A GPU that passes the availability probe can still fail when the camera's GPU pipeline initialises. The probe only proves an adapter and a device can be created; the pipeline's buffers, shaders and compute pipelines for this camera's frame size are built later, at connect, on an operation-mode switch, or on a frame-format change. The camera is then moved to the CPU pipeline rather than left without a picture, and the SDK logs an error naming the camera serial, where it happened and why.
C++ reports "no camera attached" as valid == false; the other four have no such flag, because the call itself fails: a status in C, an exception in .NET and Python, an Err in Rust.
const auto info = imager->Processing().Info(); if (info.valid) { std::println("{} pipeline: {}", optris::sdk::ToString(info.kind), info.explanation); if (info.reason == optris::sdk::PipelineReason::kGpuInitFailed) { // The one reason that is a fault: this machine was expected to // compute on its GPU and is not. } }
optris_sdk_pipeline_info info; optris_sdk_pipeline_info_init(&info, sizeof(info)); if (optris_sdk_imager_get_pipeline_info(imager, &info) == OPTRIS_SDK_OK) { printf("pipeline %d: %s\n", (int)info.kind, info.reason_text); if (info.reason == OPTRIS_SDK_PIPELINE_REASON_GPU_INIT_FAILED) { /* The one reason that is a fault: this machine was expected to * compute on its GPU and is not. */ } }
PipelineInfo info = camera.PipelineInfo; Console.WriteLine($"{info.Pipeline} pipeline: {info.ReasonText}"); if (info.Reason == PipelineReason.GpuInitFailed) { // The one reason that is a fault: this machine was expected to // compute on its GPU and is not. }
info = camera.pipeline_info print(f'pipeline {info.kind}: {info.reason_text}') if info.reason == optris_sdk.PIPELINE_REASON_GPU_INIT_FAILED: # The one reason that is a fault: this machine was expected to # compute on its GPU and is not. pass
let info = camera.pipeline_info()?; println!("{:?} pipeline: {}", info.kind, info.reason_text); if info.reason == PipelineReason::GpuInitFailed { // The one reason that is a fault: this machine was expected to // compute on its GPU and is not. }
Info() reports valid == false only when no camera is attached. A simulated camera answers with the CPU pipeline it really runs; playback answers valid == true with PipelineKind::kNone. optris::sdk::GetGpuInfo() reports which GPU adapter the SDK would use, without a camera.
Visualisation
The Imager colorises the thermal frame itself; there is no separate image builder.
17 built-in palettes, kIronBow by default; Colour Palettes names them all and GetAllPalettes() enumerates them for a UI. A 240-colour table of your own goes in with SetCustomPalette(), see Custom Palettes.
By default each frame is scaled to its own range, using the 1st and 99th percentile of the scene (AutoScaleMode::kPercentile; kAbsolute uses the coldest and hottest pixel).
imager->SetPalette(optris::sdk::Palette::kIronBow); imager->SetColorRange(20.0f, 80.0f); // Manual: 20-80 C. imager->SetColorRange({}, {}); // Back to automatic. imager->SetBgraCallback( [](const optris::sdk::BgraFrame &f) { // f.GetData() is BGRA8 pixel data, // f.GetWidth() * f.GetHeight() * 4 bytes. });
optris_sdk_imager_set_palette(imager, OPTRIS_SDK_PALETTE_IRON_BOW); /* Manual: 20-80 C. C has no optional, so each end carries a * has_<end> flag beside it. */ optris_sdk_imager_set_color_range(imager, 1, 20.0F, 1, 80.0F); /* Back to automatic: neither end given. */ optris_sdk_imager_set_color_range(imager, 0, 0.0F, 0, 0.0F); optris_sdk_imager_set_bgra_callback(imager, OnBgraFrame, NULL);
camera.Palette = Palette.IronBow; camera.SetColorRange(20.0f, 80.0f); // Manual: 20-80 C camera.SetColorRange(null, null); // Back to automatic
camera.palette = optris_sdk.PALETTE_IRON_BOW camera.set_color_range(20.0, 80.0) # Manual: 20-80 C camera.set_color_range() # Back to automatic
camera.set_palette(Palette::IronBow)?; camera.set_color_range(Some(20.0), Some(80.0))?; // Manual: 20-80 C camera.set_color_range(None, None)?; // Back to automatic
GetEffectiveColorRange() reports the range actually in use. SetColorScaleDynamics() damps how quickly an automatic scale follows the scene. Colour Palettes and Colour Range are the full chapters.
void *instance = imager->Display().GetGpuInstance(); // a WGPUInstance if (imager->Display().ConfigureSurface(surface, width, height)) { // Every frame now goes straight to the surface, colorized and // with the region overlays, at display resolution. }
void *instance = NULL; optris_sdk_imager_get_gpu_instance(imager, &instance); /* WGPUInstance */ if (optris_sdk_imager_configure_surface(imager, surface, width, height) == OPTRIS_SDK_OK) { /* Every frame now goes straight to the surface, colorized and * with the region overlays, at display resolution. */ }
nint instance = camera.GetGpuInstance(); // a WGPUInstance if (camera.ConfigureSurface(surface, width, height)) { // Every frame now goes straight to the surface, colorized and // with the region overlays, at display resolution. }
instance = camera.gpu_instance() # a WGPUInstance address if camera.configure_surface(surface, width, height): # Every frame now goes straight to the surface, colorized and # with the region overlays, at display resolution. pass
let instance = camera.gpu_instance()?; // a WGPUInstance if unsafe { camera.configure_surface(surface, width, height)? } { // Every frame now goes straight to the surface, colorized and // with the region overlays, at display resolution. }
The same picture can land in a buffer of yours instead, every frame:
optris::sdk::ExternalBuffer ext; ext.data = buffer; ext.size = size_bytes; ext.format = optris::sdk::ExternalPixelFormat::kThermalFloat32; ext.on_written = [](const optris::sdk::ExternalBuffer &buf) { RunModel(buf.data, buf.width, buf.height); }; imager->Buffers().Add(ext);
optris_sdk_imager_set_external_buffer( imager, buffer, size_bytes, OPTRIS_SDK_EXTERNAL_THERMAL_FLOAT32, OnWritten, NULL);
camera.SetExternalBuffer(buffer, sizeBytes, ExternalBufferFormat.ThermalFloat32, onWritten: (b, w, h) => RunModel(b, w, h));
camera.set_external_buffer( buffer, optris_sdk.EXTERNAL_THERMAL_FLOAT32, on_written=lambda w, h: run_model(buffer, w, h))
unsafe { camera.register_external_buffer( buffer, size_bytes, ExternalFormat::ThermalFloat32, Some(move |width, height| run_model(width, height)), )?; }
Measuring
Regions and alarms
A region is a measuring area: geometry, statistics and the alarms that watch it, in one model. Regions and Alarms are the full chapters.
Region coordinates are relative to the frame and divide both axes by its width, so y runs 0 … height/width: 0.75 on a 4:3 camera.
using namespace optris::sdk; auto zone = Region::Rect(/*centre=*/{0.5f, 0.375f}, /*size=*/{0.4f, 0.3f}); zone.name = "Zone A"; zone.emissivity = 0.95f; // A child that tracks the hottest point inside the parent, averaging // a 3x3 window clipped to that parent. Aperture aperture; aperture.shape = ApertureShape::kSquare; aperture.radius_px = 1.0f; auto hot = Region::Spot({0.0f, 0.0f}, aperture); hot.kind = RegionKind::kHotSpot; hot.name = "Zone A hot"; zone.children.push_back(std::move(hot)); const auto id = imager->Regions().Add(std::move(zone)); // 0 if invalid // After frames arrive: if (const auto region = imager->Regions().Get(id); region && region->stats.valid) { std::println("min={:.1f} max={:.1f} mean={:.1f}", region->stats.min_c, region->stats.max_c, region->stats.mean_c); }
optris_sdk_region *zone = NULL; optris_sdk_region *hot = NULL; optris_sdk_aperture aperture; optris_sdk_region_stats stats; uint64_t zone_id = 0; uint64_t hot_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, "Zone A"); optris_sdk_region_set_emissivity(zone, 0.95F); optris_sdk_imager_add_region(imager, zone, &zone_id); /* 0 if invalid */ optris_sdk_region_free(zone); /* A child that tracks the hottest point inside the parent, averaging a * 3x3 window clipped to that parent. The ABI hangs a child off the * parent's id, so the parent goes in first. */ optris_sdk_aperture_init(&aperture, sizeof(aperture)); aperture.shape = OPTRIS_SDK_APERTURE_SQUARE; aperture.radius_px = 1.0F; 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, zone_id, hot, &hot_id); optris_sdk_region_free(hot); /* After frames arrive: */ optris_sdk_region_stats_init(&stats, sizeof(stats)); if (optris_sdk_imager_get_region_stats(imager, zone_id, &stats) == OPTRIS_SDK_OK && stats.valid) { printf("min=%.1f max=%.1f mean=%.1f\n", (double)stats.min_c, (double)stats.max_c, (double)stats.mean_c); }
using Region zone = Region.Rect(centre: new Vector2(0.5f, 0.375f), size: new Vector2(0.4f, 0.3f)); zone.Name = "Zone A"; zone.Emissivity = 0.95f; ulong zoneId = camera.AddRegion(zone); // throws rather than returning 0 // A child that tracks the hottest point inside the parent, averaging a // 3x3 window clipped to that parent. using Region hotChild = Region.Spot( new Vector2(0.0f, 0.0f), new Aperture(ApertureShape.Square, radiusPixels: 1.0f)); hotChild.Kind = RegionKind.HotSpot; hotChild.Name = "Zone A hot"; camera.AddRegion(hotChild, zoneId); // After frames arrive: RegionStats zoneStats = camera.GetRegionStats(zoneId); if (zoneStats.IsValid) { Console.WriteLine($"min={zoneStats.Minimum:F1} " + $"max={zoneStats.Maximum:F1} " + $"mean={zoneStats.Mean:F1}"); }
zone = optris_sdk.Region.rect((0.5, 0.375), (0.4, 0.3)) zone.set_name('Zone A') zone.emissivity = 0.95 zone_id = camera.regions.add(zone) # raises rather than returning 0 # A child that tracks the hottest point inside the parent, averaging a # 3x3 window clipped to that parent. aperture = optris_sdk.Aperture(shape=optris_sdk.APERTURE_SQUARE, radius_px=1.0) 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(zone_id, hot) # After frames arrive: zone_stats = camera.regions.stats(zone_id) if zone_stats.valid: print(f'min={zone_stats.min_c:.1f} max={zone_stats.max_c:.1f} ' f'mean={zone_stats.mean_c:.1f}')
let mut zone = Region::rect((0.5, 0.375), (0.4, 0.3), 0.0)?; zone.set_name("Zone A")?; zone.set_emissivity(0.95)?; let zone_id = camera.add_region(&zone)?; // Err rather than 0 // A child that tracks the hottest point inside the parent, averaging a // 3x3 window clipped to that parent. let mut hot_child = Region::spot((0.0, 0.0), Some(Aperture::square(1.0)))?; hot_child.set_kind(RegionKind::HotSpot)?; hot_child.set_name("Zone A hot")?; camera.add_child_region(zone_id, &hot_child)?; // After frames arrive: let zone_stats = camera.region_stats(zone_id)?; if zone_stats.valid { println!("min={:.1} max={:.1} mean={:.1}", zone_stats.min_c, zone_stats.max_c, zone_stats.mean_c); }
Check stats.valid before reading a temperature. When it is false the statistics are quiet NaN rather than zero, deliberately, so a reading that was never taken cannot be plotted, averaged or compared against a limit by accident.
Other shapes: Region::Circle, Ellipse, Line, Polygon, Spline, ClosedSpline, Spot, Ring, and FromDrag for mouse-drawn areas.
Two regions compose with the members United(), Intersected() and Subtracted(). a.Subtracted(b) is "a, with b's area removed", so a ring is an outer circle with an inner one subtracted. They are members because the result takes its name, style, rules and children from the operand it is called on. The free Union(), Intersect() and Subtract() in region.h take a Composite, the bare geometry tree, not a Region: use those to build geometry rather than to combine two measuring areas.
A Line region measures the one pixel it passes through at each step along its length, including the pixels its two ends stop part-way inside. Before this was fixed a line collected every pixel within half a pixel of it: on sensors 320 pixels wide or more that made it two to three rows thick, and at some positions it measured nothing or counted a row twice. Line readings recorded before the fix on such cameras measured a band, not a line, and will differ.
Editing is in place and keeps the region's id, so alarms on it stay bound:
imager->Regions().Edit(id, [](Region &r) { r.SetCentre({0.6f, 0.4f}); });
optris_sdk_region *editing = NULL; if (optris_sdk_imager_copy_region(imager, id, &editing) == OPTRIS_SDK_OK) { optris_sdk_region_set_centre(editing, (optris_sdk_vec2){0.6F, 0.4F}); optris_sdk_imager_update_region(imager, id, editing); optris_sdk_region_free(editing); }
using Region editing = camera.GetRegion(regionId); editing.Centre = new Vector2(0.6f, 0.4f); camera.UpdateRegion(regionId, editing);
editing = camera.regions.copy(region_id) editing.centre = (0.6, 0.4) camera.regions.update(region_id, editing)
let mut editing = camera.region(region_id)?; editing.set_centre((0.6, 0.4))?; camera.update_region(region_id, &editing)?;
For a live display, read all of them at once:
for (const auto &state : imager->Regions().States()) { if (state.stats.valid) Draw(state.region_id, state.stats.max_c, state.alarm); }
optris_sdk_region_state all[32]; size_t count = 0; size_t i = 0; for (i = 0; i < 32; ++i) { optris_sdk_region_state_init(&all[i], sizeof(all[i])); } if (optris_sdk_imager_read_region_states(imager, all, 32, sizeof all[0], &count) == OPTRIS_SDK_OK) { for (i = 0; i < count && i < 32; ++i) { if (all[i].stats.valid) { Draw(all[i].region_id, all[i].stats.max_c, all[i].alarm); } } }
foreach (RegionState state in camera.ReadRegionStates()) { if (state.Stats.IsValid) { Draw(state.Id, state.Stats.Maximum, state.Alarm); } }
for state in camera.regions.states(): if state.stats.valid: draw(state.region_id, state.stats.max_c, state.alarm)
for state in camera.read_region_states()? { if state.stats.valid { draw(state.region_id, state.stats.max_c, state.alarm); } }
An alarm is a rule watching a signal. The signal can be a region statistic, camera telemetry, a PIF channel, a motion zone, or a value your application publishes; the machinery is the same for all of them.
Rule hot; hot.name = "over temp"; // The slot is filled in from the region id by the two-argument Add(). hot.input = SignalId::Region(0, 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.actions.push_back({ActionTrigger::kOnActivate, SnapshotAction{}}); const auto rule_id = imager->Alarms().Add(id, std::move(hot)); imager->Alarms().SetCallback([](const AlarmEvent &e) { std::println("[{}] {} -> {} at {:.1f} C", e.region_name, ToString(e.previous), ToString(e.current), e.value); });
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"); /* The slot is filled in from the region id by add_rule(). */ 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; optris_sdk_rule_set_condition(hot, &condition); optris_sdk_rule_add_snapshot_action(hot, OPTRIS_SDK_ACTION_ON_ACTIVATE, OPTRIS_SDK_SNAPSHOT_PNG, NULL, NULL, 0); optris_sdk_imager_add_rule(imager, id, hot, &rule_id); optris_sdk_rule_free(hot); optris_sdk_imager_set_alarm_callback(imager, OnAlarm, NULL);
var overTemp = new AlarmRule { Name = "over temp", // The slot is filled in from the region id by AddRule(id, rule). Input = SignalId.Region(SignalField.Max), Condition = AlarmCondition.Above(60.0f, hysteresis: 2.0f) with { Warning = new AlarmLimits { High = 55.0f }, OnDelay = TimeSpan.FromMilliseconds(100), }, }; overTemp.Actions.Add(new SnapshotAction()); ulong overTempId = camera.AddRule(regionId, overTemp);
over_temp = optris_sdk.Rule( name='over temp', # The slot is filled in from region_id by alarms.add(). 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)) over_temp.add_snapshot_action(trigger=optris_sdk.ON_ACTIVATE) over_temp_id = camera.alarms.add(over_temp, region_id=region_id) camera.alarms.on_alarm( lambda e: print(f'[{e.region_name}] ' f'{optris_sdk.state_name(e.previous)} -> ' f'{optris_sdk.state_name(e.current)} at ' f'{e.value:.1f} C'))
let mut over_temp = Rule::new()?; over_temp.set_name("over temp")?; // The slot is filled in from region_id by add_rule(). over_temp.set_input(SignalId::region(SignalField::Max))?; over_temp.set_condition( Condition::above(60.0, 2.0) .with_warning(Limits::above(55.0, 0.0)) .with_on_delay(Duration::from_millis(100)), )?; over_temp.add_snapshot_action(ActionTrigger::OnActivate, SnapshotFormat::Png, None, None, 0)?; let over_temp_id = camera.add_rule(region_id, &over_temp)?; camera.on_alarm(|e| { println!("[{}] {:?} -> {:?} at {:.1} C", e.region_name, e.previous, e.current, e.value); })?;
Note: MeasurementField, RoiAlarm and Imager::AddAlarmChannel() are removed from optris::sdk. Version 11 applications are unaffected. See Measurement Fields for the mapping.
Recording
There is no Recorder() sub-object in the four bindings: the C ABI puts the recording calls on the imager handle itself, so they hang off the camera. The pre-roll length is a Duration in Rust and .NET, seconds as a float in Python, and whole milliseconds in C, which is the ABI's own unit and where the other three narrow to.
auto &recorder = imager->Recorder(); // Pre-roll: keep the last 30 seconds in a ring buffer. recorder.EnablePreRoll(std::chrono::seconds(30)); // Start recording. If pre-roll is on, the buffer is flushed first. recorder.Start("/data/capture.mkv"); // ... later: recorder.Stop(); // When Stop() returns the file is complete and can be opened. bool recording = recorder.IsRecording();
/* `int`, not `bool`: the ABI's predicates write non-zero or zero. */ int recording = 0; /* Pre-roll: keep the last 30 seconds in a ring buffer. */ optris_sdk_imager_enable_pre_roll_ms(imager, 30000); /* Start recording. If pre-roll is on, the buffer is flushed first. */ optris_sdk_imager_start_recording(imager, "/data/capture.mkv"); /* ... later. When this returns the file is complete. */ optris_sdk_imager_stop_recording(imager); optris_sdk_imager_is_recording(imager, &recording);
// Pre-roll: keep the last 30 seconds in a ring buffer. camera.EnablePreRoll(TimeSpan.FromSeconds(30)); // Start recording. If pre-roll is on, the buffer is flushed first. camera.StartRecording("/data/capture.mkv"); // ... later. When this returns the file is complete. camera.StopRecording(); bool recording = camera.IsRecording;
# Pre-roll: keep the last 30 seconds in a ring buffer. Seconds, as a # float, like every duration on this surface. camera.enable_pre_roll(30.0) # A `with` block, because the thing that must happen on the way out is # stopping it. start_recording()/stop_recording() are there too. with camera.recording('/data/capture.mkv') as run: pass # When the block exits the file is complete and the totals are final. print(run.stats.frames_written, 'written', run.stats.frames_lost, 'lost') recording = camera.is_recording
// Pre-roll: keep the last 30 seconds in a ring buffer. camera.enable_pre_roll(Duration::from_secs(30))?; // Start recording. If pre-roll is on, the buffer is flushed first. camera.start_recording("/data/capture.mkv")?; // ... later. When this returns the file is complete. camera.stop_recording()?; let recording = camera.is_recording()?;
Start(path, duration) records for a fixed time and stops by itself. SaveSnapshot(path, format) writes the latest frame as a still image; SnapshotFormat is a plain enum with one of kPng, kTiff, kCsv and kJpeg, not a set of flags to be combined. StartIntervalCapture() writes one at a fixed interval.
A recording is laid out so an ordinary media player opens it: track one is a colorized placard carrying a notice and a QR code, one picture repeated so a player keeps showing it; track two is the measurement (FFV1 GRAY16LE, AV_DISPOSITION_DEFAULT); behind them sit the per-frame telemetry text track, the otc-meta.json attachment and a cover.jpg. What a third party may rely on states which of those properties a third-party reader may rely on and which are incidental. The short rule: find the measurement by its role tag, never as "stream 0" or "the only video stream".
Playback
Player is a FrameSource but not an Imager: it has frames, palettes, regions and alarms, and no shutter, focus or network. Regions and rules on a player behave exactly as on a live camera.
There is no separate Player type in the four bindings. The C ABI opens a recording as an optris_sdk_imager (optris_sdk_imager_create_from_file), so a replay is the same handle a camera is, and the playback calls are on it. That is what lets one loop be written against live and recorded data alike; is_playback / IsPlayback is how the two are told apart, and what only hardware can do is refused by name rather than faked.
auto player = optris::sdk::Player::Open("/data/capture.mkv"); // IoException on failure player->SetLoop(true); player->SetSpeed(2.0f); player->SetThermalCallback( [](const optris::sdk::ThermalFrame &f) { // A recording keeps the mark on the frames from before the camera's // startup calibration had finished. They are not measurements. if (!f.GetMetadata().thermal_data_reliable) return; std::println("Playback: max={:.1f} C", f.GetMaxTemperature()); }); player->Start(); // Seek. player->SeekToFrame(0); player->SeekToTimestamp(5'000'000); // Microseconds. std::println("{} / {} us", player->GetPositionUs(), player->GetDurationUs());
optris_sdk_imager *player = NULL; uint64_t position_us = 0; uint64_t duration_us = 0; /* A recording is an imager handle, not a second type. */ if (optris_sdk_imager_create_from_file(imager_path, &player) != OPTRIS_SDK_OK) { fprintf(stderr, "%s\n", optris_sdk_last_error_message()); return 1; } optris_sdk_imager_set_playback_loop(player, true); optris_sdk_imager_set_playback_speed(player, 2.0F); optris_sdk_imager_set_thermal_callback(player, OnThermalFrame, NULL); optris_sdk_imager_start(player); /* Seek. */ optris_sdk_imager_seek_to_frame(player, 0); optris_sdk_imager_seek_to_timestamp(player, 5000000); /* microseconds */ optris_sdk_imager_get_playback_position_us(player, &position_us); optris_sdk_imager_get_playback_duration_us(player, &duration_us); printf("%llu / %llu us\n", (unsigned long long)position_us, (unsigned long long)duration_us); optris_sdk_imager_destroy(player);
await using ThermalCamera player = ThermalCamera.OpenRecording("/data/capture.mkv"); player.IsLooping = true; player.PlaybackSpeed = 2.0f; player.Start(); // Seek. player.SeekToFrame(0); player.SeekTo(TimeSpan.FromSeconds(5)); Console.WriteLine($"{player.PlaybackPosition} / {player.PlaybackDuration}");
with optris_sdk.Camera.open_recording('/data/capture.mkv') as player: player.is_looping = True player.playback_speed = 2.0 player.start() # Seek. player.seek_to_frame(0) player.seek_to_timestamp(5.0) # seconds, as a float print(player.playback_position_s, '/', player.playback_duration_s, 's')
// from_file(), not open_recording(): a recording IS an imager handle, // and the name says where the frames come from rather than what they // are called. let mut player = Camera::from_file("/data/capture.mkv")?; player.set_loop(true)?; player.set_playback_speed(2.0)?; player.start()?; // Seek. player.seek_to_frame(0)?; player.seek_to_timestamp_us(5_000_000)?; // microseconds println!("{} / {} us", player.playback_position_us()?, player.playback_duration_us()?);
Pause(), Resume() and IsPaused() hold the position without stopping.
Player::Display() gives a recording the same colour windows a camera has, with two exceptions it reports rather than hides: ColorWindow::motion_only is refused, because a replay runs no motion differencing, and a picture recording (one written as colorized video) supports none of them at all. Ask Display().AreColorWindowsSupported(); it answers rather than failing, and the answer must not be cached across an upgrade. IsPicture() is answered from the stream header at Open(), so it is valid before playback starts.
GetRecordedRender() says what the colours meant when the file was written, and Player opens a recording on that palette and auto-scale mode when the file records them. GetAttachments() and ReadAttachments(path) get back files the recording carries; the static Player::ReadAttachments(path) reads them without opening the recording as a source.
Ask whether the file states a thing before believing what it reports. GetRadiation() and GetConfig() hand back plain structs, so a recording that never named an emissivity reads back as 1.0 and one that never named a range reads back as −20..100 °C: in both cases a plausible value that nobody recorded. HasRadiation() and HasTemperatureRange() separate "the file says so" from "that is the struct's default", and both are false for a v11 file and for a file from another writer. Test HasTemperatureRange() before drawing a scale bar against the range.
Opening a snapshot
A still written by this SDK carries temperatures and the settings they were computed at, so it can be measured after the fact:
using namespace optris::sdk; auto still = StillSource::Open("capture.png"); // IoException on failure const uint64_t id = still->Regions().Add(Region::Rect({0.4F, 0.4F}, {0.2F, 0.2F})); still->Refresh(); std::println("{:.1f} C", still->Regions().Get(id)->stats.max_c);
optris_sdk_imager *still = NULL; optris_sdk_region *area = NULL; optris_sdk_region_stats stats; uint64_t area_id = 0; optris_sdk_still_open("capture.png", &still); optris_sdk_region_create_rect((optris_sdk_vec2){0.4F, 0.4F}, (optris_sdk_vec2){0.2F, 0.2F}, 0.0F, &area); optris_sdk_imager_add_region(still, area, &area_id); optris_sdk_region_free(area); /* One frame, delivered once and synchronously. */ optris_sdk_still_refresh(still); optris_sdk_region_stats_init(&stats, sizeof(stats)); optris_sdk_imager_get_region_stats(still, area_id, &stats); printf("%.1f C\n", (double)stats.max_c); optris_sdk_imager_destroy(still);
using ThermalCamera still = ThermalCamera.OpenStill("capture.png"); using Region area = Region.Rect(new Vector2(0.4f, 0.4f), new Vector2(0.2f, 0.2f)); ulong areaId = still.AddRegion(area); still.Refresh(); Console.WriteLine($"{still.GetRegionStats(areaId).Maximum:F1} C");
with optris_sdk.Camera.open_still('capture.png') as still: area = optris_sdk.Region.rect((0.4, 0.4), (0.2, 0.2)) area_id = still.regions.add(area) still.refresh() print(f'{still.regions.stats(area_id).max_c:.1f} C')
let mut still = Camera::open_still("capture.png")?; let area = Region::rect((0.4, 0.4), (0.2, 0.2), 0.0)?; let area_id = still.add_region(&area)?; still.refresh_still()?; println!("{:.1} C", still.region_stats(area_id)?.max_c);
StillSource is a FrameSource, so regions, alarms, palettes and colour scaling behave as they do on a camera. It has one frame, delivered repeatedly while it is running, so FrameSource code needs no special case; Refresh() delivers it once, synchronously, which is what a program that is not streaming should use. The format is detected from the file's content, not its extension. GetPath() and GetMetadata() return the file and the whole metadata document it carries.
A raw-ADU or energy still holds uncalibrated counts with no radiometric model beside them, so Open() rejects it by name. Use rec::Snapshot::LoadRaw() for the counts.
ApplyConfig() changes the global emissivity, the same knob as on a camera: the energy-to-temperature table is rebuilt from the calibration the file carries, by the camera's own TempTable, and every pixel is re-derived through it. Verified entry for entry against a live backend on a real PI 640i. Asking for the value the file was saved at restores the saved pixels exactly. A still with no radiometry.otc attachment refuses it by name, and the temperature range is refused always: a different range is a different calibration the file does not carry.
The global knob and a region's own emissivity are different arithmetic and can differ by several kelvin at low emissivity (0.40 K at 0.90, 6.9 K at 0.50 on a +40.7 K correction). That is the camera's behaviour, reproduced.
A region's own emissivity is applied when the file carries the camera's characteristic curve, which the SDK writes into every still it saves from a camera that has one. StillSource::HonoursRegionEmissivity() answers for the file in hand.
| The file | The region reads at | Badged |
|---|---|---|
| carries the curve | what the camera would have reported, resolved through the same object a live camera uses | RegionEmissivityState::kReadingOnly: the numbers carry it, the picture does not, because a still has no pipeline behind it |
| does not | the camera's emissivity, with a warning naming it | kCameras |
The camera's emissivity, the one every pixel in the file was computed at, is in GetRadiation() either way.
Camera control
Process interface
GetPif() returns the camera's pif::PifController. Every physical camera returns a controller, whether or not anything was detected on the connector; detection is advisory, and SetIdentity() declares a PIF that detection missed. nullptr means there is no hardware at all: a simulated camera or a recording.
A refused PIF request throws pif::PifException, like every other failure in the C++ API, and its code() says which refusal it was: an index the hardware does not have, a PIF that is not attached, a value that is not a finite number. A polling loop still does not have to catch. Reading an input before the first frame has brought one is a reading rather than a refusal (DigitalState::Unknown for a digital input, NaN for an analog one), so a loop over a working interface never throws:
The other languages report a PIF refusal the way they report everything else: a status in C, an exception in C# and Python, and an Err in Rust. A simulated camera and a recording have no PIF at all and say so: nullptr in C++, OPTRIS_SDK_ERROR_NOT_SUPPORTED in C, and an exception or Err elsewhere.
auto pif = imager->GetPif(); if (!pif) { std::println("No camera behind this imager."); return; } const auto &info = pif->GetHardwareInfo(); std::println("PIF: {} DI, {} DO, {} AI, {} AO", info.digital_input_count, info.digital_output_count, info.analog_input_count, info.analog_output_count); // Set a digital output. A refused request throws. try { pif->WriteDigitalOutput(0, optris::sdk::pif::DigitalState::High); } catch (const optris::sdk::pif::PifException &e) { std::println(stderr, "DO0: {}", e.what()); } // Read an analog input: NaN until the first frame has brought one. std::println("AI0 = {}", pif->ReadAnalogInput(0));
optris_sdk_pif *pif = NULL; optris_sdk_pif_hardware_info info; float voltage = 0.0F; /* acquire, not get: the handle is yours and is freed below. */ if (optris_sdk_imager_acquire_pif(imager, &pif) != OPTRIS_SDK_OK) { printf("No camera behind this imager.\n"); return; } optris_sdk_pif_hardware_info_init(&info, sizeof(info)); optris_sdk_pif_get_hardware_info(pif, &info); printf("PIF: %u DI, %u DO, %u AI, %u AO\n", (unsigned)info.digital_input_count, (unsigned)info.digital_output_count, (unsigned)info.analog_input_count, (unsigned)info.analog_output_count); /* Set a digital output. */ if (optris_sdk_pif_write_digital_output(pif, 0, OPTRIS_SDK_DIGITAL_HIGH) != OPTRIS_SDK_OK) { fprintf(stderr, "DO0: %s\n", optris_sdk_last_error_message()); } /* Read an analog input. */ if (optris_sdk_pif_read_analog_input(pif, 0, &voltage) == OPTRIS_SDK_OK) { printf("AI0 = %f\n", (double)voltage); } optris_sdk_pif_free(pif);
using ProcessInterface pif = camera.OpenProcessInterface(); PifHardwareInfo info = pif.Hardware; Console.WriteLine($"PIF: {info.DigitalInputCount} DI, " + $"{info.DigitalOutputCount} DO, " + $"{info.AnalogInputCount} AI, " + $"{info.AnalogOutputCount} AO"); // Set a digital output. pif.WriteDigitalOutput(0, DigitalState.High); // Read an analog input. Console.WriteLine($"AI0 = {pif.ReadAnalogInput(0)}");
pif = camera.pif() info = pif.hardware_info() print(f'PIF: {info.digital_input_count} DI, ' f'{info.digital_output_count} DO, ' f'{info.analog_input_count} AI, ' f'{info.analog_output_count} AO') # Set a digital output. pif.write_digital_output(0, optris_sdk.DIGITAL_HIGH) # Read an analog input. print('AI0 =', pif.read_analog_input(0))
let mut pif = camera.process_interface()?; let info = pif.hardware_info()?; println!("PIF: {} DI, {} DO, {} AI, {} AO", info.digital_input_count, info.digital_output_count, info.analog_input_count, info.analog_output_count); // Set a digital output. pif.write_digital_output(0, DigitalState::High)?; // Read an analog input. println!("AI0 = {}", pif.read_analog_input(0)?);
A channel carries no meaning until Configure() gives it a purpose. Poll() reads, decodes and dispatches inputs to the handler set with OnDecodedInput(). To react to a PIF value, use an alarm rule on SignalId::Pif(...). examples/cpp/process_interface/pif_info.cc is the compiled version. Process Interface (PIF) is the full chapter.
Error handling
All SDK exceptions derive from SdkException. Error Handling has the whole hierarchy, which calls throw what, and the calls that validate with std::invalid_argument instead, so catch (const SdkException&) alone does not cover everything.
Two of them an open meets first:
| Exception | Carries |
|---|---|
ConnectTimeoutException |
a DeviceException: the camera did not answer within the connection timeout |
DeviceBusyException |
a DeviceException: the operation was refused and may succeed next time. Raised by an open refused on a claim, by an open whose stream would not start in its video format, and by an operation-mode switch whose format change fails. reason() says which, as a closed enum, and one of its values means nothing holds the camera, so it must not be shown as in use. detail() carries the holder and the claim file, and is empty when they cannot be named |
Non-fatal errors are raised on the SDK's threads, where a caller's try/catch cannot reach them. Register an error callback for those:
Note: The four bindings do not share C++'s exception hierarchy, and two do not have one at all. C returns a status from every entry point and has optris_sdk_last_error_message() for the text, per thread, so read it into a local before calling anything else. Rust has one error type carrying a Status, so there is no order of catch clauses to get right: match on the status. .NET and Python do have hierarchies, with their own names: ThermalDeviceException and DeviceError where C++ says DeviceException.
#include "optris/sdk.h" #include <chrono> #include <print> int main() { try { optris::sdk::ImagerConfig config; config.serial = "12345678"; auto imager = optris::sdk::Imager::Create(config); imager->SetErrorCallback( [](const std::string &msg) { std::println(stderr, "Non-fatal: {}", msg); }); imager->Start(); auto frame = imager->AcquireFrame(std::chrono::milliseconds{5000}); // Frames from before the startup calibration has finished arrive // too, and are not measurements. while (!frame.GetMetadata().thermal_data_reliable) frame = imager->AcquireFrame(std::chrono::milliseconds{5000}); std::println("Max: {:.1f} C", frame.GetMaxTemperature()); imager->Stop(); } catch (const optris::sdk::DeviceException &e) { std::println(stderr, "Device error: {}", e.what()); if (!e.serial().empty()) std::println(stderr, " Serial: {}", e.serial()); return 1; } catch (const optris::sdk::CalibrationException &e) { std::println(stderr, "Calibration: {}", e.what()); return 1; } catch (const optris::sdk::CaptureException &e) { std::println(stderr, "Capture: {}", e.what()); return 1; } catch (const optris::sdk::SdkException &e) { std::println(stderr, "SDK error: {}", e.what()); return 1; } }
#include "optris/sdk_c.h" #include <stdio.h> int main(void) { optris_sdk_imager *imager = NULL; optris_sdk_imager_options options; optris_sdk_frame *frame = NULL; optris_sdk_frame_info info; optris_sdk_status status = OPTRIS_SDK_OK; optris_sdk_imager_options_init(&options, sizeof(options)); /* There is nothing to catch: every entry point returns a status, and * optris_sdk_last_error_message() describes the last failure ON THIS * THREAD. Read it into a local before calling anything else -- C * does not define the order a function's arguments are evaluated. */ status = optris_sdk_imager_create_with_options("12345678", &options, &imager); if (status != OPTRIS_SDK_OK) { fprintf(stderr, "%s: %s\n", optris_sdk_status_name(status), optris_sdk_last_error_message()); return 1; } optris_sdk_imager_set_error_callback(imager, OnError, NULL); optris_sdk_imager_start(imager); /* Frames from before the startup calibration has finished arrive * too, and are not measurements. */ while (optris_sdk_imager_acquire_frame(imager, 5000, &frame) == OPTRIS_SDK_OK) { optris_sdk_frame_info_init(&info, sizeof(info)); optris_sdk_frame_get_info(frame, &info); if (info.thermal_data_reliable) { printf("Max: %.1f C\n", (double)info.max_temp_c); } optris_sdk_frame_free(frame); if (info.thermal_data_reliable) { break; } } optris_sdk_imager_stop(imager); optris_sdk_imager_destroy(imager); return 0; }
using Optris.Sdk; try { // There is no open-by-serial overload: find the device and open // it. CameraOptions carries the timeouts and the calibration // directory, not an identity. DeviceInfo device = Sdk.EnumerateDevices() .First(d => d.Serial == "12345678"); await using ThermalCamera camera = ThermalCamera.Open(device); camera.Start(); // Frames from before the startup calibration has finished arrive // too, and are not measurements. ThermalFrame first = await camera.AcquireFrameAsync(TimeSpan.FromSeconds(5)); while (!first.Metadata.IsThermalDataReliable) { first.Dispose(); first = await camera.AcquireFrameAsync(TimeSpan.FromSeconds(5)); } using (first) { Console.WriteLine($"Max: {first.MaxTemperature:F1} C"); } camera.Stop(); } catch (ThermalDeviceException e) { // No Serial on the exception: it carries Status, and // DeviceBusyException adds Reason, Holder and ClaimPath. Console.Error.WriteLine($"Device error: {e.Message}"); } catch (CalibrationException e) { Console.Error.WriteLine($"Calibration: {e.Message}"); } catch (FrameCaptureException e) { Console.Error.WriteLine($"Capture: {e.Message}"); } catch (OptrisSdkException e) { Console.Error.WriteLine($"SDK error: {e.Message}"); }
import optris_sdk try: with optris_sdk.Camera.open(serial='12345678') as camera: camera.start() # Frames from before the startup calibration has finished # arrive too, and are not measurements. first = camera.acquire(5000) while not first.thermal_data_reliable: first = camera.acquire(5000) print(f'Max: {first.max_c:.1f} C') camera.stop() except optris_sdk.DeviceError as exc: # exc.status is the raw code and exc.status_name its spelling. print(f'Device error [{exc.status_name}]: {exc}') except optris_sdk.TimeoutError as exc: print(f'Capture: {exc}') except optris_sdk.SdkError as exc: print(f'SDK error: {exc}')
use optris_sdk::{Camera, Status}; fn main() -> optris_sdk::Result<()> { // There is no open-by-serial entry point: find the device and open // it, which is what the shipped examples do. let Some(device) = optris_sdk::enumerate()? .into_iter() .find(|d| d.serial == "12345678") else { eprintln!("no camera 12345678 attached"); return Ok(()); }; // One error type, carrying a Status. There is no hierarchy to // catch in order; match on the status instead. match Camera::open_device(&device) { Ok(mut camera) => { let _ = camera.start(); } Err(e) if e.status() == Status::Device => { eprintln!("Device error: {e}"); } Err(e) if e.status() == Status::Calibration => { eprintln!("Calibration: {e}"); } Err(e) => eprintln!("SDK error: {e}"), } Ok(()) }
Device enumeration
Warning: Enumerating is not a read. On Linux the sweep opens every attached camera to read its descriptors, so it is a group of fragments here rather than samples: the machine that gates this manual has cameras on it, and a sample is run.
#include "optris/sdk.h" #include <print> int main() { // Cameras on the local buses. Network cameras are not included // unless asked for. auto devices = optris::sdk::EnumerateDevices(); // With options: include network and simulated. optris::sdk::EnumerationOptions opts; opts.include_network = true; opts.include_simulated = true; auto all = optris::sdk::EnumerateDevices(opts); for (const auto &dev : all) { std::println("{} S/N {} {} ({}x{} @ {} Hz)", dev.model, dev.serial, optris::sdk::ConnectionTypeToString(dev.connection), dev.width, dev.height, dev.frame_rate); } // Create an imager from an enumerated device. if (!all.empty()) { auto imager = optris::sdk::Imager::Create(all[0]); } }
#include "optris/sdk_c.h" #include <stdio.h> int main(void) { optris_sdk_device_info devices[16]; optris_sdk_enumeration_options options; optris_sdk_imager *imager = NULL; size_t count = 0; size_t i = 0; for (i = 0; i < 16; ++i) { optris_sdk_device_info_init(&devices[i], sizeof(devices[i])); } /* With options: include network and simulated. NULL options is the * local buses only. */ optris_sdk_enumeration_options_init(&options, sizeof(options)); options.include_network = 1; options.include_simulated = 1; optris_sdk_enumerate_devices(&options, devices, 16, sizeof devices[0], &count); for (i = 0; i < count && i < 16; ++i) { printf("%s S/N %s (%ux%u)\n", devices[i].model, devices[i].serial, (unsigned)devices[i].width, (unsigned)devices[i].height); } /* Create an imager from an enumerated device. */ if (count > 0) { optris_sdk_imager_create_from_device(&devices[0], &imager); optris_sdk_imager_destroy(imager); } return 0; }
using Optris.Sdk; // Cameras on the local buses. Network cameras are not included unless // asked for. IReadOnlyList<DeviceInfo> devices = Sdk.EnumerateDevices(); // With options: include network and simulated. Written in full, because // a project with implicit usings also imports System.IO.EnumerationOptions. IReadOnlyList<DeviceInfo> all = Sdk.EnumerateDevices(new Optris.Sdk.EnumerationOptions { IncludeNetwork = true, IncludeSimulated = true, }); foreach (DeviceInfo dev in all) { // No frame rate on DeviceInfo: the rate a camera will run at // depends on the operation mode, so enumeration reports the // geometry and Capabilities.MaxFrameRate reports the ceiling. Console.WriteLine($"{dev.Model} S/N {dev.Serial} {dev.Connection} " + $"({dev.Width}x{dev.Height}, up to " + $"{dev.Capabilities.MaxFrameRate} Hz)"); } // Open an enumerated device. if (all.Count > 0) { await using ThermalCamera camera = ThermalCamera.Open(all[0]); }
import optris_sdk # Cameras on the local buses. Network cameras are not included unless # asked for. devices = optris_sdk.enumerate_devices() # With options: include network and simulated. options = optris_sdk.EnumerationOptions(include_network=True, include_simulated=True) for dev in optris_sdk.enumerate_devices(options): print(f'{dev.model} S/N {dev.serial} ' f'{optris_sdk.connection_name(dev.connection)} ' f'({dev.width}x{dev.height} @ {dev.frame_rate} Hz)') # Open an enumerated device. if devices: with optris_sdk.Camera.open(devices[0]) as camera: pass
use optris_sdk::{Camera, EnumerationOptions, enumerate, enumerate_with}; fn main() -> optris_sdk::Result<()> { // Cameras on the local buses. Network cameras are not included // unless asked for. let devices = enumerate()?; // With options: include network and simulated. let options = EnumerationOptions::new() .include_network(true) .include_simulated(true); for dev in enumerate_with(&options)? { println!("{} S/N {} ({}x{})", dev.model, dev.serial, dev.width, dev.height); } // Open an enumerated device. if let Some(first) = devices.first() { let _camera = Camera::open_device(first)?; } Ok(()) }
Network discovery is a broadcast and does not cross a router. ProbeNetworkDevice() asks one address directly without opening the camera.
In C#, write Optris.Sdk.EnumerationOptions in full, or add using EnumerationOptions = Optris.Sdk.EnumerationOptions; at the top of the file. A project made from the default .NET templates has implicit usings switched on, which imports System.IO and with it System.IO.EnumerationOptions, so new EnumerationOptions { ... } after using Optris.Sdk; does not compile (error CS0104, an ambiguous reference). Code inside a namespace of its own under Optris.Sdk is not affected.
EnumerateDevices() blocks, and with include_network set it blocks for network_discovery_timeout, 3 seconds by default. To keep a sweep off a user-interface thread, run it on a thread of your own. There is no callback-based form and no need for one: the result is a std::vector<DeviceInfo> returned by value, so a std::jthread that enumerates and posts the vector is the whole solution. Device enumeration has it written out.
For arrivals and departures rather than one sweep:
optris::sdk::StartHotplugMonitor( [](const optris::sdk::DeviceInfo &dev, bool added) { std::println("{} {} S/N {}", added ? "+" : "-", dev.model, dev.serial); });
optris_sdk_start_hotplug_monitor(OnHotplug, NULL);
await foreach (DeviceChange change in Sdk.WatchDevicesAsync(CancellationToken.None)) { Console.WriteLine($"{change.Kind} {change.Device.Model} " + $"S/N {change.Device.Serial}"); }
def on_change(device, added): print('+' if added else '-', device.model, 'S/N', device.serial) with optris_sdk.hotplug_monitor(on_change): pass
let _monitor = optris_sdk::hotplug::HotplugMonitor::start(|dev, added| { println!("{} {} S/N {}", if added { "+" } else { "-" }, dev.model, dev.serial); })?;
StartHotplugMonitor() is USB only and stays that way: it takes no options, so it has nowhere to put the poll interval that watching a network needs. StartDeviceMonitor() takes options, owns its thread, and adds two things to the same arrivals and removals:
watch_claims:kClaimedandkReleased, for every claim including this process's own. ReadDeviceInfo::claimed_by_this_processto tell them apart.watch_network: cameras on the network, which the monitor does not report at all without it. A camera appears up to onenetwork_poll_intervalafter it is powered and leaves two intervals after it stops answering, and the broadcast reaches the local network segment only. UseProbeNetworkDevice()for a camera behind a router. See Device enumeration.
Camera settings
The range is two whole degrees across the ABI, so the four bindings carry a pair rather than C++'s record; extended and high_precision are their own calls there.
auto range = imager->GetTemperatureRange(); // min_c, max_c, extended, high_precision for (const auto &[lo, hi] : imager->GetDeviceInfo().available_ranges) { std::println("{}..{} C", lo, hi); } // A range change is a mode change and reloads the calibration. // Throws ConfigException for a range this camera does not offer. imager->SetTemperatureRange({.min_c = 150, .max_c = 900});
int32_t low = 0; int32_t high = 0; int32_t span_low = 0; int32_t span_high = 0; size_t range_count = 0; size_t i = 0; optris_sdk_imager_get_temperature_range(imager, &low, &high); /* Count first, then one call per entry: the ABI has no array reader * for this one. */ optris_sdk_imager_get_available_temperature_range_count(imager, &range_count); for (i = 0; i < range_count; ++i) { optris_sdk_imager_get_available_temperature_range(imager, i, &span_low, &span_high); printf("%d..%d C\n", (int)span_low, (int)span_high); } /* A range change is a mode change and reloads the calibration, and * returns OPTRIS_SDK_ERROR_CONFIGURATION for one the camera does not * offer. */ optris_sdk_imager_set_temperature_range(imager, 150, 900);
TemperatureRange active = camera.TemperatureRange; foreach (TemperatureRange span in camera.GetAvailableTemperatureRanges()) { Console.WriteLine($"{span.Minimum}..{span.Maximum} C"); } // A range change is a mode change and reloads the calibration, and // throws for a range this camera does not offer. camera.TemperatureRange = new TemperatureRange(150, 900);
low, high = camera.temperature_range for span_low, span_high in camera.available_temperature_ranges(): print(f'{span_low}..{span_high} C') # A range change is a mode change and reloads the calibration, and # raises for a range this camera does not offer. camera.temperature_range = (150, 900)
let (low, high) = camera.temperature_range()?; for (span_low, span_high) in camera.available_temperature_ranges()? { println!("{span_low}..{span_high} C"); } // A range change is a mode change and reloads the calibration, and is // Err for a range this camera does not offer. camera.set_temperature_range(150, 900)?;
TemperatureRange::extended (off by default) and high_precision (on by default, as in v11) both rebuild the energy-to-temperature table. Both are camera-wide requests; what the active mode can act on is OperationMode::extendable, high_precision_available and the extended_temp_min/extended_temp_max pair. High precision does not change the 0.1 °C step size the SDK reports, see Operation Modes.
const auto &modes = imager->GetDeviceInfo().operation_modes; for (const auto &m : modes) { // The unit comes from the mode, not from an assumption: the same // number is degrees on one optic and millimetres on another. const char *unit = m.optics_unit == optris::sdk::OpticsUnit::kMillimetres ? "mm" : "deg"; std::println("{} {} {}..{} C {}x{} @ {} Hz", m.optics_fov, unit, m.temp_min, m.temp_max, m.width, m.height, m.framerate); } imager->SetOperationMode(modes[0]); auto active = imager->GetOperationMode();
optris_sdk_operation_mode modes[16]; size_t mode_count = 0; size_t i = 0; const char *unit = NULL; for (i = 0; i < 16; ++i) { optris_sdk_operation_mode_init(&modes[i], sizeof(modes[i])); } if (optris_sdk_imager_read_operation_modes(imager, modes, sizeof modes[0], 16, &mode_count) == OPTRIS_SDK_OK) { for (i = 0; i < mode_count && i < 16; ++i) { /* The unit comes from the mode, not from an assumption. */ unit = modes[i].optics_unit == OPTRIS_SDK_OPTICS_UNIT_MILLIMETRES ? "mm" : "deg"; printf("%d %s %.0f..%.0f C %ux%u @ %u Hz\n", (int)modes[i].optics_fov, unit, (double)modes[i].temp_min_c, (double)modes[i].temp_max_c, (unsigned)modes[i].width, (unsigned)modes[i].height, (unsigned)modes[i].framerate); } if (mode_count > 0) { optris_sdk_imager_set_active_operation_mode(imager, &modes[0]); } }
IReadOnlyList<OperationMode> modes = camera.OperationModes; foreach (OperationMode m in modes) { // The unit comes from the mode, not from an assumption. string unit = m.FieldOfViewUnit == OpticsUnit.Millimetres ? "mm" : "deg"; Console.WriteLine($"{m.FieldOfView} {unit} " + $"{m.MinimumTemperature:F0}.." + $"{m.MaximumTemperature:F0} C " + $"{m.Width}x{m.Height} @ {m.FrameRate} Hz"); } camera.ActiveOperationMode = modes[0]; OperationMode activeMode = camera.ActiveOperationMode;
modes = camera.operation_modes() for m in modes: # The unit comes from the mode, not from an assumption. unit = 'mm' if m.optics_unit == optris_sdk.OPTICS_UNIT_MILLIMETRES \ else 'deg' print(f'{m.optics_fov} {unit} {m.temp_min_c:.0f}..' f'{m.temp_max_c:.0f} C {m.width}x{m.height} @ ' f'{m.framerate} Hz') camera.operation_mode = modes[0] active_mode = camera.operation_mode
let modes = camera.operation_modes()?; for m in &modes { // OpticsUnit::symbol() is the unit, from the mode rather than from // an assumption. println!("{} {} {:.0}..{:.0} C {}x{} @ {} Hz", m.optics_fov, m.optics_unit.symbol(), m.temp_min_c, m.temp_max_c, m.width, m.height, m.framerate); } camera.set_operation_mode(&modes[0])?; let active_mode = camera.active_operation_mode()?;
The radiation parameters are a whole-record setter too, so read, change and write back:
auto radiation = imager->Radiometry().Get(); radiation.emissivity = 0.95f; radiation.transmissivity = 1.0f; radiation.ambient_temp_c = 22.0f; // Also the reflected temperature. imager->Radiometry().Set(radiation);
optris_sdk_radiation_config radiation; optris_sdk_radiation_config_init(&radiation, sizeof(radiation)); optris_sdk_imager_get_radiation(imager, &radiation); radiation.emissivity = 0.95F; radiation.transmissivity = 1.0F; radiation.ambient_temperature_c = 22.0F; /* also the reflected one */ optris_sdk_imager_set_radiation(imager, &radiation);
camera.Radiation = camera.Radiation with { Emissivity = 0.95f, Transmissivity = 1.0f, // Also the reflected temperature. AmbientTemperature = 22.0f, };
radiation = camera.radiometry.get() radiation.emissivity = 0.95 radiation.transmissivity = 1.0 # One value, used as the reflected reference too. radiation.ambient_temperature_c = 22.0 camera.radiometry.set(radiation)
let mut radiation = camera.radiation()?; radiation.emissivity = 0.95; radiation.transmissivity = 1.0; // One value, used as the reflected reference too. radiation.ambient_temperature_c = 22.0; camera.set_radiation(radiation)?;
There is one ambient value, used also as the reflected temperature. There are no separate reflected-temperature, distance or humidity settings. With estimate_ambient = true the camera estimates ambient from its housing probe and GetEffectiveAmbientTemperature() reports the value in use, while Get() keeps reporting the configured number in either mode. A value written while the camera is estimating is kept, and comes back into force when estimation is turned off. Radiometry().Sources() says whether emissivity and ambient come from the SDK or from a PIF input.
Radiometry().TemperatureAtEmissivity() re-evaluates a reading you already have at another emissivity without disturbing the camera. Ask GetEmissivityConversionSupport() first: a nullopt from it is a refusal, not a conversion that made no difference. Thermal Measurement Basics covers what these three parameters mean and what gets them wrong.
// Read first: this is a whole-record setter, so a default-constructed // record writes defaults over every setting you did not think about, // the shutter forecast included. auto nuc = imager->Detector().GetAuto(); nuc.enabled = true; nuc.min_interval_secs = 30.0f; nuc.max_interval_secs = 300.0f; // How far any internal probe may drift before a correction is due, // checked once min_interval_secs has elapsed. Default 0.1. nuc.temp_drift_threshold_c = 0.5f; imager->Detector().SetAuto(nuc); // Manual trigger. This is the correction: on this hardware a // non-uniformity correction is a shutter cycle and there is no other. imager->Detector().TriggerShutter();
/* No record here: every field is an argument, in SECONDS as a float. * 0 on one of the three reads as "keep what is in force", which is why * .NET and Python take an optional rather than a number. */ optris_sdk_imager_set_auto_nuc(imager, 1, 30.0F, 300.0F, /* how far any internal probe may drift * before a correction is due; default * 0.1 */ 0.5F); /* Manual trigger. This is the correction: on this hardware a * non-uniformity correction is a shutter cycle and there is no other. */ optris_sdk_imager_trigger_shutter(imager);
// Each argument is optional, and null means "leave it alone". The // binding checks that, because by the time the call crosses the ABI // null and 0 are indistinguishable and the ABI reads 0 as "keep". camera.SetAutoCorrection(enabled: true, minimumInterval: TimeSpan.FromSeconds(30), maximumInterval: TimeSpan.FromSeconds(300), // How far any internal probe may drift before // a correction is due. Default 0.1. temperatureDrift: 0.5f); // Manual trigger. On this hardware a non-uniformity correction is a // shutter cycle and there is no other. camera.TriggerShutter();
# set_auto_nuc() takes the fields you mean by keyword and leaves the # rest where they are, so there is no whole-record read to do first. camera.detector.set_auto_nuc(enabled=True, min_interval_s=30.0, max_interval_s=300.0, # How far any internal probe may drift # before a correction is due. Default 0.1. temp_drift_threshold_c=0.5) # Manual trigger. On this hardware a non-uniformity correction is a # shutter cycle and there is no other. camera.detector.trigger_shutter()
// Every field is an argument, so there is no whole-record read to do // first; None leaves one where it is. // Seconds as f32, the ABI's own unit; 0.0 on one of the three reads as // "keep what is in force". camera.set_auto_nuc(true, 30.0, 300.0, // How far any internal probe may drift before a // correction is due. Default 0.1. 0.5)?; // Manual trigger. On this hardware a non-uniformity correction is a // shutter cycle and there is no other. camera.trigger_shutter()?;
The 30 and 300 above are this example's choice, not the defaults: a camera runs a 12-second minimum with no ceiling. Until something calls SetAuto(), a freshly opened camera runs on the engine's own schedule. GetTelemetry() reports nuc_status and flag_open. Read optris::sdk::AutoNucConfig in full before changing any of it: drift_filter_secs and drift_band_steps carry the measured account of why a settled camera still corrects every twelve seconds, what to set instead, and the one case where setting it makes things worse.
Detector().SetChipHeating() stabilises the detector at a fixed temperature. Heating is a property of the optic, not the camera: on an optic that must not be heated (the G7, for instance) kAuto and kFixed throw FeatureNotSupportedException and kFloating is the only mode, while the same camera on another optic heats.
Distortion and size-of-source correction are both on by default, matching v11:
These are three separate settings in the ABI rather than one record, so the four bindings set them one at a time.
auto p = imager->Processing().Get(); p.rdc = optris::sdk::RdcMode::kNormal; // kOff, kNormal (default), kWide p.sos_correction = true; // default p.sos_strength = 0.3f; // default 0: see below imager->Processing().Set(p); // What is actually happening, as opposed to what was asked for. const auto c = imager->Processing().Correction(); std::println("RDC: {} SoS: {}", optris::sdk::Explain(c.rdc), optris::sdk::Explain(c.sos));
optris_sdk_picture_correction correction; /* kOff, kNormal (default), kWide */ optris_sdk_imager_set_rdc_mode(imager, OPTRIS_SDK_RDC_NORMAL); optris_sdk_imager_set_sos_correction_enabled(imager, true); /* default */ optris_sdk_imager_set_sos_strength(imager, 0.3F); /* default 0: see below */ /* What is actually happening, as opposed to what was asked for. */ optris_sdk_picture_correction_init(&correction, sizeof(correction)); optris_sdk_imager_get_picture_correction(imager, &correction); printf("RDC: %d SoS: %d\n", (int)correction.rdc, (int)correction.sos);
// Off, Normal (default), Wide camera.DistortionCorrection = DistortionCorrection.Normal; camera.SizeOfSourceCorrection = true; // default camera.SizeOfSourceStrength = 0.3f; // default 0: see below // What is actually happening, as opposed to what was asked for. PictureCorrection correction = camera.GetPictureCorrection(); Console.WriteLine( $"RDC: {PictureCorrection.Explain(correction.Distortion)} " + $"SoS: {PictureCorrection.Explain(correction.SizeOfSource)}");
# RDC_OFF, RDC_NORMAL (default), RDC_WIDE camera.distortion_correction = optris_sdk.RDC_NORMAL camera.size_of_source_correction = True # default camera.size_of_source_strength = 0.3 # default 0: see below # What is actually happening, as opposed to what was asked for. A # simulated camera and a recording have no pipeline behind them and # report valid False with both statuses unknown -- which is not a # failure and must never be read as "active". correction = camera.picture_correction() print('RDC:', correction.rdc, ' SoS:', correction.sos)
// Off, Normal (default), Wide camera.set_rdc_mode(RdcMode::Normal)?; camera.set_sos_correction_enabled(true)?; // default camera.set_sos_strength(0.3)?; // default 0: see below // What is actually happening, as opposed to what was asked for. let correction = camera.picture_correction()?; println!("RDC: {:?} SoS: {:?}", correction.rdc, correction.sos);
sos_correction alone changes nothing: sos_strength defaults to 0, which is an exact identity, because the shipped correction table carries the shape of the halo and no magnitude. The strength has to be measured for a camera and its optics. Correction() reports SosStatus::kZeroStrength in that state, and kNoTable / RdcStatus::kNoCoefficients where the calibration carries nothing to apply. Neither is an error. Frame Processing Settings covers both corrections and the noise filters.
A motorized lens is focused as a share of its travel: 0.0 is the near end and 1.0 the far end, on every lens, and the SDK maps it onto the motor's own steps. That is the form to offer a person. The steps (GetFocusPosition(), SetFocusPosition(), GetFocusRange()) differ from model to model and are for saving and restoring one exact setting.
auto &optics = imager->Optics(); if (optris::sdk::IsFocusable(optics.GetCapability())) { optics.SetFocus(0.5F); // the middle of the travel float share = optics.GetFocus(); // 0.0 near .. 1.0 far }
optris_sdk_focus_capability capability = OPTRIS_SDK_FOCUS_UNKNOWN; float share = 0.0F; optris_sdk_imager_get_focus_capability(imager, &capability); if (capability == OPTRIS_SDK_FOCUS_MOTORIZED) { optris_sdk_imager_set_focus(imager, 0.5F); /* the middle of the travel */ optris_sdk_imager_get_focus(imager, &share); /* 0.0 near .. 1.0 far */ }
if (camera.CanFocus) { camera.SetFocus(0.5f); // the middle of the travel float share = camera.GetFocus(); // 0.0 near .. 1.0 far }
if camera.optics.is_focusable: camera.optics.set_focus_fraction(0.5) # the middle of the travel share = camera.optics.focus_fraction # 0.0 near .. 1.0 far
if camera.focus_capability()?.is_focusable() { camera.set_focus(0.5)?; // the middle of the travel let share = camera.focus()?; // 0.0 near .. 1.0 far }
GetDeviceInfo() is the cached identity record; GetTelemetry() is a live reading built per call.
There is no GetTelemetry() in the C ABI, and so none in the four bindings: the housing and detector readings are fields of a frame, which is where they come from. They carry the same chip_temp_known flag for the same reason, and reading them off a frame makes the one thing that matters explicit: a telemetry reading belongs to a moment, not to a camera.
const auto &info = imager->GetDeviceInfo(); std::println("Serial: {}", info.serial); std::println("Model: {}", info.model); const auto t = imager->GetTelemetry(); std::println("Box temp: {:.1f} C", t.box_temp_c); // The detector is the one probe that can be absent rather than cold. // `chip_temp_c` is 0.0 and `chip_temp_known` false on a camera whose // detector count does not decode, and 0 C is a temperature a detector // can genuinely be at. if (t.chip_temp_known) { std::println("Chip temp: {:.1f} C", t.chip_temp_c); } else { std::println("Chip temp: no reading from this camera"); }
char serial[OPTRIS_SDK_MAX_SERIAL]; char model[OPTRIS_SDK_MAX_MODEL]; optris_sdk_frame_info info; size_t written = 0; optris_sdk_imager_get_serial(imager, serial, sizeof serial, &written); optris_sdk_imager_get_model(imager, model, sizeof model, &written); printf("Serial: %s\nModel: %s\n", serial, model); optris_sdk_frame_info_init(&info, sizeof(info)); optris_sdk_frame_get_info(frame, &info); printf("Box temp: %.1f C\n", (double)info.box_temp_c); /* The detector is the one probe that can be absent rather than cold: * chip_temp_c is 0.0 and chip_temp_known zero on a camera whose * detector count does not decode, and 0 C is a temperature a detector * can genuinely be at. */ if (info.chip_temp_known) { printf("Chip temp: %.1f C\n", (double)info.chip_temp_c); } else { printf("Chip temp: no reading from this camera\n"); }
Console.WriteLine($"Serial: {camera.Serial}"); Console.WriteLine($"Model: {camera.Model}"); // On the frame's metadata, not on the frame: a telemetry reading // belongs to a moment. FrameMetadata meta = frame.Metadata; Console.WriteLine($"Box temp: {meta.HousingTemperature:F1} C"); // SensorTemperature is a float? rather than a number with a flag // beside it: null IS "no reading from this camera", and 0 C is a // temperature a detector can genuinely be at. Console.WriteLine(meta.SensorTemperature is float chip ? $"Chip temp: {chip:F1} C" : "Chip temp: no reading from this camera");
print('Serial:', camera.serial) print('Model: ', camera.model) print(f'Box temp: {frame.box_temp_c:.1f} C') # chip_temp_c is None rather than a number with a flag beside it: None # IS "no reading from this camera", and 0 C is a temperature a detector # can genuinely be at. if frame.chip_temp_c is not None: print(f'Chip temp: {frame.chip_temp_c:.1f} C') else: print('Chip temp: no reading from this camera')
println!("Serial: {}", camera.serial()?); println!("Model: {}", camera.model()?); let info = frame.info()?; // Both are Option<f32>, so both are matched rather than formatted. if let Some(box_temp) = info.box_temp_c { println!("Box temp: {box_temp:.1} C"); } // An Option<f32> rather than a number with a flag beside it: None IS // "no reading from this camera", and 0 C is a temperature a detector // can genuinely be at. match info.chip_temp_c { Some(chip) => println!("Chip temp: {chip:.1} C"), None => println!("Chip temp: no reading from this camera"), }
A camera whose calibration files could not be found still opens and streams, and its temperatures are wrong. GetCalibrationStatus() is how to tell, and GetCalibrationDiagnosis() says which source fell short. Calibration File Acquisition is the chapter.
Register memory you own and the SDK writes each frame straight into it. This removes the copy on the caller's side; internally the frame is still built and then written out.
This is the one place Rust has an unsafe, and it is unsafe for the reason the pointer makes obvious: the SDK writes into memory you own, from its own thread, and it must stay valid and unmoved until the buffer is removed or the camera is dropped. The C ABI's rule is the same and nothing enforces it there.
std::vector<float> buf(imager->GetWidth() * imager->GetHeight()); optris::sdk::ExternalBuffer ext; ext.data = buf.data(); ext.size = buf.size() * sizeof(float); ext.format = optris::sdk::ExternalPixelFormat::kThermalFloat32; ext.on_written = [&](const optris::sdk::ExternalBuffer &) { // buf[] now contains float Celsius values. }; // Throws ConfigException if the buffer is too small for the frame. imager->Buffers().Add(ext);
uint32_t width = 0; uint32_t height = 0; float *buf = NULL; optris_sdk_imager_get_width(imager, &width); optris_sdk_imager_get_height(imager, &height); buf = (float *)malloc((size_t)width * height * sizeof(float)); /* OPTRIS_SDK_ERROR_CONFIGURATION if the buffer is too small for the * frame. The memory has to outlive the registration. */ optris_sdk_imager_set_external_buffer( imager, buf, (size_t)width * height * sizeof(float), OPTRIS_SDK_EXTERNAL_THERMAL_FLOAT32, OnBufferWritten, NULL); /* ... and before the buffer is freed: */ optris_sdk_imager_remove_external_buffer(imager, buf); free(buf);
int pixels = camera.Width * camera.Height; float[] buf = GC.AllocateArray<float>(pixels, pinned: true); unsafe { fixed (float* data = buf) { camera.SetExternalBuffer((IntPtr)data, pixels * sizeof(float), ExternalPixelFormat.ThermalFloat32, () => { /* buf now holds Celsius */ }); } }
import ctypes pixels = camera.width * camera.height buf = (ctypes.c_float * pixels)() # The array has to stay referenced for as long as the SDK holds it; a # temporary here is a use-after-free the moment it is collected. camera.set_external_buffer(buf, optris_sdk.EXTERNAL_THERMAL_FLOAT32, on_written)
let pixels = (camera.width()? * camera.height()?) as usize; let mut buf = vec![0.0f32; pixels]; // SAFETY: `buf` outlives the registration and is not moved, and it is // removed before it is dropped. unsafe { camera.register_external_buffer( buf.as_mut_ptr().cast(), pixels * std::mem::size_of::<f32>(), ExternalFormat::ThermalFloat32, Some(|_width: u32, _height: u32| { /* buf holds Celsius */ }), )?; }
The formats are kThermalInt16, kThermalFloat32, kBgra, kRgb and kEnergyInt32. On unified-memory platforms (NVIDIA Jetson) a cudaMallocManaged pointer works directly.
Configuration persistence
An optris_sdk_config is opaque and the ABI has no setters on one, so the four bindings cannot modify a copied record the way C++ does: a record carries the values it was copied with, and the way to change a setting is the setting's own call. The export and the import are the same in all five.
// Read current config. auto cfg = imager->GetConfig(); std::println("Emissivity: {}", cfg.radiation.emissivity); // Modify and apply. cfg.radiation.emissivity = 0.92f; imager->ApplyConfig(cfg); // Export to a JSON file. Writes this file and nothing else. imager->SaveConfig("/data/my_camera.json"); // Import. Replaces regions, rules, motion zones, colour windows and // canvas placement with the file's. const auto report = imager->LoadConfig("/data/my_camera.json"); std::println("{}", report.diagnosis);
optris_sdk_config *cfg = NULL; optris_sdk_config_load_report report; /* An opaque record. There are no setters on one: it carries the values * it was copied with, and a setting is changed through its own call. */ optris_sdk_imager_copy_config(imager, &cfg); optris_sdk_imager_apply_config(imager, cfg, 0); optris_sdk_config_free(cfg); /* Export to a JSON file. Writes this file and nothing else. */ optris_sdk_imager_save_config(imager, "/data/my_camera.json"); /* Import. Replaces regions, rules, motion zones, colour windows and * canvas placement with the file's. */ optris_sdk_config_load_report_init(&report, sizeof(report)); optris_sdk_imager_load_config_checked(imager, "/data/my_camera.json", 0, &report); printf("%s\n", report.diagnosis);
// A record read back, with no setters on it -- and no Radiation // either: an optris_sdk_config is opaque, so the record answers its // Serial and its Canvas and nothing else. The emissivity in force is // camera.Radiation. using CameraConfiguration cfg = camera.GetConfiguration(); Console.WriteLine($"{cfg.Serial} at {camera.Radiation.Emissivity}"); // Export to a JSON file. Writes this file and nothing else. camera.SaveConfiguration("/data/my_camera.json"); // Import. Replaces regions, rules, motion zones, colour windows and // canvas placement with the file's. ConfigurationLoadReport report = camera.LoadConfiguration("/data/my_camera.json"); Console.WriteLine(report.Diagnosis);
# Export to a JSON file. Writes this file and nothing else. camera.save_config('/data/my_camera.json') # Import. Replaces regions, rules, motion zones, colour windows and # canvas placement with the file's. load_config_checked() hands back # what it did; load_config() is the same import without the report. report = camera.load_config_checked('/data/my_camera.json') print(report.diagnosis)
// Export to a JSON file. Writes this file and nothing else. camera.save_config("/data/my_camera.json")?; // Import. Replaces regions, rules, motion zones, colour windows and // canvas placement with the file's. load_config_checked() hands back // what it did; load_config() is the same import without the report. let report = camera.load_config_checked("/data/my_camera.json", false)?; println!("{}", report.diagnosis);
SaveConfig() writes atomically: an interrupted export leaves the previous file intact. LoadConfig() checks what it can before touching the camera, so a file that cannot work here is refused with nothing changed; pass ConfigLoadOptions{.require_matching_serial = true} to refuse a file from a different camera. SaveDeviceConfigArchive() is the separate write of the SDK's own per-camera archive on this machine, which is reloaded the next time that camera is opened. It is not written to the camera.
GetConfig() and ApplyConfig() are the same pair with no file involved. The reporting overload of ApplyConfig() goes through the same staged applier as LoadConfig() (everything refusable is refused before the first setting moves) and returns the same ConfigLoadReport.
This is the shape to save and restore settings in, and doing it setting by setting cannot be complete: a setting added in a later SDK version is silently absent from the caller's own save and restore, and nothing says so. A record grows with the SDK. Reachable from C, C#, Python and Rust as well.
camera.SaveConfiguration("line-3.json"); // ... later, or in another process ... ConfigurationLoadReport report = camera.LoadConfiguration("line-3.json"); Console.WriteLine(report.Diagnosis);
The no-file pair is how a program tries something and puts it back:
auto saved = imager->GetConfig(); auto radiation = imager->Radiometry().Get(); radiation.emissivity = 0.5f; imager->Radiometry().Set(radiation); // ... try something ... const auto report = imager->ApplyConfig(saved, {});
optris_sdk_config *saved = NULL; optris_sdk_radiation_config radiation; optris_sdk_imager_copy_config(imager, &saved); optris_sdk_radiation_config_init(&radiation, sizeof(radiation)); optris_sdk_imager_get_radiation(imager, &radiation); radiation.emissivity = 0.5F; optris_sdk_imager_set_radiation(imager, &radiation); /* ... try something ... */ optris_sdk_imager_apply_config(imager, saved, NULL, NULL); optris_sdk_config_free(saved);
using CameraConfiguration saved = camera.GetConfiguration(); camera.Radiation = camera.Radiation with { Emissivity = 0.5f }; // ... try something ... ConfigurationLoadReport report = camera.ApplyConfiguration(saved);
saved = camera.get_config() camera.emissivity = 0.5 # ... try something ... report = camera.apply_config(saved)
let saved = camera.get_config()?; let mut radiation = camera.radiation()?; radiation.emissivity = 0.5; camera.set_radiation(radiation)?; // ... try something ... let report = camera.apply_config(&saved, false);
And a record taken from one camera can be applied to another, with the serial check waived on purpose:
auto saved = source->GetConfig(); std::println("Restoring the settings taken from {}", saved.serial); optris::sdk::ConfigLoadOptions options; options.require_matching_serial = false; target->ApplyConfig(saved, options);
optris_sdk_config *saved = NULL; optris_sdk_imager_copy_config(source, &saved); /* Zero is already the default; spelled out because the point of this * sample is that the serial check stays off. */ optris_sdk_config_load_options options; optris_sdk_config_load_options_init(&options, sizeof(options)); options.require_matching_serial = 0; optris_sdk_imager_apply_config(target, saved, &options, NULL); optris_sdk_config_free(saved);
using CameraConfiguration saved = source.GetConfiguration(); Console.WriteLine($"Restoring the settings taken from {saved.Serial}"); target.ApplyConfiguration(saved, requireMatchingSerial: false);
saved = source.get_config() print(f"Restoring the settings taken from {saved.serial}") target.apply_config(saved, require_matching_serial=False)
let saved = source.get_config()?; println!("Restoring the settings taken from {}", saved.serial()?); target.apply_config(&saved, false);
Other languages
The same SDK is reachable from other languages through a flat C ABI, optris/sdk_c.h, built into the same library.
| Language | Package | Get it from | What it is |
|---|---|---|---|
| C | optris/sdk_c.h |
the platform package | Hand-written C99 ABI over the v12 API |
| .NET | Optris.Sdk (ThermalCamera) |
nuget.org: dotnet add package Optris.Sdk |
Hand-written package over the C ABI, targeting .NET 10; carries the native SDK |
| Python | optris_sdk |
PyPI: pip install optris-sdk |
Hand-written pure-Python package over the C ABI (ctypes), NumPy optional; the wheel carries the native SDK |
| Rust | optris-sdk over optris-sdk-sys |
crates.io: both crates in [dependencies] |
Safe crate over raw FFI declarations for the C ABI; needs the platform package installed |
Getting each one has the copy-paste line for each.
The older SWIG-generated C# and Python bindings (otcsdk) wrap the legacy API, not this one.
The C ABI's API version is OPTRIS_SDK_C_ABI_VERSION, currently 34. There is one API version for every language, see Versions.
Structs that may grow begin with a struct_size field, and every one a caller declares has an _init that stamps the size and applies the documented defaults. Call it before changing any field: a struct built by hand gets zeros where the SDK's defaults belong, and a zeroed struct_size is refused.
The rule is "does a call ever write into your buffer", not "who
produces the value". Several structs the SDK fills in itself have an _init, because the same struct is also read into storage the caller declared:
Call _init first |
Before |
|---|---|
optris_sdk_alarm_event_init() |
optris_sdk_imager_read_alarm_log() |
optris_sdk_shutter_correction_event_init() |
optris_sdk_imager_get_last_shutter_correction() |
optris_sdk_nuc_cycle_report_init() |
optris_sdk_imager_get_last_nuc_cycle() |
optris_sdk_action_error_init() |
the callback that delivers one |
optris_sdk_action_completed_init() |
the callback that delivers one |
optris_sdk_action_drop_counts_init() |
optris_sdk_imager_get_action_drop_counts() |
Has no _init |
Why |
|---|---|
optris_sdk_image, optris_sdk_motion_event, optris_sdk_attachment_request |
received borrowed, never declared |
| the nested capability blocks | the enclosing _init stamps their sizes |
optris_sdk_rgb24, optris_sdk_vec2, optris_sdk_color_window_entry |
fixed layout; no struct_size either |
Examples are under examples/cpp/, examples/c/, examples/csharp/, examples/python/ and examples/rust/, arranged by API area. examples/legacy/, examples/python3/ and examples/csharp/legacy/ hold examples for the older optris::IRImager interface, kept for existing code.