How do I get a vector of u8 RGB values when using

2020-04-16 03:23发布

I need to take an image and get a list of RGB byte values. I am using the image crate. This is what I have:

extern crate image;

fn main() {
    let im = image::open("wall.jpg").unwrap().to_rgb();
    let data: Vec<[u8; 3]> = im.pixels().flat_map(|p| vec![p.data]).collect();
    let rgb: Vec<&u8> = data.iter().flat_map(|p| p.iter()).collect();
    println!("First Pixel: {} {} {}", rgb[0], rgb[1], rgb[2]);
}

This seems pretty ugly. I have to introduce an intermediate variable and I get a vector of pointers to the values I really need, so before I can do something else, I would have to map over it again to get the actual values.

All I want is a vector of u8. How do I get that?

标签: rust
1条回答
男人必须洒脱
2楼-- · 2020-04-16 04:06

Well, if you just want the raw data itself, you can just call DynamicImage::raw_pixels:

let im = image::open("wall.jpg").unwrap().to_rbg();
let rgb: Vec<u8> = im.raw_pixels();

If all you're actually interested in is the first pixel though, I'd recommend calling GenericImage::get_pixel:

let im = image::open("wall.jpg").unwrap();
let first_pixel = im.get_pixel(0, 0);

Which you can then turn into a [u8; 3] array of RGB data:

let rgb = first_pixel.to_rbg();
println!("First Pixel: {} {} {}", rgb.data[0], rgb.data[1], rgb.data[2]);
查看更多
登录 后发表回答