//! 图像加载与二值化 //! //! 使用 `image` crate 加载 PNG/JPEG/WebP,转为灰度再二值化为布尔矩阵。 /// 从图像字节加载并二值化 /// /// 步骤:解码 → 灰度 → 按中位数阈值二值化 pub(crate) fn load_and_binarize(bytes: &[u8]) -> Result>, String> { let img = image::load_from_memory(bytes).map_err(|e| format!("图像解码失败: {e}"))?; let gray = img.to_luma8(); let (w, h) = gray.dimensions(); let width = w as usize; let height = h as usize; // 计算中位数阈值 let mut all_pixels: Vec = gray.iter().copied().collect(); all_pixels.sort_unstable(); let threshold = all_pixels[all_pixels.len() / 2]; // 二值化:像素 < 阈值 → true(暗模块),否则 false(亮模块) let matrix: Vec> = (0..height) .map(|y| { (0..width) .map(|x| gray.get_pixel(x as u32, y as u32).0[0] < threshold) .collect() }) .collect(); Ok(matrix) }