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

5

我正在使用 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。我应该如何调用这个方法?

1个回答

4

您想调用的函数channel_count()是一个静态方法。它为一种类型定义,而不是该类型的对象。您可以使用以下方式调用:

Rgba::channel_count()

或者

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

由于缺少类型信息,第一个表单可能会失败(在这种情况下)。

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

要获取你想要的RGB值,请查看你所拥有类型Rgba的文档。

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

如果pixelRgba<u8>类型(对应于你的p.2),你可以通过调用pixel.data来将其作为数组给出或者进行索引。例如,pixel[0]将给出红色值。


谢谢,我现在明白了。这很令人困惑,我以为channel_countPixel实例的一个方法。 - Max

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接