Skip to main content

lensbench_export/
image.rs

1//! 格子の画像(16 bit TIFF・32 bit float TIFF・16 bit PNG)。外部の画像ライブラリなしで、
2//! TIFF は非圧縮・ストリップ 1 本・リトルエンディアン、PNG は 16 bit グレー(像の模擬は 16 bit の RGB も、読むのは png の crate)。
3//! 画像の行 0 = 上 = y の最大(格子は行 0 = y の最小で渡す)。説明(JSON)は TIFF の ImageDescription にも入れる。
4
5use std::path::Path;
6
7/// 画像の形式
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum ImageFormat {
10    Tiff16,
11    TiffFloat,
12    Png16,
13}
14
15impl ImageFormat {
16    /// 拡張子から(tif・tiff は 16 bit、float なら 32 bit float)
17    pub fn from_path(p: &Path, float: bool) -> Option<ImageFormat> {
18        let e = p.extension()?.to_str()?.to_ascii_lowercase();
19        match e.as_str() {
20            "tif" | "tiff" => Some(if float {
21                ImageFormat::TiffFloat
22            } else {
23                ImageFormat::Tiff16
24            }),
25            "png" => Some(ImageFormat::Png16),
26            _ => None,
27        }
28    }
29}
30
31/// 格子 `grid`(nx × ny、行 0 = y の最小)を画像の行の並び(行 0 = 上)にして 16 bit に割り付ける。
32/// `scale`: Some((lo, hi)) なら lo → 0、hi → 65535 に線形(NaN は 0)、None なら値をそのまま丸める(生画像)
33pub fn to_u16(grid: &[f64], nx: usize, ny: usize, scale: Option<(f64, f64)>) -> Vec<u16> {
34    let mut u = vec![0u16; nx * ny];
35    for r in 0..ny {
36        for i in 0..nx {
37            let v = grid[(ny - 1 - r) * nx + i];
38            let w = if v.is_nan() {
39                0.0
40            } else {
41                match scale {
42                    Some((lo, hi)) => (v - lo) / (hi - lo) * 65535.0,
43                    None => v,
44                }
45            };
46            u[r * nx + i] = w.round_ties_even().clamp(0.0, 65535.0) as u16;
47        }
48    }
49    u
50}
51
52/// 値の範囲(NaN を除く)。幅がなければ (0, 1)
53pub fn data_range(grid: &[f64]) -> (f64, f64) {
54    let (mut lo, mut hi) = (f64::MAX, f64::MIN);
55    for &v in grid {
56        if !v.is_nan() {
57            lo = lo.min(v);
58            hi = hi.max(v);
59        }
60    }
61    if hi > lo {
62        (lo, hi)
63    } else {
64        (0.0, 1.0)
65    }
66}
67
68/// TIFF(16 bit の値 `u`、または 32 bit float の値 `f`。行 0 = 上)を書く。`description` は ASCII にして入れる
69pub fn write_tiff(
70    path: &Path,
71    nx: usize,
72    ny: usize,
73    u: Option<&[u16]>,
74    f: Option<&[f32]>,
75    description: &str,
76    software: &str,
77) -> std::io::Result<()> {
78    let float = f.is_some();
79    let (bps, fmt) = if float { (32u32, 3u32) } else { (16, 1) };
80    let mut desc: Vec<u8> = description
81        .chars()
82        .flat_map(|c| {
83            if (c as u32) < 128 {
84                vec![c as u8]
85            } else {
86                // BMP の外はサロゲートの対で(JSON のまま読める)
87                let mut b = [0u16; 2];
88                c.encode_utf16(&mut b)
89                    .iter()
90                    .flat_map(|x| format!("\\u{x:04x}").into_bytes())
91                    .collect()
92            }
93        })
94        .collect();
95    desc.push(0);
96    let mut soft = software.as_bytes().to_vec();
97    soft.push(0);
98    let data_bytes = (nx * ny) as u32 * bps / 8;
99    let off_desc = 8u32;
100    let off_soft = off_desc + desc.len() as u32;
101    let mut off_data = off_soft + soft.len() as u32;
102    off_data += off_data & 1;
103    let mut off_ifd = off_data + data_bytes;
104    off_ifd += off_ifd & 1;
105    let tags: [(u16, u16, u32, u32); 13] = [
106        (256, 4, 1, nx as u32),
107        (257, 4, 1, ny as u32),
108        (258, 3, 1, bps),
109        (259, 3, 1, 1),
110        (262, 3, 1, 1),
111        (270, 2, desc.len() as u32, off_desc),
112        (273, 4, 1, off_data),
113        (277, 3, 1, 1),
114        (278, 4, 1, ny as u32),
115        (279, 4, 1, data_bytes),
116        (284, 3, 1, 1),
117        (305, 2, soft.len() as u32, off_soft),
118        (339, 3, 1, fmt),
119    ];
120    let mut b: Vec<u8> = Vec::with_capacity(off_ifd as usize + 200);
121    b.extend_from_slice(b"II");
122    b.extend_from_slice(&42u16.to_le_bytes());
123    b.extend_from_slice(&off_ifd.to_le_bytes());
124    b.extend_from_slice(&desc);
125    b.extend_from_slice(&soft);
126    b.resize(off_data as usize, 0);
127    if let Some(f) = f {
128        for v in f {
129            b.extend_from_slice(&v.to_le_bytes());
130        }
131    } else if let Some(u) = u {
132        for v in u {
133            b.extend_from_slice(&v.to_le_bytes());
134        }
135    }
136    b.resize(off_ifd as usize, 0);
137    b.extend_from_slice(&(tags.len() as u16).to_le_bytes());
138    for (tag, typ, count, value) in tags {
139        b.extend_from_slice(&tag.to_le_bytes());
140        b.extend_from_slice(&typ.to_le_bytes());
141        b.extend_from_slice(&count.to_le_bytes());
142        if typ == 3 && count == 1 {
143            b.extend_from_slice(&(value as u16).to_le_bytes());
144            b.extend_from_slice(&0u16.to_le_bytes());
145        } else {
146            b.extend_from_slice(&value.to_le_bytes());
147        }
148    }
149    b.extend_from_slice(&0u32.to_le_bytes());
150    lensbench_core::vfs::write(path, b)
151}
152
153/// TIFF([`write_tiff`] で書いたもの)を読み戻す: 値(行 0 = 上)と nx・ny
154pub fn read_tiff(path: &Path) -> std::io::Result<(Vec<f64>, usize, usize)> {
155    let b = lensbench_core::vfs::read(path)?;
156    let bad = || std::io::Error::new(std::io::ErrorKind::InvalidData, "TIFF");
157    let u16at = |o: usize| {
158        b.get(o..o + 2)
159            .map(|s| u16::from_le_bytes([s[0], s[1]]))
160            .ok_or_else(bad)
161    };
162    let u32at = |o: usize| {
163        b.get(o..o + 4)
164            .map(|s| u32::from_le_bytes([s[0], s[1], s[2], s[3]]))
165            .ok_or_else(bad)
166    };
167    let ifd = u32at(4)? as usize;
168    let n = u16at(ifd)? as usize;
169    let (mut nx, mut ny, mut off, mut bps, mut fmt) = (0usize, 0usize, 0usize, 16u32, 1u32);
170    for k in 0..n {
171        let e = ifd + 2 + 12 * k;
172        let (tag, typ) = (u16at(e)?, u16at(e + 2)?);
173        let val = if typ == 3 {
174            u16at(e + 8)? as u32
175        } else {
176            u32at(e + 8)?
177        };
178        match tag {
179            256 => nx = val as usize,
180            257 => ny = val as usize,
181            258 => bps = val,
182            273 => off = val as usize,
183            339 => fmt = val,
184            _ => {}
185        }
186    }
187    let mut v = vec![0.0; nx * ny];
188    for (i, x) in v.iter_mut().enumerate() {
189        *x = if bps == 32 && fmt == 3 {
190            f32::from_bits(u32at(off + 4 * i)?) as f64
191        } else {
192            u16at(off + 2 * i)? as f64
193        };
194    }
195    Ok((v, nx, ny))
196}
197
198/// 16 bit グレーの PNG(行 0 = 上)
199pub fn write_png16(path: &Path, nx: usize, ny: usize, u: &[u16]) -> std::io::Result<()> {
200    let mut buf = Vec::new();
201    let mut e = png::Encoder::new(&mut buf, nx as u32, ny as u32);
202    e.set_color(png::ColorType::Grayscale);
203    e.set_depth(png::BitDepth::Sixteen);
204    let mut w = e.write_header().map_err(std::io::Error::other)?;
205    let mut data = Vec::with_capacity(nx * ny * 2);
206    for v in u {
207        data.extend_from_slice(&v.to_be_bytes());
208    }
209    w.write_image_data(&data).map_err(std::io::Error::other)?;
210    w.finish().map_err(std::io::Error::other)?;
211    lensbench_core::vfs::write(path, buf)
212}
213
214/// PNG を読む(グレー・RGB、8・16 bit、パレット・α 付きも。α は捨てる): (幅, 高さ, チャンネル(1 か 3、行 0 = 上、0〜1))
215pub fn read_png(path: &Path) -> std::io::Result<(usize, usize, Vec<Vec<f64>>)> {
216    let b = lensbench_core::vfs::read(path)?;
217    let mut d = png::Decoder::new(std::io::Cursor::new(b));
218    d.set_transformations(png::Transformations::EXPAND);
219    let mut r = d.read_info().map_err(std::io::Error::other)?;
220    let mut buf = vec![0; r.output_buffer_size()];
221    let info = r.next_frame(&mut buf).map_err(std::io::Error::other)?;
222    let (w, h) = (info.width as usize, info.height as usize);
223    let (bytes, max) = match info.bit_depth {
224        png::BitDepth::Sixteen => (2, 65535.0),
225        png::BitDepth::Eight => (1, 255.0),
226        d => return Err(std::io::Error::other(format!("PNG bit depth {d:?}"))),
227    };
228    let (nc, color) = match info.color_type {
229        png::ColorType::Grayscale => (1, 1),
230        png::ColorType::GrayscaleAlpha => (2, 1),
231        png::ColorType::Rgb => (3, 3),
232        png::ColorType::Rgba => (4, 3),
233        c => return Err(std::io::Error::other(format!("PNG color type {c:?}"))),
234    };
235    let at = |k: usize| -> f64 {
236        let o = k * bytes;
237        let v = if bytes == 2 {
238            u16::from_be_bytes([buf[o], buf[o + 1]]) as f64
239        } else {
240            buf[o] as f64
241        };
242        v / max
243    };
244    let line = info.line_size / bytes;
245    let ch = (0..color)
246        .map(|c| {
247            (0..w * h)
248                .map(|k| at((k / w) * line + (k % w) * nc + c))
249                .collect()
250        })
251        .collect();
252    Ok((w, h, ch))
253}
254
255/// 16 bit の PNG(チャンネル 1 ならグレー、3 なら RGB。値は 0〜1 を 0〜65535 に、外は切る。行 0 = 上)
256pub fn write_png16_channels(
257    path: &Path,
258    w: usize,
259    h: usize,
260    ch: &[Vec<f64>],
261) -> std::io::Result<()> {
262    let mut buf = Vec::new();
263    let mut e = png::Encoder::new(&mut buf, w as u32, h as u32);
264    e.set_color(if ch.len() == 3 {
265        png::ColorType::Rgb
266    } else {
267        png::ColorType::Grayscale
268    });
269    e.set_depth(png::BitDepth::Sixteen);
270    let mut wr = e.write_header().map_err(std::io::Error::other)?;
271    let mut data = Vec::with_capacity(w * h * 2 * ch.len());
272    for k in 0..w * h {
273        for c in ch {
274            let v = c[k];
275            let u = if v.is_finite() {
276                (v.clamp(0.0, 1.0) * 65535.0).round() as u16
277            } else {
278                0
279            };
280            data.extend_from_slice(&u.to_be_bytes());
281        }
282    }
283    wr.write_image_data(&data).map_err(std::io::Error::other)?;
284    wr.finish().map_err(std::io::Error::other)?;
285    lensbench_core::vfs::write(path, buf)
286}
287
288/// JSON の説明を横に書く(拡張子を .json に)
289pub fn write_sidecar(path: &Path, json: &str) -> std::io::Result<()> {
290    lensbench_core::vfs::write(path.with_extension("json"), json)
291}
292
293#[cfg(test)]
294mod tests {
295    use super::*;
296
297    #[test]
298    fn png_channels_read_back() {
299        let dir = std::env::temp_dir().join(format!("lb_png_{}", std::process::id()));
300        lensbench_core::vfs::create_dir_all(&dir).unwrap();
301        let f = dir.join("c.png");
302        let ch = vec![
303            vec![0.0, 0.5, 1.0, 2.0],
304            vec![1.0, 0.0, 0.25, 0.0],
305            vec![0.0; 4],
306        ];
307        write_png16_channels(&f, 2, 2, &ch).unwrap();
308        let (w, h, back) = read_png(&f).unwrap();
309        assert_eq!((w, h, back.len()), (2, 2, 3));
310        assert!((back[0][1] - 0.5).abs() < 1e-4 && back[0][3] == 1.0 && back[1][2] > 0.24);
311        let _ = std::fs::remove_dir_all(&dir);
312    }
313
314    #[test]
315    fn tiff_reads_back() {
316        let dir = std::env::temp_dir().join(format!("lb_img_{}", std::process::id()));
317        lensbench_core::vfs::create_dir_all(&dir).unwrap();
318        let grid = vec![0.0, 1.0, 2.0, f64::NAN, 4.0, 5.0];
319        let u = to_u16(&grid, 3, 2, Some((0.0, 5.0)));
320        // 行 0 = 上 = 格子の最後の行
321        assert_eq!(u, vec![0, 52428, 65535, 0, 13107, 26214]);
322        let p = dir.join("a.tif");
323        write_tiff(&p, 3, 2, Some(&u), None, "{\"a\": \"µ\"}", "lensbench").unwrap();
324        let (v, nx, ny) = read_tiff(&p).unwrap();
325        assert_eq!((nx, ny), (3, 2));
326        assert_eq!(v, u.iter().map(|&x| x as f64).collect::<Vec<_>>());
327        let f: Vec<f32> = vec![1.5, f32::NAN, -2.0, 3.0];
328        let p2 = dir.join("b.tif");
329        write_tiff(&p2, 2, 2, None, Some(&f), "{}", "lensbench").unwrap();
330        let (v2, _, _) = read_tiff(&p2).unwrap();
331        assert_eq!(v2[0], 1.5);
332        assert!(v2[1].is_nan());
333        write_png16(&dir.join("c.png"), 3, 2, &u).unwrap();
334        let _ = std::fs::remove_dir_all(&dir);
335    }
336}