nlfiedler / magick-rust

Rust bindings for ImageMagick
https://crates.io/crates/magick_rust
Apache License 2.0
246 stars 63 forks source link

Removing background of image #103

Open weiying-chen opened 1 year ago

weiying-chen commented 1 year ago

Currently, is there a way to accomplish that? In order words, is there a way to replicate this?

#!/bin/bash

for f in *.png; do
  # Remove background
  magick "$f" \
    -fill none -fuzz 75% -draw "alpha 0,0 floodfill" \
    "temp_no_background_$f"
done

I asked this question on Reddit:

https://www.reddit.com/r/learnrust/comments/12ql8hi/removing_background_of_image_using_magickrust/

nlfiedler commented 1 year ago

I don't know the answer to that specific question. However, if you can determine the functions in the MagickWand API that would facilitate this, then you can take a look at the docs for this crate [1] to see if those functions are already exposed. If not, then we can add wrappers for those functions, it's pretty easy to do.

[1] https://nlfiedler.github.io/magick-rust/magick_rust/struct.MagickWand.html

crat0z commented 1 year ago

I also was looking for something that works like OP, in my case I'm trying to detect white backgrounds to make it transparent. Essentially, I make a white border around the image 1 pixel wide and then use MagickFloodfillPaintImage like so:

fn try_floodfill(data: &Vec<u8>, fuzzy: f64) -> Result<Vec<u8>, Error> {
    magick_wand_genesis();

    let mw = MagickWand::new();

    mw.read_image_blob(data)?;

    let mut fw = PixelWand::new();
    let mut bw = PixelWand::new();

    fw.set_color("none")?;
    bw.set_color("white")?;

    mw.border_image(
        &bw,
        1,
        1,
        magick_rust::bindings::CompositeOperator_OverCompositeOp,
    )?;

    unsafe {
        magick_rust::bindings::MagickFloodfillPaintImage(
            mw.wand,
            fw.wand,
            fuzzy,
            bw.wand,
            0,
            0,
            MagickBooleanType_MagickFalse,
        );
    }

    Ok(mw.write_image_blob("png")?)
}

This works for me but it'd be nice if there was a safe function to call on MagickWand