Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Removing background of image #103

Open
weiying-chen opened this issue Apr 18, 2023 · 2 comments
Open

Removing background of image #103

weiying-chen opened this issue Apr 18, 2023 · 2 comments

Comments

@weiying-chen
Copy link

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/

@weiying-chen weiying-chen changed the title Removing background of images Removing background of image Apr 18, 2023
@nlfiedler
Copy link
Owner

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
Copy link

crat0z commented Apr 26, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants