2016-11-10 34 views
0

我使用的是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。我應該怎麼稱呼這種方法?

回答

0

您試圖調用的函數channel_count()是一種靜態方法。它被定義爲一個類型,而不是該類型的對象。你有

Rgba::channel_count() 

<Rgba<u8> as Pixel>::channel_count() 

的第一種形式很可能會失敗(在這種情況下)調用它由於缺乏類型信息。

但是,我不認爲它會給你你想要的。它應該只是返回號碼4,因爲這是Rgba具有的頻道數量。

要獲得您想要的RGB值,請查看您所用類型的文檔,Rgba

它有一個公開會員,data,它是一個4元素的數組,它實現了Index

如果pixelRgba<u8>型(相當於你p.2),你可以得到你尋求任何能夠給他們以你爲一個陣列,或者通過索引值通過調用pixel.data。例如,pixel[0]會給你紅色的價值。

+0

謝謝,我現在明白了。這非常令人困惑,我認爲'channel_count'應該是'Pixel'實例的一種方法。 – Max