1use std::fs;
2use std::path::Path;
3#[cfg(feature = "image-io")]
4use std::path::PathBuf;
5use thiserror::Error;
6#[cfg(feature = "image-io")]
7use visloc_core::types::FrameId;
8use visloc_vision::features::{GrayscaleImage, GrayscaleImageError};
9
10#[derive(Debug, Error)]
11pub enum PgmImageError {
12 #[error("I/O error: {0}")]
13 Io(#[from] std::io::Error),
14 #[error("invalid PGM header: {0}")]
15 InvalidHeader(String),
16 #[error("unsupported PGM magic {0}; expected P2 or P5")]
17 UnsupportedMagic(String),
18 #[error("invalid PGM integer: {0}")]
19 InvalidInteger(String),
20 #[error("unsupported PGM max value {0}; expected 1..=255")]
21 UnsupportedMaxValue(u32),
22 #[error("PGM pixel count mismatch: expected {expected_len}, got {actual_len}")]
23 PixelCountMismatch {
24 expected_len: usize,
25 actual_len: usize,
26 },
27 #[error("grayscale image error: {0}")]
28 Grayscale(#[from] GrayscaleImageError),
29}
30
31#[cfg(feature = "image-io")]
32#[derive(Debug, Error)]
33pub enum CommonImageError {
34 #[error("image decode/encode error: {0}")]
35 Image(#[from] image::ImageError),
36 #[error("grayscale image error: {0}")]
37 Grayscale(#[from] GrayscaleImageError),
38 #[error("image dimensions are too large for common image encoders: {width}x{height}")]
39 DimensionTooLarge { width: usize, height: usize },
40 #[error("failed to build grayscale image buffer")]
41 InvalidImageBuffer,
42}
43
44#[cfg(feature = "image-io")]
45#[derive(Debug, Error)]
46pub enum ImageSequenceError {
47 #[error("image sequence I/O error: {0}")]
48 Io(#[from] std::io::Error),
49 #[error("image frame {path} failed to load: {source}")]
50 FrameLoad {
51 path: PathBuf,
52 source: CommonImageError,
53 },
54 #[error("timestamp count mismatch: {path_count} image paths, {timestamp_count} timestamps")]
55 TimestampCountMismatch {
56 path_count: usize,
57 timestamp_count: usize,
58 },
59 #[error("invalid timestamp line {line_number}: {line} ({message})")]
60 InvalidTimestampLine {
61 line_number: usize,
62 line: String,
63 message: String,
64 },
65}
66
67#[cfg(feature = "image-io")]
68#[derive(Debug, Clone, PartialEq)]
69pub struct LoadedImageFrame {
70 pub frame_id: FrameId,
71 pub timestamp_nanoseconds: Option<i128>,
72 pub path: PathBuf,
73 pub image: GrayscaleImage,
74}
75
76#[cfg(feature = "image-io")]
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct ImageSequenceSummary {
79 pub frame_count: usize,
80 pub first_frame_id: Option<FrameId>,
81 pub last_frame_id: Option<FrameId>,
82 pub width: Option<usize>,
83 pub height: Option<usize>,
84 pub varying_dimensions: bool,
85 pub timestamp_count: usize,
86 pub first_timestamp_nanoseconds: Option<i128>,
87 pub last_timestamp_nanoseconds: Option<i128>,
88 pub timestamps_valid: bool,
89}
90
91#[cfg(feature = "image-io")]
92#[derive(Debug, Clone, PartialEq, Eq)]
93pub enum ImageSequenceValidationIssue {
94 InconsistentDimensions {
95 frame_id: FrameId,
96 path: PathBuf,
97 width: usize,
98 height: usize,
99 expected_width: usize,
100 expected_height: usize,
101 },
102 MissingTimestamp {
103 frame_id: FrameId,
104 path: PathBuf,
105 },
106 NonMonotonicTimestamp {
107 frame_id: FrameId,
108 path: PathBuf,
109 timestamp_nanoseconds: i128,
110 previous_frame_id: FrameId,
111 previous_timestamp_nanoseconds: i128,
112 },
113}
114
115pub fn read_pgm(path: impl AsRef<Path>) -> Result<GrayscaleImage, PgmImageError> {
116 parse_pgm(&fs::read(path)?)
117}
118
119pub fn write_pgm_ascii(
120 path: impl AsRef<Path>,
121 image: &GrayscaleImage,
122) -> Result<(), PgmImageError> {
123 fs::write(path, to_pgm_ascii(image)?)?;
124 Ok(())
125}
126
127pub fn parse_pgm(bytes: &[u8]) -> Result<GrayscaleImage, PgmImageError> {
128 let (magic, offset) = next_token(bytes, 0)
129 .ok_or_else(|| PgmImageError::InvalidHeader("missing magic".to_owned()))?;
130 let (width, offset) = parse_usize_token(bytes, offset, "width")?;
131 let (height, offset) = parse_usize_token(bytes, offset, "height")?;
132 let (max_value, offset) = parse_u32_token(bytes, offset, "max value")?;
133 if max_value == 0 || max_value > 255 {
134 return Err(PgmImageError::UnsupportedMaxValue(max_value));
135 }
136
137 let expected_len = width * height;
138 match magic.as_str() {
139 "P2" => parse_pgm_ascii_pixels(bytes, offset, width, height, expected_len, max_value),
140 "P5" => parse_pgm_binary_pixels(bytes, offset, width, height, expected_len, max_value),
141 other => Err(PgmImageError::UnsupportedMagic(other.to_owned())),
142 }
143}
144
145pub fn to_pgm_ascii(image: &GrayscaleImage) -> Result<String, PgmImageError> {
146 let mut output = format!("P2\n{} {}\n255\n", image.width(), image.height());
147 for (index, pixel) in image.pixels().iter().enumerate() {
148 let value = (pixel.clamp(0.0, 1.0) * 255.0).round() as u8;
149 output.push_str(&value.to_string());
150 if (index + 1) % image.width() == 0 {
151 output.push('\n');
152 } else {
153 output.push(' ');
154 }
155 }
156 Ok(output)
157}
158
159#[cfg(feature = "image-io")]
160pub fn read_common_image(path: impl AsRef<Path>) -> Result<GrayscaleImage, CommonImageError> {
161 dynamic_image_to_grayscale(image::open(path)?)
162}
163
164#[cfg(feature = "image-io")]
174pub fn read_common_image_colmap_grayscale(
175 path: impl AsRef<Path>,
176) -> Result<GrayscaleImage, CommonImageError> {
177 dynamic_image_to_colmap_grayscale(image::open(path)?)
178}
179
180#[cfg(feature = "image-io")]
181pub fn decode_common_image(bytes: &[u8]) -> Result<GrayscaleImage, CommonImageError> {
182 dynamic_image_to_grayscale(image::load_from_memory(bytes)?)
183}
184
185#[cfg(feature = "image-io")]
187pub fn decode_common_image_colmap_grayscale(
188 bytes: &[u8],
189) -> Result<GrayscaleImage, CommonImageError> {
190 dynamic_image_to_colmap_grayscale(image::load_from_memory(bytes)?)
191}
192
193#[cfg(feature = "image-io")]
194pub fn write_png_gray(
195 path: impl AsRef<Path>,
196 grayscale: &GrayscaleImage,
197) -> Result<(), CommonImageError> {
198 let width =
199 u32::try_from(grayscale.width()).map_err(|_| CommonImageError::DimensionTooLarge {
200 width: grayscale.width(),
201 height: grayscale.height(),
202 })?;
203 let height =
204 u32::try_from(grayscale.height()).map_err(|_| CommonImageError::DimensionTooLarge {
205 width: grayscale.width(),
206 height: grayscale.height(),
207 })?;
208 let pixels = grayscale
209 .pixels()
210 .iter()
211 .map(|pixel| (pixel.clamp(0.0, 1.0) * 255.0).round() as u8)
212 .collect();
213 let buffer = image::GrayImage::from_raw(width, height, pixels)
214 .ok_or(CommonImageError::InvalidImageBuffer)?;
215 buffer.save_with_format(path, image::ImageFormat::Png)?;
216 Ok(())
217}
218
219#[cfg(feature = "image-io")]
220pub fn read_common_image_sequence<P>(
221 paths: &[P],
222) -> Result<Vec<LoadedImageFrame>, ImageSequenceError>
223where
224 P: AsRef<Path>,
225{
226 read_common_image_sequence_with_optional_timestamps(paths, None)
227}
228
229#[cfg(feature = "image-io")]
230pub fn read_common_image_sequence_with_timestamps<P>(
231 paths: &[P],
232 timestamps_nanoseconds: &[i128],
233) -> Result<Vec<LoadedImageFrame>, ImageSequenceError>
234where
235 P: AsRef<Path>,
236{
237 if paths.len() != timestamps_nanoseconds.len() {
238 return Err(ImageSequenceError::TimestampCountMismatch {
239 path_count: paths.len(),
240 timestamp_count: timestamps_nanoseconds.len(),
241 });
242 }
243 read_common_image_sequence_with_optional_timestamps(paths, Some(timestamps_nanoseconds))
244}
245
246#[cfg(feature = "image-io")]
247pub fn read_timestamp_nanoseconds_txt(
248 path: impl AsRef<Path>,
249) -> Result<Vec<i128>, ImageSequenceError> {
250 parse_timestamp_nanoseconds_txt(&fs::read_to_string(path)?)
251}
252
253#[cfg(feature = "image-io")]
254pub fn parse_timestamp_nanoseconds_txt(text: &str) -> Result<Vec<i128>, ImageSequenceError> {
255 let mut timestamps = Vec::new();
256 for (line_index, line) in text.lines().enumerate() {
257 let line_number = line_index + 1;
258 let trimmed = line.trim();
259 if trimmed.is_empty() || trimmed.starts_with('#') {
260 continue;
261 }
262 let token = trimmed.split_whitespace().next().ok_or_else(|| {
263 ImageSequenceError::InvalidTimestampLine {
264 line_number,
265 line: line.to_owned(),
266 message: "missing timestamp".to_owned(),
267 }
268 })?;
269 let timestamp =
270 token
271 .parse::<i128>()
272 .map_err(|error| ImageSequenceError::InvalidTimestampLine {
273 line_number,
274 line: line.to_owned(),
275 message: error.to_string(),
276 })?;
277 timestamps.push(timestamp);
278 }
279 Ok(timestamps)
280}
281
282#[cfg(feature = "image-io")]
283fn read_common_image_sequence_with_optional_timestamps<P>(
284 paths: &[P],
285 timestamps_nanoseconds: Option<&[i128]>,
286) -> Result<Vec<LoadedImageFrame>, ImageSequenceError>
287where
288 P: AsRef<Path>,
289{
290 let mut frames = Vec::with_capacity(paths.len());
291 for (index, path) in paths.iter().enumerate() {
292 let path = path.as_ref();
293 let image = read_common_image(path).map_err(|source| ImageSequenceError::FrameLoad {
294 path: path.to_path_buf(),
295 source,
296 })?;
297 frames.push(LoadedImageFrame {
298 frame_id: index as FrameId,
299 timestamp_nanoseconds: timestamps_nanoseconds.map(|timestamps| timestamps[index]),
300 path: path.to_path_buf(),
301 image,
302 });
303 }
304 Ok(frames)
305}
306
307#[cfg(feature = "image-io")]
308pub fn read_common_image_sequence_dir(
309 dir: impl AsRef<Path>,
310) -> Result<Vec<LoadedImageFrame>, ImageSequenceError> {
311 let paths = common_image_sequence_paths_dir(dir)?;
312 read_common_image_sequence(&paths)
313}
314
315#[cfg(feature = "image-io")]
316pub fn read_common_image_sequence_dir_with_timestamps(
317 dir: impl AsRef<Path>,
318 timestamps_nanoseconds: &[i128],
319) -> Result<Vec<LoadedImageFrame>, ImageSequenceError> {
320 let paths = common_image_sequence_paths_dir(dir)?;
321 read_common_image_sequence_with_timestamps(&paths, timestamps_nanoseconds)
322}
323
324#[cfg(feature = "image-io")]
325pub fn read_common_image_sequence_dir_with_timestamp_file(
326 dir: impl AsRef<Path>,
327 timestamp_path: impl AsRef<Path>,
328) -> Result<Vec<LoadedImageFrame>, ImageSequenceError> {
329 let timestamps = read_timestamp_nanoseconds_txt(timestamp_path)?;
330 read_common_image_sequence_dir_with_timestamps(dir, ×tamps)
331}
332
333#[cfg(feature = "image-io")]
334fn common_image_sequence_paths_dir(
335 dir: impl AsRef<Path>,
336) -> Result<Vec<PathBuf>, ImageSequenceError> {
337 let mut paths = Vec::new();
338 for entry in fs::read_dir(dir)? {
339 let path = entry?.path();
340 if is_supported_common_image_path(&path) {
341 paths.push(path);
342 }
343 }
344 paths.sort();
345 Ok(paths)
346}
347
348#[cfg(feature = "image-io")]
349pub fn common_image_sequence_summary(frames: &[LoadedImageFrame]) -> ImageSequenceSummary {
350 let first = frames.first();
351 let timestamp_count = frames
352 .iter()
353 .filter(|frame| frame.timestamp_nanoseconds.is_some())
354 .count();
355 ImageSequenceSummary {
356 frame_count: frames.len(),
357 first_frame_id: first.map(|frame| frame.frame_id),
358 last_frame_id: frames.last().map(|frame| frame.frame_id),
359 width: first.map(|frame| frame.image.width()),
360 height: first.map(|frame| frame.image.height()),
361 varying_dimensions: !validate_common_image_sequence_dimensions(frames).is_empty(),
362 timestamp_count,
363 first_timestamp_nanoseconds: frames.iter().find_map(|frame| frame.timestamp_nanoseconds),
364 last_timestamp_nanoseconds: frames
365 .iter()
366 .rev()
367 .find_map(|frame| frame.timestamp_nanoseconds),
368 timestamps_valid: validate_common_image_sequence_timestamps(frames).is_empty(),
369 }
370}
371
372#[cfg(feature = "image-io")]
373pub fn validate_common_image_sequence_dimensions(
374 frames: &[LoadedImageFrame],
375) -> Vec<ImageSequenceValidationIssue> {
376 let Some(first) = frames.first() else {
377 return Vec::new();
378 };
379 let expected_width = first.image.width();
380 let expected_height = first.image.height();
381
382 frames
383 .iter()
384 .skip(1)
385 .filter_map(|frame| {
386 let width = frame.image.width();
387 let height = frame.image.height();
388 (width != expected_width || height != expected_height).then(|| {
389 ImageSequenceValidationIssue::InconsistentDimensions {
390 frame_id: frame.frame_id,
391 path: frame.path.clone(),
392 width,
393 height,
394 expected_width,
395 expected_height,
396 }
397 })
398 })
399 .collect()
400}
401
402#[cfg(feature = "image-io")]
403pub fn validate_common_image_sequence_timestamps(
404 frames: &[LoadedImageFrame],
405) -> Vec<ImageSequenceValidationIssue> {
406 if frames
407 .iter()
408 .all(|frame| frame.timestamp_nanoseconds.is_none())
409 {
410 return Vec::new();
411 }
412
413 let mut issues = Vec::new();
414 let mut previous: Option<(FrameId, i128)> = None;
415 for frame in frames {
416 let Some(timestamp_nanoseconds) = frame.timestamp_nanoseconds else {
417 issues.push(ImageSequenceValidationIssue::MissingTimestamp {
418 frame_id: frame.frame_id,
419 path: frame.path.clone(),
420 });
421 continue;
422 };
423
424 if let Some((previous_frame_id, previous_timestamp_nanoseconds)) = previous {
425 if timestamp_nanoseconds < previous_timestamp_nanoseconds {
426 issues.push(ImageSequenceValidationIssue::NonMonotonicTimestamp {
427 frame_id: frame.frame_id,
428 path: frame.path.clone(),
429 timestamp_nanoseconds,
430 previous_frame_id,
431 previous_timestamp_nanoseconds,
432 });
433 }
434 }
435 previous = Some((frame.frame_id, timestamp_nanoseconds));
436 }
437
438 issues
439}
440
441#[cfg(feature = "image-io")]
442fn is_supported_common_image_path(path: &Path) -> bool {
443 let Some(extension) = path.extension().and_then(|extension| extension.to_str()) else {
444 return false;
445 };
446 matches!(
447 extension.to_ascii_lowercase().as_str(),
448 "jpg" | "jpeg" | "png"
449 )
450}
451
452#[cfg(feature = "image-io")]
453fn dynamic_image_to_grayscale(
454 dynamic: image::DynamicImage,
455) -> Result<GrayscaleImage, CommonImageError> {
456 let luma = dynamic.to_luma8();
457 let (width, height) = luma.dimensions();
458 GrayscaleImage::from_luma_u8(width as usize, height as usize, luma.into_raw())
459 .map_err(CommonImageError::from)
460}
461
462#[cfg(feature = "image-io")]
463fn dynamic_image_to_colmap_grayscale(
464 dynamic: image::DynamicImage,
465) -> Result<GrayscaleImage, CommonImageError> {
466 let rgb = dynamic.to_rgb8();
467 let (width, height) = rgb.dimensions();
468 let pixels = rgb
469 .as_raw()
470 .chunks_exact(3)
471 .map(|channels| {
472 let luminance = 0.2126f32 * f32::from(channels[0])
477 + 0.7152f32 * f32::from(channels[1])
478 + 0.0722f32 * f32::from(channels[2])
479 + 0.5f32;
480 luminance as u8
481 })
482 .collect();
483 GrayscaleImage::from_luma_u8(width as usize, height as usize, pixels)
484 .map_err(CommonImageError::from)
485}
486
487fn parse_pgm_ascii_pixels(
488 bytes: &[u8],
489 mut offset: usize,
490 width: usize,
491 height: usize,
492 expected_len: usize,
493 max_value: u32,
494) -> Result<GrayscaleImage, PgmImageError> {
495 let mut pixels = Vec::with_capacity(expected_len);
496 while let Some((token, next_offset)) = next_token(bytes, offset) {
497 let value = parse_u32(&token)?;
498 if value > max_value {
499 return Err(PgmImageError::InvalidInteger(format!(
500 "pixel value {value} exceeds max value {max_value}"
501 )));
502 }
503 pixels.push(value as f32 / max_value as f32);
504 offset = next_offset;
505 }
506
507 if pixels.len() != expected_len {
508 return Err(PgmImageError::PixelCountMismatch {
509 expected_len,
510 actual_len: pixels.len(),
511 });
512 }
513 GrayscaleImage::new(width, height, pixels).map_err(PgmImageError::from)
514}
515
516fn parse_pgm_binary_pixels(
517 bytes: &[u8],
518 offset: usize,
519 width: usize,
520 height: usize,
521 expected_len: usize,
522 max_value: u32,
523) -> Result<GrayscaleImage, PgmImageError> {
524 let pixel_offset = skip_single_whitespace(bytes, offset);
525 let data = bytes.get(pixel_offset..).unwrap_or_default();
526 if data.len() != expected_len {
527 return Err(PgmImageError::PixelCountMismatch {
528 expected_len,
529 actual_len: data.len(),
530 });
531 }
532
533 let pixels = data
534 .iter()
535 .map(|value| *value as f32 / max_value as f32)
536 .collect();
537 GrayscaleImage::new(width, height, pixels).map_err(PgmImageError::from)
538}
539
540fn parse_usize_token(
541 bytes: &[u8],
542 offset: usize,
543 label: &str,
544) -> Result<(usize, usize), PgmImageError> {
545 let (token, offset) = next_token(bytes, offset)
546 .ok_or_else(|| PgmImageError::InvalidHeader(format!("missing {label}")))?;
547 Ok((parse_usize(&token)?, offset))
548}
549
550fn parse_u32_token(
551 bytes: &[u8],
552 offset: usize,
553 label: &str,
554) -> Result<(u32, usize), PgmImageError> {
555 let (token, offset) = next_token(bytes, offset)
556 .ok_or_else(|| PgmImageError::InvalidHeader(format!("missing {label}")))?;
557 Ok((parse_u32(&token)?, offset))
558}
559
560fn parse_usize(token: &str) -> Result<usize, PgmImageError> {
561 token
562 .parse::<usize>()
563 .map_err(|error| PgmImageError::InvalidInteger(error.to_string()))
564}
565
566fn parse_u32(token: &str) -> Result<u32, PgmImageError> {
567 token
568 .parse::<u32>()
569 .map_err(|error| PgmImageError::InvalidInteger(error.to_string()))
570}
571
572fn next_token(bytes: &[u8], mut offset: usize) -> Option<(String, usize)> {
573 loop {
574 while offset < bytes.len() && bytes[offset].is_ascii_whitespace() {
575 offset += 1;
576 }
577 if offset >= bytes.len() {
578 return None;
579 }
580 if bytes[offset] != b'#' {
581 break;
582 }
583 while offset < bytes.len() && bytes[offset] != b'\n' {
584 offset += 1;
585 }
586 }
587
588 let start = offset;
589 while offset < bytes.len() && !bytes[offset].is_ascii_whitespace() {
590 offset += 1;
591 }
592 Some((
593 String::from_utf8_lossy(&bytes[start..offset]).to_string(),
594 offset,
595 ))
596}
597
598fn skip_single_whitespace(bytes: &[u8], offset: usize) -> usize {
599 if offset < bytes.len() && bytes[offset].is_ascii_whitespace() {
600 offset + 1
601 } else {
602 offset
603 }
604}