Search code examples
imagemagickcrop

how to autocrop a deskewed scanned image


Following this approach, deskewing works great, how do I autocrop so it the outer border comes in until it finds a mostly white contiguous rectangle, so it could be auto-cropped after deskewing?


Solution

  • If you are using Imagemagick 7, you can do an extreme trim using the new -define trim:percent-background=0% to remove all the background from the image. See https://imagemagick.org/script/command-line-options.php#trim

    Input:

    enter image description here

    magick skewed_1500.jpeg -background black -deskew 60% -background black -define trim:percent-background=0% -fuzz 1% -trim +repage x.jpg
    

    Result:

    enter image description here

    ADDITION:

    You can trim even more by trimming before the deskew. I had to use a large fuzz value to remove the bottom white. There must be some slight gray spot somewhere down there that I cannot see. But if there is no black border to start, you may trim too much white all around. That is the downside.

    magick skewed_1500.jpeg -bordercolor white -border 1 -fuzz 75% -trim +repage -background black -deskew 60% -background black -define trim:percent-background=0% -fuzz 1% -trim +repage x.jpg
    

    Result:

    enter image description here