ndarray_vision/format/
mod.rs

1use crate::core::traits::PixelBound;
2use crate::core::*;
3use ndarray::Data;
4use num_traits::cast::{FromPrimitive, NumCast};
5use num_traits::{Num, NumAssignOps};
6use std::fmt::Display;
7use std::fs::{read, File};
8use std::io::prelude::*;
9use std::path::Path;
10
11/// Trait for an image encoder
12pub trait Encoder<T, U, C>
13where
14    U: Data<Elem = T>,
15    T: Copy + Clone + Num + NumAssignOps + NumCast + PartialOrd + Display + PixelBound,
16    C: ColourModel,
17{
18    /// Encode an image into a sequence of bytes for the given format
19    fn encode(&self, image: &ImageBase<U, C>) -> Vec<u8>;
20
21    /// Encode an image saving it to the file at filename. This function shouldn't
22    /// add an extension preferring the user to do that instead.
23    fn encode_file<P: AsRef<Path>>(
24        &self,
25        image: &ImageBase<U, C>,
26        filename: P,
27    ) -> std::io::Result<()> {
28        let mut file = File::create(filename)?;
29        file.write_all(&self.encode(image))?;
30        Ok(())
31    }
32}
33
34/// Trait for an image decoder, use this to get an image from a byte stream
35pub trait Decoder<T, C>
36where
37    T: Copy
38        + Clone
39        + FromPrimitive
40        + Num
41        + NumAssignOps
42        + NumCast
43        + PartialOrd
44        + Display
45        + PixelBound,
46    C: ColourModel,
47{
48    /// From the bytes decode an image, will perform any scaling or conversions
49    /// required to represent elements with type T.
50    fn decode(&self, bytes: &[u8]) -> std::io::Result<Image<T, C>>;
51    /// Given a filename decode an image performing any necessary conversions.
52    fn decode_file<P: AsRef<Path>>(&self, filename: P) -> std::io::Result<Image<T, C>> {
53        let bytes = read(filename)?;
54        self.decode(&bytes)
55    }
56}
57
58/// Netpbm refers to a collection of image formats used and defined by the Netpbm
59/// project. These include the portable pixmap format (PPM), portable graymap
60/// format (PGM), and portable bitmap format (PBM)
61pub mod netpbm;