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

[![enter image description here](https://i.stack.imgur.com/rTVSl.jpg)](https://i.stack.imgur.com/rTVSl.jpg)

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

* create a mask image (replace background pixels with white with fuzz and threshold)
* apply the mask over the original image to generate the output

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](https://i.stack.imgur.com/db15E.png)](https://i.stack.imgur.com/db15E.png)

Answer: 
I would take advantage of [HSL](https://en.wikipedia.org/wiki/HSL_and_HSV) 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](https://i.stack.imgur.com/tINcy.png)](https://i.stack.imgur.com/tINcy.png)
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](https://i.stack.imgur.com/pKjoT.jpg)](https://i.stack.imgur.com/pKjoT.jpg)

Then apply some median filtering to smooth it:

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

```

[![enter image description here](https://i.stack.imgur.com/024SA.jpg)](https://i.stack.imgur.com/024SA.jpg)

or maybe a bigger filter:

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

```

which gives this

[![enter image description here](https://i.stack.imgur.com/NXYcX.jpg)](https://i.stack.imgur.com/NXYcX.jpg)

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](https://i.stack.imgur.com/RSrLW.jpg)](https://i.stack.imgur.com/RSrLW.jpg)

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](http://www.imagemagick.org/Usage/scripts/flicker_cmp).

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

```

[![enter image description here](https://i.stack.imgur.com/DaloI.gif)](https://i.stack.imgur.com/DaloI.gif)