Illustrated C/C++ source sheets, symbol index, API relationship graph, compiler console and debug trace

LIVE AI / FLEXIBLE SENSING / FLIGHT CONTEXT

Sensoraia API

Live AI and sensing, connected to the flight.
See, listen, inspect and return supported results while airborne.

Loading...
Searching...
No Matches
lwir_calibrate.cpp
Go to the documentation of this file.
1/*
2 * Copyright 2026 OpenUAS
3 * SPDX-License-Identifier: Apache-2.0
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18/** @brief Request POSIX.1-2008 stream/descriptor APIs before system headers. */
19#define _POSIX_C_SOURCE 200809L
20
21/**
22 * @file lwir_calibrate.cpp
23 * @brief Native host tool for LWIR lens and camera-mount calibration.
24 * @details Lens mode estimates pinhole intrinsics and five Brown-Conrady
25 * distortion coefficients from varied checkerboard photographs. Mount mode
26 * holds those intrinsics fixed and estimates camera-to-body rotation from a
27 * board physically aligned with the aircraft datum. Keeping these stages
28 * separate avoids interpreting lens distortion as a mounting error.
29 *
30 * OpenCV supplies detection, geometry and drawing; bundled libjpeg handles
31 * JPEG I/O so no OpenCV imgcodecs module or additional codec dependency is
32 * needed. Original pixels are neither resized nor EXIF-oriented before fitting:
33 * coefficients must describe the same native coordinates used by LWIRcam.
34 * Only inspection previews are enlarged and annotated.
35 *
36 * Each run produces a runtime-readable profile, a diagnostic report and
37 * inspection previews. Failed runs remove the candidate profile but retain
38 * available diagnostic evidence. Outputs are intended for a trusted workshop
39 * directory, not concurrent writers competing for the same filenames.
40 * @warning Numerical convergence is not physical verification. Every exported
41 * profile remains unverified; corner orientation, board alignment and independent
42 * measurements must be checked before relying on projected coordinates.
43 * @see fit_lens
44 * @see fit_mount
45 */
46#include "version.h"
47
48#include <cstddef>
49#include <cstdio>
50#include <jpeglib.h>
51#include "jpeg_marker_guard.h"
52#include <setjmp.h>
53
54#include <opencv2/calib3d.hpp>
55#include <opencv2/core.hpp>
56#include <opencv2/core/persistence.hpp>
57#include <opencv2/imgproc.hpp>
58#include "opencv_parallel.hpp"
59
60#include <algorithm>
61#include <array>
62#include <cerrno>
63#include <cctype>
64#include <cmath>
65#include <cstdint>
66#include <filesystem>
67#include <fstream>
68#include <iomanip>
69#include <iostream>
70#include <memory>
71#include <set>
72#include <sstream>
73#include <stdexcept>
74#include <string>
75#include <sys/stat.h>
76#include <unistd.h>
77#include <vector>
78
79namespace {
80
81/** @brief Filesystem operations use paths rather than shell command strings. */
82namespace fs = std::filesystem;
83
84/** @brief Compressed-input ceiling, checked before libjpeg starts decoding. */
85constexpr size_t maximum_jpeg_bytes = 128U * 1024U * 1024U;
86/** @brief Decoded-pixel ceiling; compressed file size alone cannot bound memory. */
87constexpr uint64_t maximum_image_pixels = 32U * 1024U * 1024U;
88/** @brief Per-axis limit also bounds the preview encoder's scanline scratch. */
89constexpr unsigned maximum_image_dimension = 8192U;
90/** @brief Accepted-image-list cap; this is not a total fitting-memory budget. */
91constexpr size_t maximum_directory_images = 10000U;
92/** @brief Minimum complete fitting views; count alone cannot ensure varied poses. */
93constexpr size_t minimum_fit_views = 15U;
94/** @brief Minimum complete hold-out views when an independent set is requested. */
95constexpr size_t minimum_check_views = 5U;
96/** @brief Convert the workshop's measured millimetre pitch to solver metres. */
97constexpr double metres_per_millimetre = 0.001;
98/** @brief Enlarge small thermal images for inspection, subject to pixel limits. */
99constexpr double preferred_preview_scale = 3.0;
100/** @brief Inspection JPEG quality; previews never feed back into the fit. */
101constexpr int preview_jpeg_quality = 95;
102/** @brief Runtime schema key kept false regardless of the numerical residual. */
103constexpr const char* profile_verified_key = "verified";
104
105/** @brief Distinguish invalid invocation from an unsuccessful calibration run. */
106struct UsageError : std::runtime_error {
107 using std::runtime_error::runtime_error;
108};
109
110/** @brief Close C streams during normal return and C++ exception unwinding. */
111struct FileCloser {
112 /** @brief Release an owned stream without throwing.
113 * @param file Stream to close, or nullptr for an empty owner.
114 * @note Writers check flushing separately; this deleter cannot report errors.
115 */
116 void operator()(FILE* file) const noexcept
117 {
118 if (file != nullptr) {
119 std::fclose(file);
120 }
121 }
122};
123
124/** @brief Single owner for a FILE stream, including error paths. */
125using File = std::unique_ptr<FILE, FileCloser>;
126
127/** @brief libjpeg-compatible error manager and its active C recovery target.
128 * @details The manager must be first: libjpeg exposes only its base pointer to
129 * the callback. Keeping codec state outside the setjmp stack frame lets C++
130 * ownership clean it up after the callback returns control via longjmp.
131 */
132struct JpegError {
133 jpeg_error_mgr manager{}; ///< Base error manager passed to libjpeg.
134 jmp_buf recovery{}; ///< Recovery point active only during the codec operation.
135 void (*emit)(j_common_ptr, int) = nullptr;
136};
137
138/** @brief Return a fatal libjpeg error to the enclosing decode/encode operation.
139 * @param state Codec whose error manager belongs to a JpegError instance.
140 * @pre That instance has an active setjmp recovery point on the current thread.
141 * @details libjpeg normally terminates the process on a fatal error. This C-only
142 * jump returns to a boundary that can throw a descriptive C++ exception instead;
143 * no exception crosses libjpeg's C call frames.
144 */
145void jpeg_failure(j_common_ptr state)
146{
147 auto* error = reinterpret_cast<JpegError*>(state->err);
148 longjmp(error->recovery, 1);
149}
150
151void jpeg_message(j_common_ptr state, int level)
152{
154 reinterpret_cast<JpegError*>(state->err)->emit(state, level);
155}
156
157/** @brief Own decoder state and its output across libjpeg's C error recovery. */
158struct Decoder {
159 jpeg_decompress_struct state{}; ///< libjpeg decompressor and allocation state.
160 JpegError error{}; ///< Recovery target used by jpeg_failure().
161 bool created = false; ///< Destroy only after codec creation has completed.
162 cv::Mat gray; ///< Ref-counted native grayscale pixels, not a display transform.
163
164 /** @brief Release codec allocations after successful creation. */
165 ~Decoder()
166 {
167 if (created) {
168 jpeg_destroy_decompress(&state);
169 }
170 }
171};
172
173/** @brief Own preview-compression state across normal and recovered returns. */
174struct Encoder {
175 jpeg_compress_struct state{}; ///< libjpeg compressor and allocation state.
176 JpegError error{}; ///< Recovery target used by jpeg_failure().
177 bool created = false; ///< Prevent destruction of a not-yet-created compressor.
178
179 /** @brief Release codec allocations after successful creation. */
180 ~Encoder()
181 {
182 if (created) {
183 jpeg_destroy_compress(&state);
184 }
185 }
186};
187
188/** @brief Validated invocation; dimensions count inner corners, not squares. */
189struct Options {
190 /** @brief Independent stages with different physical evidence requirements.
191 * @details lens fits intrinsics/distortion from multiple views; mount fits
192 * rotation using fixed intrinsics and an aircraft-aligned board.
193 */
194 enum class Mode { lens, mount };
195 Mode mode = Mode::lens; ///< Selected calibration stage.
196 int columns = 0; ///< Inner corners along the board's first coordinate axis.
197 int rows = 0; ///< Inner corners along the board's second coordinate axis.
198 double square_mm = 0.0; ///< Measured adjacent-corner pitch in millimetres.
199 fs::path output; ///< New candidate profile; existing evidence is not replaced.
200 fs::path images; ///< Lens-fitting JPEG directory.
201 fs::path check; ///< Optional separate lens hold-out JPEG directory.
202 fs::path image; ///< Mount photograph in the lens profile's native dimensions.
203 fs::path lens; ///< Intrinsic profile held fixed during mount fitting.
204 bool reverse_corners = false; ///< Explicitly reverse mount detection order.
205};
206
207/** @brief Related artifacts share one stem so evidence stays with its profile. */
208struct OutputPaths {
209 fs::path profile; ///< Candidate calibration consumed by LWIRcam.
210 fs::path previews; ///< Directory of annotated inspection-only JPEGs.
211 fs::path report; ///< Human-readable fit/check diagnostics and failure details.
212};
213
214/** @brief Intrinsics read without inheriting mounting or verification claims. */
215struct LensProfile {
216 cv::Size image_size; ///< Native pixel dimensions for which coefficients apply.
217 cv::Mat camera_matrix; ///< Double-precision 3x3 pinhole matrix, focal units pixels.
218 cv::Mat distortion; ///< Double-precision k1, k2, p1, p2, k3 in OpenCV order.
219};
220
221/** @brief Ordered diagnostic lines retained for success and failure reports. */
222using Report = std::vector<std::string>;
223
224/** @brief Stop a run before invalid evidence can propagate to its profile.
225 * @param condition Invariant required for the next operation.
226 * @param message Diagnostic explaining the failed invariant.
227 * @throws std::runtime_error If condition is false.
228 */
229void require(bool condition, const std::string& message)
230{
231 if (!condition) {
232 throw std::runtime_error(message);
233 }
234}
235
236/** @brief Parse an entire finite numeric argument, never a valid prefix alone.
237 * @param text Argument token to parse.
238 * @param option Option name used in the failure diagnostic.
239 * @return Finite value; its physical range is checked by parse_options().
240 * @throws UsageError If trailing text or a nonfinite value is present.
241 * @throws std::invalid_argument If no number can be parsed.
242 * @throws std::out_of_range If conversion exceeds the representable range.
243 */
244double parse_double(const std::string& text, const std::string& option)
245{
246 size_t consumed = 0;
247 const double value = std::stod(text, &consumed);
248 if (consumed != text.size() || !std::isfinite(value)) {
249 throw UsageError(option + " requires one finite number");
250 }
251 return value;
252}
253
254/** @brief Parse a bounded nonnegative integer before narrowing to int.
255 * @param text Complete decimal argument token.
256 * @param option Option name used in the failure diagnostic.
257 * @return Parsed value in 0..1000000; board limits are checked separately.
258 * @throws UsageError If trailing text or an out-of-policy value is present.
259 * @throws std::invalid_argument If no integer can be parsed.
260 * @throws std::out_of_range If conversion overflows long.
261 */
262int parse_integer(const std::string& text, const std::string& option)
263{
264 size_t consumed = 0;
265 const long value = std::stol(text, &consumed, 10);
266 if (consumed != text.size() || value < 0 || value > 1000000) {
267 throw UsageError(option + " requires a nonnegative integer");
268 }
269 return static_cast<int>(value);
270}
271
272/** @brief Describe the two workshop stages without opening images or devices.
273 * @param program Invocation name displayed in command examples.
274 */
275void print_usage(const char* program)
276{
277 std::cout << LWIR_CALIBRATE_BUILD_VERSION << "\n"
278 << "Usage:\n"
279 << " " << program << " lens --images DIR [--check DIR] --columns N --rows N\n"
280 << " --square-mm MM --output PROFILE.yml\n"
281 << " " << program << " mount --image PHOTO.jpg --lens PROFILE.yml\n"
282 << " --columns N --rows N --square-mm MM --output PROFILE.yml\n"
283 << " [--reverse-corners]\n"
284 << "Only original JPG/JPEG calibration photographs are accepted.\n";
285}
286
287/** @brief Validate stage-specific arguments before creating any output paths.
288 * @param argc Number of command-line tokens, including the executable name.
289 * @param argv Command-line tokens supplied to main().
290 * @return Complete invocation with compatible options and bounded board geometry.
291 * @throws UsageError If options are missing, repeated, unknown or incompatible.
292 * @throws std::exception On numeric conversion failures.
293 * @details Rejecting duplicates prevents a silently overridden pitch or board
294 * size from changing the physical interpretation of an otherwise plausible fit.
295 */
296Options parse_options(int argc, char** argv)
297{
298 if (argc < 2) {
299 throw UsageError("select lens or mount mode");
300 }
301 Options options;
302 const std::string mode(argv[1]);
303 if (mode == "lens") {
304 options.mode = Options::Mode::lens;
305 } else if (mode == "mount") {
306 options.mode = Options::Mode::mount;
307 } else {
308 throw UsageError("mode must be lens or mount");
309 }
310
311 std::set<std::string> seen;
312 for (int index = 2; index < argc; ++index) {
313 const std::string key(argv[index]);
314 if (!seen.insert(key).second) {
315 throw UsageError("option repeated: " + key);
316 }
317 if (key == "--reverse-corners") {
318 options.reverse_corners = true;
319 continue;
320 }
321 if (index + 1 >= argc) {
322 throw UsageError("missing value for " + key);
323 }
324 const std::string value(argv[++index]);
325 if (key == "--columns") {
326 options.columns = parse_integer(value, key);
327 } else if (key == "--rows") {
328 options.rows = parse_integer(value, key);
329 } else if (key == "--square-mm") {
330 options.square_mm = parse_double(value, key);
331 } else if (key == "--output") {
332 options.output = value;
333 } else if (key == "--images") {
334 options.images = value;
335 } else if (key == "--check") {
336 options.check = value;
337 } else if (key == "--image") {
338 options.image = value;
339 } else if (key == "--lens") {
340 options.lens = value;
341 } else {
342 throw UsageError("unknown option: " + key);
343 }
344 }
345
346 if (options.columns < 3 || options.columns > 64 || options.rows < 3 || options.rows > 64
347 || options.square_mm <= 0.0 || options.square_mm > 10000.0 || options.output.empty()) {
348 throw UsageError("use 3..64 inner corners per dimension, a positive square pitch, and --output");
349 }
350 if (options.mode == Options::Mode::lens && (options.images.empty() || !options.image.empty()
351 || !options.lens.empty() || options.reverse_corners)) {
352 throw UsageError("lens mode requires --images and does not accept mount-only options");
353 }
354 if (options.mode == Options::Mode::mount && (options.image.empty() || options.lens.empty()
355 || !options.images.empty() || !options.check.empty())) {
356 throw UsageError("mount mode requires --image and --lens, not --images or --check");
357 }
358 return options;
359}
360
361/** @brief Open a nonempty, size-bounded regular file for JPEG decoding.
362 * @param path Input photograph; the descriptor is checked after opening.
363 * @return Owned binary stream positioned at its beginning.
364 * @throws std::runtime_error If opening or descriptor validation fails.
365 * @note This is a trusted-directory workflow, not a no-follow or nonblocking
366 * open: descriptor validation does not provide hostile-path isolation.
367 */
368File open_regular_jpeg(const fs::path& path)
369{
370 const std::string native_path = path.string();
371 File input(std::fopen(native_path.c_str(), "rb"));
372 require(input != nullptr, "cannot open JPEG: " + native_path);
373 struct stat status {};
374 require(::fstat(::fileno(input.get()), &status) == 0 && S_ISREG(status.st_mode)
375 && status.st_size > 0 && static_cast<uint64_t>(status.st_size) <= maximum_jpeg_bytes,
376 "JPEG must be a non-empty regular file below 128 MiB: " + native_path);
377 return input;
378}
379
380/** @brief Decode native grayscale pixels using the already-bundled JPEG codec.
381 * @param path Original JPG/JPEG photograph.
382 * @return Owned/ref-counted CV_8UC1 image in the JPEG's stored orientation.
383 * @throws std::runtime_error If file bounds, dimensions or codec checks fail.
384 * @details Grayscale is sufficient for checkerboard geometry. Dimension checks
385 * precede image allocation, and codec warnings reject damaged-but-recoverable
386 * inputs rather than allowing reconstructed pixels to bias a calibration.
387 */
388cv::Mat read_jpeg_gray(const fs::path& path)
389{
390 File input = open_regular_jpeg(path);
391 auto decoder = std::make_unique<Decoder>();
392 decoder->state.err = jpeg_std_error(&decoder->error.manager);
393 decoder->error.emit = decoder->error.manager.emit_message;
394 decoder->error.manager.emit_message = jpeg_message;
395 decoder->error.manager.error_exit = jpeg_failure;
396 if (setjmp(decoder->error.recovery)) {
397 throw std::runtime_error("invalid or damaged JPEG: " + path.string());
398 }
399 decoder->created = true;
400 jpeg_create_decompress(&decoder->state);
401 jpeg_stdio_src(&decoder->state, input.get());
402 require(jpeg_read_header(&decoder->state, TRUE) == JPEG_HEADER_OK,
403 "invalid JPEG header: " + path.string());
404 const uint64_t width = decoder->state.image_width;
405 const uint64_t height = decoder->state.image_height;
406 require(width >= 2 && height >= 2 && width <= maximum_image_dimension
407 && height <= maximum_image_dimension && width * height <= maximum_image_pixels,
408 "unsupported JPEG dimensions: " + path.string());
409 decoder->state.out_color_space = JCS_GRAYSCALE;
410 jpeg_start_decompress(&decoder->state);
411 decoder->gray.create(static_cast<int>(height), static_cast<int>(width), CV_8UC1);
412 while (decoder->state.output_scanline < decoder->state.output_height) {
413 JSAMPROW row = decoder->gray.ptr(decoder->state.output_scanline);
414 require(jpeg_read_scanlines(&decoder->state, &row, 1) == 1,
415 "incomplete JPEG scanline: " + path.string());
416 }
417 jpeg_finish_decompress(&decoder->state);
418 require(decoder->error.manager.num_warnings == 0, "damaged JPEG: " + path.string());
419 return decoder->gray;
420}
421
422/** @brief Encode an inspection preview without linking OpenCV imgcodecs.
423 * @param path Destination inside this run's prepared preview directory.
424 * @param bgr Nonempty CV_8UC3 image within the configured size ceilings.
425 * @throws std::runtime_error On invalid dimensions or write/codec failure.
426 * @details Convert BGR to RGB one bounded row at a time, avoiding another
427 * full-image color copy. Previews are lossy display artifacts, never fit inputs.
428 * @note A fatal codec error unlinks its partial preview; this is not an atomic
429 * publication or crash-durability guarantee.
430 */
431void write_jpeg_bgr(const fs::path& path, const cv::Mat& bgr)
432{
433 require(!bgr.empty() && bgr.type() == CV_8UC3
434 && bgr.cols <= static_cast<int>(maximum_image_dimension)
435 && bgr.rows <= static_cast<int>(maximum_image_dimension)
436 && static_cast<uint64_t>(bgr.cols) * static_cast<uint64_t>(bgr.rows) <= maximum_image_pixels,
437 "preview must be an 8-bit BGR image within the configured dimension limit");
438 const std::string native_path = path.string();
439 File output(std::fopen(native_path.c_str(), "wb"));
440 require(output != nullptr, "cannot create JPEG preview: " + native_path);
441 auto encoder = std::make_unique<Encoder>();
442 encoder->state.err = jpeg_std_error(&encoder->error.manager);
443 encoder->error.manager.error_exit = jpeg_failure;
444 std::array<JSAMPLE, maximum_image_dimension * 3U> rgb_row{};
445 if (setjmp(encoder->error.recovery)) {
446 ::unlink(native_path.c_str());
447 throw std::runtime_error("JPEG preview encoding failed: " + native_path);
448 }
449 encoder->created = true;
450 jpeg_create_compress(&encoder->state);
451 jpeg_stdio_dest(&encoder->state, output.get());
452 encoder->state.image_width = static_cast<JDIMENSION>(bgr.cols);
453 encoder->state.image_height = static_cast<JDIMENSION>(bgr.rows);
454 encoder->state.input_components = 3;
455 encoder->state.in_color_space = JCS_RGB;
456 jpeg_set_defaults(&encoder->state);
457 jpeg_set_quality(&encoder->state, preview_jpeg_quality, TRUE);
458 jpeg_start_compress(&encoder->state, TRUE);
459 while (encoder->state.next_scanline < encoder->state.image_height) {
460 const unsigned int y = encoder->state.next_scanline;
461 const cv::Vec3b* source = bgr.ptr<cv::Vec3b>(static_cast<int>(y));
462 for (int x = 0; x < bgr.cols; ++x) {
463 rgb_row[static_cast<size_t>(x) * 3U] = source[x][2];
464 rgb_row[static_cast<size_t>(x) * 3U + 1U] = source[x][1];
465 rgb_row[static_cast<size_t>(x) * 3U + 2U] = source[x][0];
466 }
467 JSAMPROW row = rgb_row.data();
468 require(jpeg_write_scanlines(&encoder->state, &row, 1) == 1,
469 "cannot write JPEG preview scanline");
470 }
471 jpeg_finish_compress(&encoder->state);
472 require(std::fflush(output.get()) == 0, "cannot flush JPEG preview: " + native_path);
473}
474
475/** @brief Collect supported photographs in stable lexical order.
476 * @param directory Nonrecursive input directory.
477 * @return Nonempty sorted list of regular .jpg/.jpeg files, case-insensitive.
478 * @throws std::runtime_error If enumeration fails, finds no JPEGs or exceeds
479 * the accepted-image cap.
480 * @details Stable ordering keeps report/preview indexing reproducible for the
481 * same filenames. Extensions select candidates; libjpeg validates their content.
482 */
483std::vector<fs::path> jpg_paths(const fs::path& directory)
484{
485 std::error_code error;
486 require(fs::is_directory(directory, error) && !error,
487 "not an image directory: " + directory.string());
488 std::vector<fs::path> paths;
489 for (fs::directory_iterator it(directory, error), end; !error && it != end; it.increment(error)) {
490 if (paths.size() >= maximum_directory_images) {
491 throw std::runtime_error("image directory exceeds the 10000-file limit: " + directory.string());
492 }
493 if (!it->is_regular_file(error) || error) {
494 error.clear();
495 continue;
496 }
497 std::string extension = it->path().extension().string();
498 std::transform(extension.begin(), extension.end(), extension.begin(),
499 [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
500 if (extension == ".jpg" || extension == ".jpeg") {
501 paths.push_back(it->path());
502 }
503 }
504 require(!error, "cannot enumerate image directory: " + directory.string());
505 std::sort(paths.begin(), paths.end());
506 require(!paths.empty(), "no JPG/JPEG images in " + directory.string());
507 return paths;
508}
509
510/** @brief Build the planar metric coordinates matching detector corner order.
511 * @param columns Inner corners per row, already validated by parse_options().
512 * @param rows Inner-corner rows, already validated by parse_options().
513 * @param square_mm Measured adjacent-corner pitch in millimetres.
514 * @return Row-major points in metres with origin at corner zero and z=0.
515 * @details Consistent metric units make pose translations meaningful; resizing
516 * an image or confusing square count with corner count changes the model.
517 */
518std::vector<cv::Point3f> board_points(int columns, int rows, double square_mm)
519{
520 const float pitch_m = static_cast<float>(square_mm * metres_per_millimetre);
521 std::vector<cv::Point3f> points;
522 points.reserve(static_cast<size_t>(columns) * static_cast<size_t>(rows));
523 for (int row = 0; row < rows; ++row) {
524 for (int column = 0; column < columns; ++column) {
525 points.emplace_back(column * pitch_m, row * pitch_m, 0.0F);
526 }
527 }
528 return points;
529}
530
531/** @brief Detect a complete board with OpenCV's subpixel sector-based method.
532 * @param gray Original native grayscale image, not an enlarged preview.
533 * @param options Validated inner-corner dimensions.
534 * @param[out] corners Detected subpixel positions; consume only on success.
535 * @return True when a complete board of the requested dimensions is found.
536 * @details Normalization and exhaustive search help low-contrast thermal
537 * patterns. Detection order still cannot establish physical aircraft axes.
538 */
539bool detect_board(const cv::Mat& gray, const Options& options, std::vector<cv::Point2f>& corners)
540{
541 const cv::Size pattern(options.columns, options.rows);
542 return cv::findChessboardCornersSB(gray, pattern, corners,
543 cv::CALIB_CB_NORMALIZE_IMAGE | cv::CALIB_CB_EXHAUSTIVE);
544}
545
546/** @brief Measure per-corner Euclidean reprojection RMS in original pixels.
547 * @param object_points Board coordinates in the frame used for pose fitting.
548 * @param image_points Corresponding observed native pixel positions.
549 * @param rotation Rodrigues object-to-camera rotation vector.
550 * @param translation Object-to-camera translation in board units (metres here).
551 * @param camera_matrix Pinhole intrinsics with focal lengths in pixels.
552 * @param distortion OpenCV distortion coefficients used by the fitted model.
553 * @return Square root of summed squared 2D errors divided by corner count.
554 * @pre Correspondence arrays have equal nonzero length.
555 * @note This residual measures image-model agreement, not ground-position or
556 * temperature accuracy, board alignment or correctness of physical axis labels.
557 */
558double reprojection_rms(const std::vector<cv::Point3f>& object_points,
559 const std::vector<cv::Point2f>& image_points,
560 const cv::Mat& rotation, const cv::Mat& translation,
561 const cv::Mat& camera_matrix, const cv::Mat& distortion)
562{
563 std::vector<cv::Point2f> projected;
564 cv::projectPoints(object_points, rotation, translation, camera_matrix, distortion, projected);
565 double squared_error = 0.0;
566 for (size_t index = 0; index < projected.size(); ++index) {
567 const cv::Point2f delta = projected[index] - image_points[index];
568 squared_error += delta.dot(delta);
569 }
570 return std::sqrt(squared_error / static_cast<double>(projected.size()));
571}
572
573/** @brief Save inspectable corner evidence separately from fitting pixels.
574 * @param gray Original native grayscale image.
575 * @param corners Complete detected pattern in native pixel coordinates.
576 * @param options Validated board dimensions.
577 * @param path New preview JPEG path.
578 * @param numbered Label corners 0, 1 and columns to expose both board directions.
579 * @details Nearest-neighbor enlargement keeps thermal pixel structure visible.
580 * Both side and pixel limits constrain the preferred scale. Numbered neighbors
581 * let an operator check detector order against the physically aligned board.
582 * @throws std::runtime_error If corner indexing or preview encoding fails.
583 */
584void write_preview(const cv::Mat& gray, const std::vector<cv::Point2f>& corners,
585 const Options& options, const fs::path& path, bool numbered)
586{
587 cv::Mat canvas;
588 cv::cvtColor(gray, canvas, cv::COLOR_GRAY2BGR);
589 cv::drawChessboardCorners(canvas, cv::Size(options.columns, options.rows), corners, true);
590 const double dimension_scale = std::min(
591 static_cast<double>(maximum_image_dimension) / canvas.cols,
592 static_cast<double>(maximum_image_dimension) / canvas.rows);
593 const double pixel_scale = std::sqrt(static_cast<double>(maximum_image_pixels) / canvas.total());
594 const double scale = std::min(preferred_preview_scale, std::min(dimension_scale, pixel_scale));
595 const cv::Size preview_size(std::max(1, cvRound(canvas.cols * scale)),
596 std::max(1, cvRound(canvas.rows * scale)));
597 cv::resize(canvas, canvas, preview_size, 0.0, 0.0, cv::INTER_NEAREST);
598 if (numbered) {
599 for (const int index : {0, 1, options.columns}) {
600 require(static_cast<size_t>(index) < corners.size(), "internal corner index outside detected pattern");
601 const cv::Point point(cvRound(corners[index].x * preview_size.width / gray.cols),
602 cvRound(corners[index].y * preview_size.height / gray.rows));
603 const std::string label = std::to_string(index);
604 cv::putText(canvas, label, point, cv::FONT_HERSHEY_SIMPLEX, 0.7, cv::Scalar(0, 0, 0), 4, cv::LINE_AA);
605 cv::putText(canvas, label, point, cv::FONT_HERSHEY_SIMPLEX, 0.7, cv::Scalar(255, 255, 255), 1, cv::LINE_AA);
606 }
607 }
608 write_jpeg_bgr(path, canvas);
609}
610
611/** @brief Keep live console diagnostics and the saved evidence in the same order.
612 * @param[in,out] report Accumulated diagnostic lines.
613 * @param line Message to retain and print.
614 */
615void report_line(Report& report, const std::string& line)
616{
617 report.push_back(line);
618 std::cout << line << '\n';
619}
620
621/** @brief Write retained evidence as a plain-text workshop report.
622 * @param path Report path belonging to this run.
623 * @param report Ordered diagnostics, including any terminal failure message.
624 * @throws std::runtime_error If opening or writing the stream fails.
625 * @note Used best-effort during failure cleanup; not an atomic journal.
626 */
627void write_report(const fs::path& path, const Report& report)
628{
629 std::ofstream output(path, std::ios::binary | std::ios::trunc);
630 require(output.good(), "cannot write calibration report: " + path.string());
631 for (const std::string& line : report) {
632 output << line << '\n';
633 }
634 require(output.good(), "incomplete calibration report: " + path.string());
635}
636
637/** @brief Refuse existing artifacts before creating the run's directories.
638 * @param options Invocation containing the requested new profile path.
639 * @return Profile, report and preview paths after directory creation succeeds.
640 * @throws std::runtime_error If any artifact already exists or cannot be checked.
641 * @throws fs::filesystem_error If directory creation fails.
642 * @details Checking all three artifacts preserves evidence from earlier runs,
643 * including failed ones. It is a workshop overwrite guard, not an exclusive
644 * filesystem reservation against another process racing the same pathname.
645 */
646OutputPaths prepare_outputs(const Options& options)
647{
648 OutputPaths paths{options.output, options.output.parent_path() /
649 (options.output.stem().string() + "-previews"), options.output};
650 paths.report.replace_extension(".report.txt");
651 std::error_code error;
652 require(!fs::exists(paths.profile, error) && !error && !fs::exists(paths.previews, error)
653 && !error && !fs::exists(paths.report, error) && !error,
654 "output, report or preview path already exists; choose a new output name");
655 fs::path parent = paths.profile.parent_path();
656 if (parent.empty()) {
657 parent = ".";
658 }
659 fs::create_directories(parent);
660 fs::create_directory(paths.previews);
661 return paths;
662}
663
664/** @brief Record enough setup context to interpret the residuals and previews.
665 * @param options Board dimensions and measured pitch used for this run.
666 * @param[in,out] report Destination for software, pattern and verification notes.
667 */
668void append_report_header(const Options& options, Report& report)
669{
670 std::ostringstream header;
671 header << "LWIR workshop calibration; OpenCV " << CV_VERSION;
672 report.push_back(header.str());
673 std::ostringstream pattern;
674 pattern << "Pattern " << options.columns << 'x' << options.rows
675 << " inner corners, pitch " << options.square_mm << " mm";
676 report.push_back(pattern.str());
677 report.emplace_back("verified=0; inspect previews and perform independent physical checks.");
678}
679
680/** @brief Reject nonfinite coefficients before persisting a candidate profile.
681 * @param camera_matrix Fitted or imported intrinsics.
682 * @param distortion Fitted or imported distortion coefficients.
683 * @param mounting Row-major camera-to-body rotation coefficients.
684 * @throws std::runtime_error If an array fails its numeric check.
685 * @note This is a numeric sanity check, not a physical calibration assessment.
686 */
687void validate_outputs(const cv::Mat& camera_matrix, const cv::Mat& distortion,
688 const std::array<double, 9>& mounting)
689{
690 require(cv::checkRange(camera_matrix) && cv::checkRange(distortion),
691 "fit produced non-finite camera coefficients");
692 require(std::all_of(mounting.begin(), mounting.end(),
693 [](double value) { return std::isfinite(value); }),
694 "fit produced non-finite mounting coefficients");
695}
696
697/** @brief Export coefficients in the format consumed by native LWIRcam.
698 * @param path Candidate profile path approved by prepare_outputs().
699 * @param size Native image dimensions to which the calibration applies.
700 * @param matrix Double-precision 3x3 intrinsic matrix.
701 * @param distortion At least five doubles in k1, k2, p1, p2, k3 order.
702 * @param mounting Nine row-major camera-to-body rotation coefficients.
703 * @throws std::runtime_error If numeric validation or output completion fails.
704 * @details Seventeen significant digits preserve double precision on round-trip.
705 * The rotation stays on one line because the bounded runtime loader parses one
706 * record per line; a general serializer may wrap long fitted coefficients.
707 * Verification is always false, including when refining a previously used lens.
708 * @note Output completion is checked, but publication is not atomic or fsynced.
709 */
710void write_profile(const fs::path& path, cv::Size size, const cv::Mat& matrix,
711 const cv::Mat& distortion, const std::array<double, 9>& mounting)
712{
713 validate_outputs(matrix, distortion, mounting);
714 std::ofstream output(path, std::ios::out | std::ios::trunc);
715 require(output.is_open(), "cannot write calibration profile: " + path.string());
716 output << "%YAML:1.0\n---\n" << std::setprecision(17);
717 output << "image_width: " << size.width << '\n';
718 output << "image_height: " << size.height << '\n';
719 output << "fx: " << matrix.at<double>(0, 0) << '\n';
720 output << "fy: " << matrix.at<double>(1, 1) << '\n';
721 output << "cx: " << matrix.at<double>(0, 2) << '\n';
722 output << "cy: " << matrix.at<double>(1, 2) << '\n';
723 const cv::Mat flat_distortion = distortion.reshape(1, 1);
724 static const std::array<const char*, 5> keys{{"k1", "k2", "p1", "p2", "k3"}};
725 for (int index = 0; index < 5; ++index) {
727 << flat_distortion.at<double>(0, index) << '\n';
728 }
729 output << profile_verified_key << ": 0\ncamera_to_body: [";
730 for (size_t index = 0; index < mounting.size(); ++index) {
731 output << (index == 0 ? " " : ", ") << mounting[index];
732 }
733 output << " ]\n";
734 output.close();
735 require(output.good(), "cannot finish calibration profile: " + path.string());
736 require(fs::file_size(path) > 0, "calibration profile is empty: " + path.string());
737}
738
739/** @brief Import only the fixed intrinsics needed by the mounting solver.
740 * @param path Existing profile with numeric dimensions and lens coefficients.
741 * @return Double-precision intrinsics/distortion and their native pixel size.
742 * @throws std::runtime_error If required fields, dimensions or focal lengths fail
743 * validation.
744 * @throws cv::Exception If OpenCV cannot parse the profile.
745 * @details Mount fitting must not refit the lens from a single board view or
746 * inherit a prior mounting/verification claim. Numeric nodes are required so a
747 * quoted number cannot silently become a missing or default coefficient.
748 */
749LensProfile read_lens_profile(const fs::path& path)
750{
751 cv::FileStorage input(path.string(), cv::FileStorage::READ);
752 require(input.isOpened(), "cannot open lens profile: " + path.string());
753 const auto read_number = [&input, &path](const char* key) {
754 const cv::FileNode node = input[key];
755 require(!node.empty() && (node.isInt() || node.isReal()),
756 std::string("missing or nonnumeric lens key: ") + key + " in " + path.string());
757 double value = 0.0;
758 node >> value;
759 require(std::isfinite(value), std::string("non-finite lens key: ") + key);
760 return value;
761 };
762 const double width_value = read_number("image_width");
763 const double height_value = read_number("image_height");
764 require(width_value >= 1 && width_value <= maximum_image_dimension
765 && height_value >= 1 && height_value <= maximum_image_dimension
766 && std::floor(width_value) == width_value && std::floor(height_value) == height_value,
767 "invalid lens-profile dimensions");
768 LensProfile profile;
769 profile.image_size = cv::Size(static_cast<int>(width_value), static_cast<int>(height_value));
770 profile.camera_matrix = cv::Mat::eye(3, 3, CV_64F);
771 profile.camera_matrix.at<double>(0, 0) = read_number("fx");
772 profile.camera_matrix.at<double>(1, 1) = read_number("fy");
773 profile.camera_matrix.at<double>(0, 2) = read_number("cx");
774 profile.camera_matrix.at<double>(1, 2) = read_number("cy");
775 require(profile.camera_matrix.at<double>(0, 0) > 0 && profile.camera_matrix.at<double>(1, 1) > 0,
776 "lens focal lengths must be positive");
777 profile.distortion = cv::Mat(1, 5, CV_64F);
778 static const std::array<const char*, 5> keys{{"k1", "k2", "p1", "p2", "k3"}};
779 for (int index = 0; index < 5; ++index) {
780 profile.distortion.at<double>(0, index) = read_number(keys[static_cast<size_t>(index)]);
781 }
782 return profile;
783}
784
785/** @brief Fit lens geometry and report residuals on separate check photographs.
786 * @param options Validated lens-stage invocation and measured board pitch.
787 * @param outputs Fresh artifact paths prepared for this run.
788 * @param[in,out] report Fitting/check diagnostics retained for operator review.
789 * @throws std::runtime_error If inputs disagree, too few complete boards remain,
790 * a check pose fails or output cannot be written.
791 * @throws cv::Exception If OpenCV detection or optimization fails.
792 * @details Only corner correspondences are retained between images, not all
793 * decoded photographs. OpenCV estimates intrinsics, five distortion coefficients
794 * and a separate pose for each accepted view. Hold-out images estimate poses
795 * using those fixed lens coefficients, so they are not additional fitting data.
796 * @warning View count and low residuals do not prove useful image coverage or
797 * correct board dimensions. Exported mounting is nominal, not measured here.
798 */
799void fit_lens(const Options& options, const OutputPaths& outputs, Report& report)
800{
801 const std::vector<cv::Point3f> board = board_points(options.columns, options.rows, options.square_mm);
802 const std::vector<fs::path> paths = jpg_paths(options.images);
803 std::vector<std::vector<cv::Point3f>> object_views;
804 std::vector<std::vector<cv::Point2f>> image_views;
805 std::vector<fs::path> accepted_paths;
806 cv::Size image_size;
807 for (size_t index = 0; index < paths.size(); ++index) {
808 const cv::Mat gray = read_jpeg_gray(paths[index]);
809 const cv::Size current_size(gray.cols, gray.rows);
810 if (image_size.empty()) {
811 image_size = current_size;
812 } else {
813 require(image_size == current_size,
814 "mixed image dimensions at " + paths[index].string() + "; do not resize to force a match");
815 }
816 std::vector<cv::Point2f> corners;
817 if (!detect_board(gray, options, corners)) {
818 report_line(report, "SKIPPED no complete pattern: " + paths[index].string());
819 continue;
820 }
821 object_views.push_back(board);
822 image_views.push_back(corners);
823 accepted_paths.push_back(paths[index]);
824 std::ostringstream preview_name;
825 preview_name << "fit-" << std::setw(3) << std::setfill('0') << index << ".jpg";
826 write_preview(gray, corners, options, outputs.previews / preview_name.str(), false);
827 }
828 require(object_views.size() >= minimum_fit_views,
829 "only " + std::to_string(object_views.size()) + " complete patterns; need at least 15 varied views");
830
831 cv::Mat camera_matrix;
832 cv::Mat distortion;
833 std::vector<cv::Mat> rotations;
834 std::vector<cv::Mat> translations;
835 const double rms = cv::calibrateCamera(object_views, image_views, image_size,
836 camera_matrix, distortion, rotations, translations);
837 require(std::isfinite(rms), "lens fit produced non-finite RMS");
838 {
839 std::ostringstream line;
840 line << std::fixed << std::setprecision(6) << "Fitting RMS: " << rms
841 << " pixels; retained views: " << accepted_paths.size();
842 report_line(report, line.str());
843 }
844 for (size_t index = 0; index < accepted_paths.size(); ++index) {
845 std::ostringstream line;
846 line << std::fixed << std::setprecision(6) << "FIT "
847 << reprojection_rms(board, image_views[index], rotations[index], translations[index],
848 camera_matrix, distortion)
849 << " px: " << accepted_paths[index].string();
850 report_line(report, line.str());
851 }
852
853 if (!options.check.empty()) {
854 // Resolve path aliases so a symlink to a fitting image is not a hold-out.
855 // This is path separation, not content deduplication of copied photographs.
856 std::set<fs::path> fit_files;
857 for (const fs::path& path : paths) {
858 fit_files.insert(fs::weakly_canonical(path));
859 }
860 size_t check_count = 0;
861 const std::vector<fs::path> check_paths = jpg_paths(options.check);
862 for (size_t index = 0; index < check_paths.size(); ++index) {
863 require(fit_files.count(fs::weakly_canonical(check_paths[index])) == 0,
864 "check images must be separate from fitting images: " + check_paths[index].string());
865 const cv::Mat gray = read_jpeg_gray(check_paths[index]);
866 require(cv::Size(gray.cols, gray.rows) == image_size,
867 "check-image dimensions differ: " + check_paths[index].string());
868 std::vector<cv::Point2f> corners;
869 if (!detect_board(gray, options, corners)) {
870 report_line(report, "SKIPPED check pattern: " + check_paths[index].string());
871 continue;
872 }
873 cv::Mat rotation;
874 cv::Mat translation;
875 require(cv::solvePnP(board, corners, camera_matrix, distortion, rotation, translation),
876 "cannot estimate check-board pose: " + check_paths[index].string());
877 std::ostringstream line;
878 line << std::fixed << std::setprecision(6) << "CHECK "
879 << reprojection_rms(board, corners, rotation, translation, camera_matrix, distortion)
880 << " px: " << check_paths[index].string();
881 report_line(report, line.str());
882 ++check_count;
883 std::ostringstream preview_name;
884 preview_name << "check-" << std::setw(3) << std::setfill('0') << index << ".jpg";
885 write_preview(gray, corners, options, outputs.previews / preview_name.str(), false);
886 }
887 require(check_count >= minimum_check_views,
888 "only " + std::to_string(check_count) + " complete check patterns; supply at least 5");
889 } else {
890 report_line(report, "WARNING: no independent check set supplied");
891 }
892 report_line(report, "Mounting is NOMINAL ONLY; physical axis measurement is still required.");
893 const std::array<double, 9> nominal_mounting{{0, -1, 0, 1, 0, 0, 0, 0, 1}};
894 write_profile(outputs.profile, image_size, camera_matrix, distortion, nominal_mounting);
895}
896
897/** @brief Estimate camera-to-body rotation using an aircraft-aligned board.
898 * @param options Mount-stage invocation with fixed lens profile and photograph.
899 * @param outputs Fresh artifact paths prepared for this run.
900 * @param[in,out] report Residual, axis-direction and inspection diagnostics.
901 * @throws std::runtime_error If dimensions, board detection, pose cheirality or
902 * profile publication checks fail.
903 * @throws cv::Exception If OpenCV parsing, detection or pose solving fails.
904 * @details Camera axes are right/down/forward; aircraft body axes are
905 * forward/right/down. The board's increasing columns must point body-right and
906 * increasing rows tailward, in a plane parallel to the body datum. The solver's
907 * body-to-camera rotation is inverted for downstream camera-ray projection.
908 * Translation is a board-pose nuisance variable, not the camera/GPS lever arm.
909 * @warning A symmetric checkerboard can give a plausible residual with a wrong
910 * physical orientation. The numbered preview and datum alignment require human
911 * confirmation; positive board depth alone cannot verify the mount.
912 */
913void fit_mount(const Options& options, const OutputPaths& outputs, Report& report)
914{
915 const LensProfile lens = read_lens_profile(options.lens);
916 const cv::Mat gray = read_jpeg_gray(options.image);
917 require(cv::Size(gray.cols, gray.rows) == lens.image_size,
918 "mount image does not match lens-profile dimensions");
919 std::vector<cv::Point2f> corners;
920 require(detect_board(gray, options, corners),
921 "no complete checker pattern; improve contrast, focus or framing");
922 // Reversal is an explicit operator choice, never inferred from a low RMS.
923 if (options.reverse_corners) {
924 std::reverse(corners.begin(), corners.end());
925 }
926 write_preview(gray, corners, options, outputs.previews / "mount-order.jpg", true);
927
928 const std::vector<cv::Point3f> board = board_points(options.columns, options.rows, options.square_mm);
929 std::vector<cv::Point3f> body_points;
930 body_points.reserve(board.size());
931 // Board x grows rightward and board y tailward: body (forward,right) = (-y,x).
932 // The arbitrary corner origin affects fitted translation, not the rotation.
933 for (const cv::Point3f& point : board) {
934 body_points.emplace_back(-point.y, point.x, point.z);
935 }
936 cv::Mat rotation;
937 cv::Mat translation;
938 require(cv::solvePnP(body_points, corners, lens.camera_matrix, lens.distortion, rotation, translation),
939 "mounting pose did not converge");
940 cv::Mat body_to_camera_mat;
941 cv::Rodrigues(rotation, body_to_camera_mat);
942 cv::Matx33d body_to_camera;
943 for (int row = 0; row < 3; ++row) {
944 for (int column = 0; column < 3; ++column) {
945 body_to_camera(row, column) = body_to_camera_mat.at<double>(row, column);
946 }
947 }
948 // Reject the physically impossible branch with any board point behind the lens.
949 for (const cv::Point3f& point : body_points) {
950 const cv::Vec3d camera_point = body_to_camera * cv::Vec3d(point.x, point.y, point.z)
951 + cv::Vec3d(translation.at<double>(0), translation.at<double>(1),
952 translation.at<double>(2));
953 require(camera_point[2] > 0.0, "board pose lies behind the camera; check corner order");
954 }
955 // solvePnP maps object/body coordinates into camera coordinates; rays need
956 // the opposite direction. For a Rodrigues rotation, transpose is the inverse.
957 const cv::Matx33d camera_to_body = body_to_camera.t();
958 std::array<double, 9> mounting{};
959 for (int row = 0; row < 3; ++row) {
960 for (int column = 0; column < 3; ++column) {
961 mounting[static_cast<size_t>(3 * row + column)] = camera_to_body(row, column);
962 }
963 }
964 {
965 std::ostringstream line;
966 line << std::fixed << std::setprecision(6) << "Mount reprojection RMS: "
967 << reprojection_rms(body_points, corners, rotation, translation,
968 lens.camera_matrix, lens.distortion) << " pixels";
969 report_line(report, line.str());
970 }
971 report_line(report, "ASSUMPTION: board columns point body-right; rows point toward tail; board is level with body datum.");
972 report_line(report, "CONFIRM preview labels 0, 1 and " + std::to_string(options.columns)
973 + " against the physical board; no automatic verification.");
974 {
975 const cv::Vec3d optical_axis(camera_to_body(0, 2), camera_to_body(1, 2), camera_to_body(2, 2));
976 std::ostringstream line;
977 line << "Optical axis in body forward/right/down: [" << optical_axis[0] << ", "
978 << optical_axis[1] << ", " << optical_axis[2] << "]";
979 report_line(report, line.str());
980 }
981 write_profile(outputs.profile, lens.image_size, lens.camera_matrix, lens.distortion, mounting);
982}
983
984} // namespace
985
986/** @brief Run one workshop stage with distinct invocation and fitting failures.
987 * @param argc Number of command-line arguments, including the executable name.
988 * @param argv Command-line arguments; help/version require no input files.
989 * @retval 0 Requested information or calibration artifacts were produced.
990 * @retval 1 Calibration or I/O failed; available diagnostic evidence is retained.
991 * @retval 2 Invocation or numeric argument parsing failed before output setup.
992 * @details Failed processing removes the candidate profile so a partial result
993 * cannot masquerade as a usable calibration. Reports/previews stay available for
994 * diagnosis, and report-writing failure never hides the original error.
995 */
996int main(int argc, char** argv)
997{
998 if (argc == 2 && (std::string(argv[1]) == "--version" || std::string(argv[1]) == "-V")) {
999 std::cout << LWIR_CALIBRATE_BUILD_VERSION << '\n';
1000 return 0;
1001 }
1002 if (argc == 2 && (std::string(argv[1]) == "--help" || std::string(argv[1]) == "-h")) {
1003 print_usage(argv[0]);
1004 return 0;
1005 }
1006
1007 Options options;
1008 try {
1009 options = parse_options(argc, argv);
1010 } catch (const UsageError& error) {
1011 std::cerr << error.what() << '\n';
1012 print_usage(argv[0]);
1013 return 2;
1014 } catch (const std::exception& error) {
1015 std::cerr << error.what() << '\n';
1016 return 2;
1017 }
1018
1019 OutputPaths outputs;
1020 Report report;
1021 try {
1022 const usher_cv_parallel::ScopedBackend opencv_parallel_backend;
1023 outputs = prepare_outputs(options);
1024 append_report_header(options, report);
1025 if (options.mode == Options::Mode::lens) {
1026 fit_lens(options, outputs, report);
1027 } else {
1028 fit_mount(options, outputs, report);
1029 }
1030 report_line(report, "Not automatically verified. Inspect evidence before using coordinates.");
1031 write_report(outputs.report, report);
1032 std::cout << "Profile: " << outputs.profile << "\nReport: " << outputs.report
1033 << "\nPreviews: " << outputs.previews << '\n';
1034 return 0;
1035 } catch (const cv::Exception& error) {
1036 report.push_back(std::string("STOP: ") + error.what());
1037 } catch (const std::exception& error) {
1038 report.push_back(std::string("STOP: ") + error.what());
1039 }
1040
1041 std::error_code remove_error;
1042 // outputs is assigned only after prepare_outputs succeeds. An existing profile
1043 // rejected by the overwrite guard must never become a cleanup target.
1044 if (!outputs.profile.empty()) {
1045 fs::remove(outputs.profile, remove_error);
1046 }
1047 if (!outputs.report.empty()) {
1048 try {
1049 write_report(outputs.report, report);
1050 } catch (...) {
1051 }
1052 }
1053 if (!report.empty()) {
1054 std::cerr << report.back() << '\n';
1055 }
1056 if (!outputs.report.empty()) {
1057 std::cerr << "Details: " << outputs.report << "\nChoose a new output filename on retry.\n";
1058 }
1059 return 1;
1060}
static void report(const struct capture_intent *intent, unsigned camera_id, uint32_t outcome)
Record a terminal outcome without allowing telemetry backlog to block camera release.
size_t size
Definition chdk_pipe.c:143
RAII guard installing the backend at startup and joining workers before main() exits.
static bool parse_double(const char *text, double *value)
Parse a finite floating-point token in full.
static int parse_options(int argc, char **argv, struct options *options)
Parse and cross-validate EARcam command-line configuration.
Definition earcam.c:437
static void print_usage(FILE *stream, const char *program)
Print command-line help or version-led usage text.
Definition earcam.c:314
static void jpeg_message(j_common_ptr codec, int level)
Check JPEG marker bounds ahead of normal codec diagnostics.
Reject invalid Huffman selectors before the bundled codec indexes its tables.
static void usher_jpeg_validate_marker(j_common_ptr state)
Validate marker parameters from an error manager's emit_message callback.
int main(int argc, char **argv)
Run one workshop stage with distinct invocation and fitting failures.
struct jpeg_compress_struct encoder
Definition lwir_image.c:59
uint8_t row[LWIR_MAX_WIDTH *3U]
Definition lwir_image.c:63
jmp_buf recovery
Definition lwir_image.c:61
static void jpeg_failure(j_common_ptr encoder)
libjpeg error_exit replacement: abandon the photo instead of exiting.
Definition lwir_image.c:86
struct jpeg_error_mgr error
Definition lwir_image.c:60
struct jpeg_decompress_struct decoder
Definition lwir_mock.c:55
static struct usher_camera_profile profile
Header-only C++17 cv::parallel::ParallelForAPI backend for Sensoraia.
static const char header[]
Definition pose_log.c:87
static FILE * output
Definition pose_log.c:77
Compile-time build identity strings for USHER executables.
#define LWIR_CALIBRATE_BUILD_VERSION
Definition version.h:78
Validated capture and reporting policy, fixed before the sample loop.
Definition earcam.c:137
One timestamped geographic position for a replay annotation.
struct captured_image image
Definition usher.c:371