1use std::fs;
2use std::path::Path;
3
4use thiserror::Error;
5use visloc_core::types::{Camera, CameraId};
6
7#[derive(Debug, Error)]
8pub enum CalibrationError {
9 #[error("I/O error: {0}")]
10 Io(#[from] std::io::Error),
11 #[error("invalid KITTI calibration line {line_number}: {line} ({message})")]
12 InvalidKittiLine {
13 line_number: usize,
14 line: String,
15 message: String,
16 },
17 #[error("KITTI projection {label} was not found")]
18 KittiProjectionNotFound { label: String },
19 #[error("invalid KITTI projection {label}: {message}")]
20 InvalidKittiProjection { label: String, message: String },
21}
22
23#[derive(Debug, Clone, PartialEq)]
24pub struct KittiProjection {
25 pub label: String,
26 pub values: [f64; 12],
27}
28
29impl KittiProjection {
30 pub const fn fx(&self) -> f64 {
31 self.values[0]
32 }
33
34 pub const fn fy(&self) -> f64 {
35 self.values[5]
36 }
37
38 pub const fn cx(&self) -> f64 {
39 self.values[2]
40 }
41
42 pub const fn cy(&self) -> f64 {
43 self.values[6]
44 }
45
46 pub const fn t(&self) -> (f64, f64, f64) {
51 (self.values[3], self.values[7], self.values[11])
52 }
53 pub const fn tx(&self) -> f64 {
54 self.values[3]
55 }
56
57 pub fn stereo_baseline_from(&self, reference: &KittiProjection) -> Option<f64> {
66 if (self.fx() - reference.fx()).abs() > 1e-6 || self.fx() <= 0.0 {
67 return None;
68 }
69 let tx = self.tx() - reference.tx();
70 if tx.abs() < 1e-9 {
71 return None;
72 }
73 Some((-tx / self.fx()).abs())
74 }
75
76 pub fn to_pinhole_camera(
77 &self,
78 camera_id: CameraId,
79 width: u32,
80 height: u32,
81 ) -> Result<Camera, CalibrationError> {
82 let fx = self.fx();
83 let fy = self.fy();
84 if !fx.is_finite() || fx <= 0.0 {
85 return Err(CalibrationError::InvalidKittiProjection {
86 label: self.label.clone(),
87 message: format!("fx must be positive and finite, got {fx}"),
88 });
89 }
90 if !fy.is_finite() || fy <= 0.0 {
91 return Err(CalibrationError::InvalidKittiProjection {
92 label: self.label.clone(),
93 message: format!("fy must be positive and finite, got {fy}"),
94 });
95 }
96
97 Ok(Camera::pinhole(
98 camera_id,
99 width,
100 height,
101 fx,
102 fy,
103 self.cx(),
104 self.cy(),
105 ))
106 }
107}
108
109pub fn read_kitti_calibration_txt(
110 path: impl AsRef<Path>,
111) -> Result<Vec<KittiProjection>, CalibrationError> {
112 parse_kitti_calibration_txt(&fs::read_to_string(path)?)
113}
114
115pub fn read_kitti_pinhole_camera(
116 path: impl AsRef<Path>,
117 label: &str,
118 camera_id: CameraId,
119 width: u32,
120 height: u32,
121) -> Result<Camera, CalibrationError> {
122 let projections = read_kitti_calibration_txt(path)?;
123 kitti_projection_to_pinhole_camera(&projections, label, camera_id, width, height)
124}
125
126pub fn parse_kitti_calibration_txt(text: &str) -> Result<Vec<KittiProjection>, CalibrationError> {
127 let mut projections = Vec::new();
128 for (line_index, line) in text.lines().enumerate() {
129 let line_number = line_index + 1;
130 let trimmed = line.trim();
131 if trimmed.is_empty() || trimmed.starts_with('#') {
132 continue;
133 }
134 let Some((label, rest)) = trimmed.split_once(':') else {
135 continue;
136 };
137 let label = label.trim();
138 if !is_kitti_projection_label(label) {
139 continue;
140 }
141
142 let tokens: Vec<_> = rest.split_whitespace().collect();
143 if tokens.len() != 12 {
144 return Err(CalibrationError::InvalidKittiLine {
145 line_number,
146 line: line.to_owned(),
147 message: format!("expected 12 projection values, got {}", tokens.len()),
148 });
149 }
150
151 let mut values = [0.0; 12];
152 for (index, token) in tokens.iter().enumerate() {
153 values[index] =
154 token
155 .parse::<f64>()
156 .map_err(|error| CalibrationError::InvalidKittiLine {
157 line_number,
158 line: line.to_owned(),
159 message: format!("invalid projection value {index}: {error}"),
160 })?;
161 }
162
163 projections.push(KittiProjection {
164 label: label.to_owned(),
165 values,
166 });
167 }
168 Ok(projections)
169}
170
171pub fn kitti_projection_to_pinhole_camera(
172 projections: &[KittiProjection],
173 label: &str,
174 camera_id: CameraId,
175 width: u32,
176 height: u32,
177) -> Result<Camera, CalibrationError> {
178 projections
179 .iter()
180 .find(|projection| projection.label == label)
181 .ok_or_else(|| CalibrationError::KittiProjectionNotFound {
182 label: label.to_owned(),
183 })?
184 .to_pinhole_camera(camera_id, width, height)
185}
186
187fn is_kitti_projection_label(label: &str) -> bool {
188 let bytes = label.as_bytes();
189 bytes.len() == 2 && bytes[0] == b'P' && bytes[1].is_ascii_digit()
190}