1use num_traits::AsPrimitive;
2
3pub mod cam2;
4pub mod cam3;
5pub mod canvas_bitmap;
6pub mod canvas_gif;
7pub mod canvas_svg;
8pub mod colmap;
9pub mod color;
10pub mod colormap;
11pub mod morphology;
12pub mod rasterize_aabb3;
13pub mod rasterize_circle;
14pub mod rasterize_line;
15pub mod rasterize_polygon;
16pub mod rasterize_triangle;
17pub mod raycast_trimesh2;
18pub mod raycast_trimesh3;
19pub mod splat_circle;
20pub mod splat_gaussian2;
21pub mod splat_point2;
22pub mod splat_point3;
23pub mod texture;
24pub mod tile_acceleration;
25
26pub fn write_png_from_float_image_grayscale<Real, Path>(
27 path: Path,
28 img_shape: &(usize, usize),
29 img: &[Real],
30) -> anyhow::Result<()>
31where
32 Real: num_traits::Float + 'static + Copy + AsPrimitive<u8>,
33 usize: AsPrimitive<Real>,
34 Path: AsRef<std::path::Path>,
35{
36 let pix2color_u8: Vec<u8> = img
37 .iter()
38 .map(|&v| {
39 let a: Real = v.clamp(Real::zero(), Real::one());
40 (a * 255.as_()).as_()
41 })
42 .collect();
43 let file = std::fs::File::create(path)?;
44 let w = std::io::BufWriter::new(file);
45 let mut encoder = png::Encoder::new(
46 w,
47 img_shape.0.try_into().unwrap(),
48 img_shape.1.try_into().unwrap(),
49 ); encoder.set_color(png::ColorType::Grayscale);
51 encoder.set_depth(png::BitDepth::Eight);
52 let mut writer = encoder.write_header()?;
53 writer.write_image_data(&pix2color_u8)?; Ok(())
55}
56
57pub fn write_png_from_float_image_rgb<Real, Path>(
58 path: Path,
59 img_shape: &(usize, usize),
60 img: &[Real],
61) -> anyhow::Result<()>
62where
63 Real: num_traits::Float + 'static + Copy + AsPrimitive<u8>,
64 usize: AsPrimitive<Real>,
65 Path: AsRef<std::path::Path>,
66{
67 let zero = Real::zero();
68 let one = Real::one();
69 let v255: Real = 255usize.as_();
70 let pix2color_u8: Vec<u8> = img
71 .iter()
72 .map(|&v| {
73 let a: Real = v.clamp(zero, one);
74 (a * v255).as_()
75 })
76 .collect();
77 let file = std::fs::File::create(path)?;
78 let w = std::io::BufWriter::new(file);
79 let mut encoder = png::Encoder::new(w, img_shape.0.try_into()?, img_shape.1.try_into()?); encoder.set_color(png::ColorType::Rgb);
81 encoder.set_depth(png::BitDepth::Eight);
82 let mut writer = encoder.write_header()?;
83 writer.write_image_data(&pix2color_u8)?; Ok(())
85}
86
87pub fn load_image_as_float_array<P>(path: P) -> anyhow::Result<(Vec<f32>, (usize, usize), usize)>
88where
89 P: AsRef<std::path::Path>,
90{
91 use image::GenericImageView;
92 let img_trg = image::open(path)?;
93 let (width, height) = img_trg.dimensions();
94 let (width, height) = (width as usize, height as usize);
95 let depth: usize = img_trg.color().bytes_per_pixel().into();
96 let img_trg = img_trg.into_bytes();
97 let img_trg: Vec<f32> = img_trg.iter().map(|&v| (v as f32) / 255.0f32).collect();
98 assert_eq!(img_trg.len(), width * height * depth);
99 Ok((img_trg, (width, height), depth))
100}