如何在 Rust 中读取图像中的像素值

Max*_*Max 5 image-processing rust

我正在使用活塞 Rust 图像库(版本 0.10.3),如下所示:

extern crate image;

use std::f32;
use std::fs::File;
use std::path::Path;


use image::GenericImage;
use image::Pixels;
use image::Pixel;

fn init(input_path: &str) {
    let mut img = image::open(&Path::new(input_path)).unwrap();

    let img_width = img.dimensions().0;
    let img_height = img.dimensions().1;

    for p in img.pixels() { println!("pixel: {}", p.2.channel_count()); }
}

fn main() {
    init("file.png");
}
Run Code Online (Sandbox Code Playgroud)

此示例失败并显示错误消息

error: no method named `channel_count` found for type `image::Rgba<u8>` in the current scope
  --> src/main.rs:20:55
   |
20 |     for p in img.pixels() { println!("pixel: {}", p.2.channel_count()); }
   |                                                       ^^^^^^^^^^^^^
<std macros>:2:27: 2:58 note: in this expansion of format_args!
<std macros>:3:1: 3:54 note: in this expansion of print! (defined in <std macros>)
src/main.rs:20:29: 20:72 note: in this expansion of println! (defined in <std macros>)
   |
   = note: found the following associated functions; to be used as methods, functions must have a `self` parameter
note: candidate #1 is defined in the trait `image::Pixel`
  --> src/main.rs:20:55
   |
20 |     for p in img.pixels() { println!("pixel: {}", p.2.channel_count()); }
   |                                                       ^^^^^^^^^^^^^
<std macros>:2:27: 2:58 note: in this expansion of format_args!
<std macros>:3:1: 3:54 note: in this expansion of print! (defined in <std macros>)
src/main.rs:20:29: 20:72 note: in this expansion of println! (defined in <std macros>)
Run Code Online (Sandbox Code Playgroud)

我理解这是真的,因为文档提到我想要的方法是Pixel 特征的一部分- 文档并没有真正说明如何访问从现有图像加载的缓冲区中的单个像素,它主要是谈论从 获取像素ImageBuffer

如何迭代图像中的所有像素并从中获取 RGB/其他值?

Pixel::channels(&self)编辑:阅读源代码后,我通过调用whichtake解决了这个问题&self,因此我发现这必须是通过特征添加到实现Pixel的对象的方法。

所以 的签名channel_count()既没有参数也没有&self。我应该如何调用这个方法?

pah*_*olg 4

您尝试调用的函数channel_count()是静态方法。它是为类型定义的,而不是为该类型的对象定义的。你用它来称呼它

Rgba::channel_count()
Run Code Online (Sandbox Code Playgroud)

或者

<Rgba<u8> as Pixel>::channel_count()
Run Code Online (Sandbox Code Playgroud)

因为第一种形式可能会由于缺乏类型信息而失败(在这种情况下)。

但是,我认为它不会给你你想要的。它应该只返回数字,4因为这是具有的通道数Rgba

要获得您想要的 RGB 值,请查看您所拥有的类型的文档,Rgba.

它有一个公共成员 ,data它是一个 4 元素数组,并且它实现Index.

如果pixel是 类型Rgba<u8>(对应于您的),您可以通过调用将它们作为数组提供给您或通过索引来p.2获取您寻求的值。pixel.data例如,pixel[0]会给你红色值。