Search code examples
imageimagemagickcropimage-manipulation

Remove white background and crop to fit foreground


I'm looking for a script (with Imagemagick or python?) that can crop an image to fit the foreground image (non white pixels that are connected).

Basically, selecting white background, inverting the selection and cropping to the nearest rectangular image.

Example: this image with white background:

image with white background

should become this image:

image cropped to foreground image


Solution

  • This will work on the example image supplied:

    convert "https://i.sstatic.net/TEMXc.jpg" -bordercolor white -border 10x10 -fuzz 20% -trim "output.jpg"
    

    EDIT: Just thought I should add an explanation.

    -trim removes from the outside the pixels that are the same colour down to a different colour.

    -fuzz allows for slight colour variations which may not be obvious; which you can get due to jpg compression.

    You need to add the border first otherwise the -trim will not work, due to the black pixels on the bottom edge of the image.