我正在使用 Piston 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");
}
这个例子会出现错误信息。
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>)
我理解这是正确的,因为文档提到我想要的方法是 Pixel trait 的一部分 - 文档并没有清楚地说明如何从已加载的图像缓冲区中访问单个像素,它主要讨论从 ImageBuffer
获取像素。
如何迭代图像中的所有像素并从中获取rgb/其他值?
编辑:阅读源代码后,我通过调用 Pixel::channels(&self)
来解决了这个问题,它需要 &self
,因此我发现这必须是通过 trait 添加到实现 Pixel 的对象的方法。
所以 channel_count()
的签名既没有参数也没有 &self
。我应该如何调用这个方法?
channel_count
是Pixel
实例的一个方法。 - Max