I am trying to remove the white background of few images programmatically and make it transparent. The format of the image is simple, it has a white background and a single object mainly positioned in the middle.
I want to replicate the functionality of the https://remove.bg website which makes the background of the image transparent.
I have tried using sharp or imageMagick software to make the background transparent. But it makes some of the pixels inside the main object become transparent too. Which I definitely don't want.
Was using the below code in imageMagik to convert the white background to transparent
convert brownie.jpg -transparent white brownie.png
convert cakebig.jpg -fuzz 1% -transparent white cakebig.png
Didn't seem to work perfectly.
After running the commands, the images did become transparent but few of the pixels inside the main object got affected too.
Input Image

Output from ImageMagik (See how some of the pixels inside main object got transparent)

Expected Output from https://remove.bg (See no effect on the main object)

It seems like an image processing problem and seems like OpenCV is the best solution for this. I don't know much about the library so it's a little tricky. Was checking out some code and came across grab cut and graph cut algorithm which can be used for image segmentation. But I am not totally sure about it. Please help in the proper solution to this in OpenCV.
I will add a little more to Mark Setchell's excellent ImageMagick answer about using a fuzzy flood fill by adding some antialiasing via blurring the alpha channel a little and then zeroing blurred values below mid-gray. This will smooth the jagged edges left from the fuzzy flood fill. Note too large a fuzz value will cause leakage into your ice cream, because the color of the ice cream is similar to that of the background. Too little fuzz value will not adequately remove the background. So the fuzz value tolerance in this image is tight.
Input:

For ImageMagick 6:
convert img.png -fuzz 2% -fill none -draw "matte 0,0 floodfill" -channel alpha -blur 0x2 -level 50x100% +channel result.png
For Imagemagick 7:
magick img.png -fuzz 2% -fill none -draw "alpha 0,0 floodfill" -channel alpha -blur 0x2 -level 50x100% +channel result.png

You will need to download the result to see that the background is transparent and the outline is smooth.
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