我使用的是piston Rust image library(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
,因此我想出了這必須是通過特性添加到實現Pixel的對象的方法。
所以channel_count()
的簽名既沒有參數也沒有&self
。我應該怎麼稱呼這種方法?
謝謝,我現在明白了。這非常令人困惑,我認爲'channel_count'應該是'Pixel'實例的一種方法。 – Max