Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a picture in pure black and white in Rust

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?

like image 984
beep Avatar asked Nov 26 '25 18:11

beep


1 Answers

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.

like image 106
Denys Séguret Avatar answered Nov 29 '25 09:11

Denys Séguret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!