n0nChun
n0nChun

Reputation: 740

Removing background using imagemagick, on a white product

Here's the original image I'm trying to remove background from:

enter image description here

I am trying to use imagemagick to remove the background from an image. When the image has a white product, my script doesn't work well. It removes the white from inside the product also. In brief I'm trying to do the following

If I use a fuzz factor of 0, like shown below, i get the background removed, but it creates a nasty halo around it. What can be done here?

This one is image with fuzz factor 0

Upvotes: 1

Views: 2313

Answers (2)

Mark Setchell
Mark Setchell

Reputation: 207670

I would go for a simple threshold to pick out the white and then some sort of filtration to remove the noise/ragged edges. So, for example

convert shirt.jpg -threshold 99.99% -negate  result.jpg

which gives this:

enter image description here

Then apply some median filtering to smooth it:

convert shirt.jpg -threshold 99.99% -median 5 -negate  result.jpg

enter image description here

or maybe a bigger filter:

convert shirt.jpg -threshold 99.99% -median 11 -negate  result.jpg

which gives this

enter image description here

Alternatively, you may get on better with an erosion and a dilation...

convert shirt.jpg -threshold 99.99% -negate  \
   -morphology erode  diamond:3              \
   -morphology dilate diamond:3 result.jpg

enter image description here

You may like to use Anthony Thyssen's flicker_compare to flicker between the input and result image to see what you have got, see here.

./flickercompare -o flick.gif shirt.jpg result.jpg

enter image description here

Upvotes: 1

emcconville
emcconville

Reputation: 24439

I would take advantage of HSL colorspace, and create an alpha mask from the lightness channel.

convert tshirt.jpg \( \
        +clone -colorspace HSL -separate \
        -delete 0,1 -fx 'u>0.975?0:1' \) \
        -compose CopyOpacity -composite  \
        out.png

enter image description here

Upvotes: 2

Related Questions