保存图像文件 根据文件扩展名自动决定格式。
(path: P, mat: &Mat)
| 37 | /// |
| 38 | /// 根据文件扩展名自动决定格式。 |
| 39 | pub fn imwrite<P: AsRef<Path>>(path: P, mat: &Mat) -> Result<()> { |
| 40 | if mat.channels != 3 { |
| 41 | return Err(anyhow!( |
| 42 | "Only 3-channel (BGR) images are supported for saving currently" |
| 43 | )); |
| 44 | } |
| 45 | |
| 46 | // 1. BGR -> RGB 转换 |
| 47 | // image crate save 需要 RGB |
| 48 | let pixel_count = (mat.rows * mat.cols) as usize; |
| 49 | let mut rgb_data = Vec::with_capacity(pixel_count * 3); |
| 50 | |
| 51 | for r in 0..mat.rows { |
| 52 | let row = mat.row_bytes(r); |
| 53 | for c in 0..mat.cols as usize { |
| 54 | let offset = c * 3; |
| 55 | let b = row[offset]; |
| 56 | let g = row[offset + 1]; |
| 57 | let r = row[offset + 2]; |
| 58 | |
| 59 | rgb_data.push(r); |
| 60 | rgb_data.push(g); |
| 61 | rgb_data.push(b); |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | // 2. 保存 |
| 66 | image::save_buffer( |
| 67 | path, |
| 68 | &rgb_data, |
| 69 | mat.cols as u32, |
| 70 | mat.rows as u32, |
| 71 | image::ColorType::Rgb8, |
| 72 | ) |
| 73 | .map_err(|e| anyhow!("Failed to save image: {}", e))?; |
| 74 | |
| 75 | Ok(()) |
| 76 | } |