Skip to main content

viva_genicam/
image_io.rs

1//! Saving frames as PNG or TIFF at the camera's bit depth.
2//!
3//! Behind the `image-io` feature. A frame is first converted by
4//! [`viva_pfnc::convert::full_depth`]: monochrome stays grey, everything else
5//! becomes RGB, and samples wider than 8 bits — Mono10/12/14/16 packed or
6//! not, and Bayer mosaics demosaiced at their own depth — are written as
7//! 16-bit images.
8//!
9//! **16-bit samples are scaled to the full 16-bit range**, as PNG requires
10//! of an encoder whose samples are narrower than the file's (PNG 3rd edition
11//! §12.4), by left bit replication: a 12-bit `0xABC` is written `0xABCA`.
12//! `value >> (16 − bits)` gives the camera's value back exactly. A PNG
13//! records `bits` in its `sBIT` chunk (§11.3.2.4); TIFF has no such field,
14//! so a TIFF holds the same scaled samples and the depth is yours to know.
15//! Samples of 8 or 16 bits are written unchanged.
16//!
17//! Files are uncompressed TIFF and default-compression PNG.
18
19use std::io::Cursor;
20use std::path::Path;
21
22use viva_pfnc::convert::{self, ConvertError, Pixels};
23
24use crate::Frame;
25
26/// An image file format [`encode`] writes.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28#[non_exhaustive]
29pub enum ImageFormat {
30    /// PNG: 8- or 16-bit grey or RGB, the camera's depth in `sBIT`.
31    Png,
32    /// Baseline TIFF, uncompressed: 8- or 16-bit grey or RGB.
33    Tiff,
34}
35
36impl ImageFormat {
37    /// The format a file name asks for: `.png`, or `.tif`/`.tiff`, in any
38    /// case.
39    pub fn from_path(path: &Path) -> Option<Self> {
40        let extension = path.extension()?.to_str()?.to_ascii_lowercase();
41        match extension.as_str() {
42            "png" => Some(ImageFormat::Png),
43            "tif" | "tiff" => Some(ImageFormat::Tiff),
44            _ => None,
45        }
46    }
47
48    /// The usual file extension, without the dot.
49    pub fn extension(self) -> &'static str {
50        match self {
51            ImageFormat::Png => "png",
52            ImageFormat::Tiff => "tiff",
53        }
54    }
55}
56
57/// Why an image could not be written.
58#[derive(Debug, thiserror::Error)]
59#[non_exhaustive]
60pub enum ImageIoError {
61    /// The frame's pixels could not be converted.
62    #[error(transparent)]
63    Convert(#[from] ConvertError),
64    /// `pixels` is not `width × height` samples (of `channels` each).
65    #[error("{samples} samples for a {width}×{height} image with {channels} channel(s)")]
66    Size {
67        /// The samples given.
68        samples: usize,
69        /// The image's width.
70        width: u32,
71        /// Its height.
72        height: u32,
73        /// Samples per pixel: 1 for grey, 3 for colour.
74        channels: usize,
75    },
76    /// A pixel layout this encoder does not write.
77    #[error("cannot encode this pixel layout")]
78    Layout,
79    /// The path does not name a format: it ends in none of `.png`, `.tif`,
80    /// `.tiff`.
81    #[error("{0} does not end in .png, .tif or .tiff")]
82    Extension(std::path::PathBuf),
83    /// The PNG or TIFF encoder refused the image. The source is the
84    /// encoder's error.
85    #[error("cannot encode image: {0}")]
86    Encode(#[source] Box<dyn std::error::Error + Send + Sync + 'static>),
87    /// Writing the file failed.
88    #[error(transparent)]
89    Io(#[from] std::io::Error),
90}
91
92/// A frame as an image file, at its own depth (see the [module](self)
93/// documentation).
94pub fn encode_frame(frame: &Frame, format: ImageFormat) -> Result<Vec<u8>, ImageIoError> {
95    let pixels = convert::full_depth(
96        frame.pixel_format,
97        frame.width,
98        frame.height,
99        frame.row_stride(),
100        &frame.payload,
101    )?;
102    encode(&pixels, frame.width, frame.height, format)
103}
104
105/// Write a frame to `path`, in the format its extension names.
106pub fn save_frame(frame: &Frame, path: &Path) -> Result<(), ImageIoError> {
107    let format =
108        ImageFormat::from_path(path).ok_or_else(|| ImageIoError::Extension(path.to_path_buf()))?;
109    std::fs::write(path, encode_frame(frame, format)?)?;
110    Ok(())
111}
112
113/// A `width × height` image as a file; [`Pixels::into_rgb`] first for colour.
114pub fn encode(
115    pixels: &Pixels,
116    width: u32,
117    height: u32,
118    format: ImageFormat,
119) -> Result<Vec<u8>, ImageIoError> {
120    let image = Image::of(pixels, width, height)?;
121    match format {
122        ImageFormat::Png => image.png(),
123        ImageFormat::Tiff => image.tiff(),
124    }
125}
126
127/// Samples ready for a file: 16-bit ones already scaled.
128struct Image<'a> {
129    width: u32,
130    height: u32,
131    rgb: bool,
132    samples: Samples<'a>,
133    /// The camera's depth when it is narrower than the file's 16 bits.
134    significant: Option<u8>,
135}
136
137enum Samples<'a> {
138    Eight(&'a [u8]),
139    Sixteen(Vec<u16>),
140}
141
142impl<'a> Image<'a> {
143    fn of(pixels: &'a Pixels, width: u32, height: u32) -> Result<Self, ImageIoError> {
144        let (rgb, samples, bits) = match pixels {
145            Pixels::Gray8(v) => (false, Samples::Eight(v), 8),
146            Pixels::Rgb8(v) => (true, Samples::Eight(v), 8),
147            Pixels::Gray16 { samples, bits } => {
148                (false, Samples::Sixteen(scale(samples, *bits)), *bits)
149            }
150            Pixels::Rgb16 { samples, bits } => {
151                (true, Samples::Sixteen(scale(samples, *bits)), *bits)
152            }
153            _ => return Err(ImageIoError::Layout),
154        };
155        let channels = if rgb { 3 } else { 1 };
156        let expected = (width as usize)
157            .checked_mul(height as usize)
158            .and_then(|n| n.checked_mul(channels));
159        let actual = match &samples {
160            Samples::Eight(v) => v.len(),
161            Samples::Sixteen(v) => v.len(),
162        };
163        if expected != Some(actual) {
164            return Err(ImageIoError::Size {
165                samples: actual,
166                width,
167                height,
168                channels,
169            });
170        }
171        Ok(Image {
172            width,
173            height,
174            rgb,
175            samples,
176            significant: (8 < bits && bits < 16).then_some(bits),
177        })
178    }
179
180    fn png(&self) -> Result<Vec<u8>, ImageIoError> {
181        let failed = |e: png::EncodingError| ImageIoError::Encode(Box::new(e));
182        let mut file = Vec::new();
183        let mut encoder = png::Encoder::new(&mut file, self.width, self.height);
184        encoder.set_color(if self.rgb {
185            png::ColorType::Rgb
186        } else {
187            png::ColorType::Grayscale
188        });
189        let data: Vec<u8> = match &self.samples {
190            Samples::Eight(v) => {
191                encoder.set_depth(png::BitDepth::Eight);
192                v.to_vec()
193            }
194            Samples::Sixteen(v) => {
195                encoder.set_depth(png::BitDepth::Sixteen);
196                // §7.2: network byte order.
197                v.iter().flat_map(|s| s.to_be_bytes()).collect()
198            }
199        };
200        let mut writer = encoder.write_header().map_err(failed)?;
201        if let Some(bits) = self.significant {
202            // §11.3.2.4: one byte per channel, before IDAT.
203            let channels = if self.rgb { 3 } else { 1 };
204            writer
205                .write_chunk(png::chunk::sBIT, &[bits; 3][..channels])
206                .map_err(failed)?;
207        }
208        writer.write_image_data(&data).map_err(failed)?;
209        writer.finish().map_err(failed)?;
210        Ok(file)
211    }
212
213    fn tiff(&self) -> Result<Vec<u8>, ImageIoError> {
214        use tiff::encoder::{TiffEncoder, colortype};
215        let failed = |e: tiff::TiffError| ImageIoError::Encode(Box::new(e));
216        let mut file = Cursor::new(Vec::new());
217        let mut encoder = TiffEncoder::new(&mut file).map_err(failed)?;
218        let (w, h) = (self.width, self.height);
219        match (&self.samples, self.rgb) {
220            (Samples::Eight(v), false) => encoder.write_image::<colortype::Gray8>(w, h, v),
221            (Samples::Eight(v), true) => encoder.write_image::<colortype::RGB8>(w, h, v),
222            (Samples::Sixteen(v), false) => encoder.write_image::<colortype::Gray16>(w, h, v),
223            (Samples::Sixteen(v), true) => encoder.write_image::<colortype::RGB16>(w, h, v),
224        }
225        .map_err(failed)?;
226        Ok(file.into_inner())
227    }
228}
229
230/// PNG 3rd edition §12.4, left bit replication: the `bits` valid bits moved
231/// to the top of 16, their own top bits repeated into the bits left open.
232fn scale(samples: &[u16], bits: u8) -> Vec<u16> {
233    if bits >= 16 {
234        return samples.to_vec();
235    }
236    let open = 16 - u32::from(bits);
237    samples
238        .iter()
239        .map(|&v| (v << open) | (v >> (u32::from(bits) - open)))
240        .collect()
241}
242
243#[cfg(test)]
244mod tests {
245    use std::io::Cursor;
246
247    use bytes::Bytes;
248    use viva_pfnc::PixelFormat;
249
250    use super::*;
251
252    fn frame(format: PixelFormat, width: u32, height: u32, payload: &[u8]) -> Frame {
253        Frame::new(Bytes::copy_from_slice(payload), width, height, format)
254    }
255
256    /// (colour type, bit depth, sBIT, samples as big-endian bytes).
257    fn read_png(file: &[u8]) -> (png::ColorType, png::BitDepth, Option<Vec<u8>>, Vec<u8>) {
258        let mut reader = png::Decoder::new(Cursor::new(file)).read_info().unwrap();
259        let info = reader.info();
260        let (colour, depth) = (info.color_type, info.bit_depth);
261        let sbit = info.sbit.as_ref().map(|s| s.to_vec());
262        let mut buf = vec![0; reader.output_buffer_size().unwrap()];
263        let out = reader.next_frame(&mut buf).unwrap();
264        buf.truncate(out.buffer_size());
265        (colour, depth, sbit, buf)
266    }
267
268    /// PNG 3rd edition §12.4: a 12-bit sample is scaled up to 16 bits by left
269    /// bit replication — 0xABC becomes 0xABC0 | 0xA, 0x123 becomes 0x1231 —
270    /// and §11.3.2.4 `sBIT` records the 12 significant bits, so `>> 4` gives
271    /// the camera's values back. §7.2: 16-bit samples are big-endian.
272    #[test]
273    fn mono12_is_a_16_bit_grey_png_with_its_depth_in_sbit() {
274        let file = encode_frame(
275            &frame(PixelFormat::Mono12p, 2, 1, &[0xBC, 0x3A, 0x12]),
276            ImageFormat::Png,
277        )
278        .unwrap();
279        let (colour, depth, sbit, samples) = read_png(&file);
280        assert_eq!(
281            (colour, depth),
282            (png::ColorType::Grayscale, png::BitDepth::Sixteen)
283        );
284        assert_eq!(sbit, Some(vec![12]));
285        assert_eq!(samples, [0xAB, 0xCA, 0x12, 0x31]);
286    }
287
288    /// A 12-bit mosaic is demosaiced at its own depth into 16-bit RGB.
289    #[test]
290    fn bayer12_is_a_16_bit_rgb_png() {
291        // A flat 4×4 RGGB mosaic: R = 0xC8F, G = 0x64A, B = 0x323.
292        let mut payload = Vec::new();
293        for y in 0..4 {
294            for x in 0..4 {
295                let v: u16 = match (x % 2, y % 2) {
296                    (0, 0) => 0xC8F,
297                    (1, 1) => 0x323,
298                    _ => 0x64A,
299                };
300                payload.extend_from_slice(&v.to_le_bytes());
301            }
302        }
303        let file = encode_frame(
304            &frame(PixelFormat::BayerRG12, 4, 4, &payload),
305            ImageFormat::Png,
306        )
307        .unwrap();
308        let (colour, depth, sbit, samples) = read_png(&file);
309        assert_eq!(
310            (colour, depth),
311            (png::ColorType::Rgb, png::BitDepth::Sixteen)
312        );
313        assert_eq!(sbit, Some(vec![12, 12, 12]));
314        // (1, 1) is a blue site with four red diagonals and four green
315        // neighbours, all inside the image: R 0xC8F → 0xC8FC,
316        // G 0x64A → 0x64A6, B 0x323 → 0x3233.
317        let at = (4 + 1) * 3 * 2;
318        assert_eq!(&samples[at..at + 6], [0xC8, 0xFC, 0x64, 0xA6, 0x32, 0x33]);
319    }
320
321    /// 8- and 16-bit samples go in unchanged, and carry no `sBIT`.
322    #[test]
323    fn whole_byte_depths_are_written_as_they_are() {
324        let file = encode_frame(
325            &frame(PixelFormat::Mono8, 2, 1, &[7, 250]),
326            ImageFormat::Png,
327        )
328        .unwrap();
329        assert_eq!(
330            read_png(&file),
331            (
332                png::ColorType::Grayscale,
333                png::BitDepth::Eight,
334                None,
335                vec![7, 250]
336            )
337        );
338        let file = encode_frame(
339            &frame(PixelFormat::Mono16, 1, 1, &[0x34, 0x12]),
340            ImageFormat::Png,
341        )
342        .unwrap();
343        assert_eq!(
344            read_png(&file),
345            (
346                png::ColorType::Grayscale,
347                png::BitDepth::Sixteen,
348                None,
349                vec![0x12, 0x34]
350            )
351        );
352        let file = encode_frame(
353            &frame(PixelFormat::BGR8Packed, 1, 1, &[1, 2, 3]),
354            ImageFormat::Png,
355        )
356        .unwrap();
357        assert_eq!(
358            read_png(&file),
359            (
360                png::ColorType::Rgb,
361                png::BitDepth::Eight,
362                None,
363                vec![3, 2, 1]
364            )
365        );
366    }
367
368    #[test]
369    fn colour_can_be_asked_for() {
370        let pixels = viva_pfnc::convert::full_depth(PixelFormat::Mono8, 1, 1, None, &[9]).unwrap();
371        let file = encode(&pixels.into_rgb(), 1, 1, ImageFormat::Png).unwrap();
372        assert_eq!(
373            read_png(&file),
374            (
375                png::ColorType::Rgb,
376                png::BitDepth::Eight,
377                None,
378                vec![9, 9, 9]
379            )
380        );
381    }
382
383    /// The same samples as the PNG, in an uncompressed TIFF.
384    #[test]
385    fn mono12_is_a_16_bit_grey_tiff() {
386        let file = encode_frame(
387            &frame(PixelFormat::Mono12p, 2, 1, &[0xBC, 0x3A, 0x12]),
388            ImageFormat::Tiff,
389        )
390        .unwrap();
391        let mut decoder = tiff::decoder::Decoder::new(Cursor::new(file)).unwrap();
392        assert_eq!(decoder.dimensions().unwrap(), (2, 1));
393        assert_eq!(decoder.colortype().unwrap(), tiff::ColorType::Gray(16));
394        let mut image = tiff::decoder::DecodingResult::U16(Vec::new());
395        decoder.read_image_to_buffer(&mut image).unwrap();
396        let tiff::decoder::DecodingResult::U16(samples) = image else {
397            panic!("16-bit samples expected");
398        };
399        assert_eq!(samples, [0xABCA, 0x1231]);
400    }
401
402    #[test]
403    fn rgb_is_an_8_bit_rgb_tiff() {
404        let file = encode_frame(
405            &frame(PixelFormat::BGR8Packed, 1, 1, &[1, 2, 3]),
406            ImageFormat::Tiff,
407        )
408        .unwrap();
409        let mut decoder = tiff::decoder::Decoder::new(Cursor::new(file)).unwrap();
410        assert_eq!(decoder.colortype().unwrap(), tiff::ColorType::RGB(8));
411        let mut image = tiff::decoder::DecodingResult::U8(Vec::new());
412        decoder.read_image_to_buffer(&mut image).unwrap();
413        assert!(matches!(image, tiff::decoder::DecodingResult::U8(v) if v == [3, 2, 1]));
414    }
415
416    #[test]
417    fn the_format_comes_from_the_extension() {
418        for (path, format) in [
419            ("a.png", Some(ImageFormat::Png)),
420            ("dir/b.PNG", Some(ImageFormat::Png)),
421            ("c.tif", Some(ImageFormat::Tiff)),
422            ("d.tiff", Some(ImageFormat::Tiff)),
423            ("e.pgm", None),
424            ("f", None),
425        ] {
426            assert_eq!(ImageFormat::from_path(Path::new(path)), format, "{path}");
427        }
428    }
429
430    #[test]
431    fn an_unconvertible_frame_is_an_error() {
432        assert!(matches!(
433            encode_frame(
434                &frame(PixelFormat::Coord3DC32f, 1, 1, &[0; 4]),
435                ImageFormat::Png
436            ),
437            Err(ImageIoError::Convert(_))
438        ));
439    }
440}