I want to convert a picture in pure black and white(e.g. no grayscale) using Image crate, the result should be a picture with 0 and 255 RGB values.
Following the docs i've wrote the following:
let img = image::open("photo.jpg").unwrap(); // Load picture
let gray_img = img.grayscale(); // Convert it
// Access a random pixel value
let px = gray_img.get_pixel(0,0);
println!("{:?}", pixel.data); // Print RGB array
The problem here is that, whatever pixel i print, it gives me grayscale value. So, is there a function to convert an image in pure black and white? Something like Pillow's convert function for Python?
Here's how you can first build a grayscale image then dither it to a Black and White one:
use image::{self, imageops::*};
let img = image::open("cat.jpeg").unwrap();
let mut img = img.grayscale();
let mut img = img.as_mut_luma8().unwrap();
dither(&mut img, &BiLevel);
img.save("cat.png").unwrap(); // this step is optional but convenient for testing
You should of course properly handle errors instead of just doing unwrap.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With