Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a vector of u8 RGB values when using the image crate?

Tags:

rust

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?

like image 605
Mad Wombat Avatar asked Jun 12 '18 15:06

Mad Wombat


1 Answers

As of 0.23.12, to_rgb has been deprecated use DynamicImage::to_rgb8 or DynamicImage::to_bytes instead:

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

// Alternatively
let bytes = image::open("wall.jpg").unwrap().to_bytes();

Prior to 0.23.12, if you just want the raw data itself, you can just call DynamicImage::raw_pixels:

let im = image::open("wall.jpg").unwrap().to_rgb();
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]);
like image 135
Wesley Wiser Avatar answered Oct 06 '22 18:10

Wesley Wiser