MCPcopy Index your code
hub / github.com/RustCV/RustCV / imread

Function imread

rustcv/src/imgcodecs/mod.rs:9–34  ·  view source on GitHub ↗

读取图像文件 支持 JPG, PNG, BMP 等常见格式。 注意:这将强制转换为 BGR 格式以匹配 OpenCV 默认行为。

(path: P)

Source from the content-addressed store, hash-verified

7/// 支持 JPG, PNG, BMP 等常见格式。
8/// 注意:这将强制转换为 BGR 格式以匹配 OpenCV 默认行为。
9pub fn imread<P: AsRef<Path>>(path: P) -> Result<Mat> {
10 // 1. 使用 image crate 加载
11 let img = image::open(path).map_err(|e| anyhow!("Failed to open image: {}", e))?;
12
13 // 2. 转换为 RGB8 (统一格式)
14 let rgb = img.to_rgb8();
15 let (width, height) = (rgb.width() as i32, rgb.height() as i32);
16
17 // 3. 转换为 BGR (OpenCV 默认)
18 // 这是一个内存拷贝过程,但对于文件 IO 来说,性能瓶颈通常在磁盘读取,而不是这里的内存重排。
19 let pixel_count = (width * height) as usize;
20 let mut bgr_data = Vec::with_capacity(pixel_count * 3);
21
22 for pixel in rgb.pixels() {
23 let [r, g, b] = pixel.0;
24 bgr_data.push(b); // Blue first
25 bgr_data.push(g);
26 bgr_data.push(r); // Red last
27 }
28
29 // 4. 构造 Mat (Packed layout, so step = width * 3)
30 let mut mat = Mat::new(height, width, 3);
31 mat.data = bgr_data;
32
33 Ok(mat)
34}
35
36/// 保存图像文件
37///

Callers

nothing calls this directly

Calls 3

openFunction · 0.50
widthMethod · 0.45
heightMethod · 0.45

Tested by

no test coverage detected