Page 1 of 1

Autocropping left/right margins only

Posted: 2014-12-01T05:38:59-07:00
by ozbigben
Hi All

Did a couple of quick searches and didn't find much so I figured I'd post this, if only for my own reference later. I had a need for centering the text block of pages horizontally only and then padding out the image to a fixed size. The last bit is handled with a basic -extent command with the dimensions being determined by a database containing the image metadata, so all I need to figure out was how to crop the white margins on the left and right side of the text block. The images are a mixture of greyscale and bitonal images, black text on white background. After doing a bit of hunting around I finished up using a variation on another script I hacked together to crop the black borders of photographs. viewtopic.php?f=22&t=20613&p=82555#p82555

Drag and drop DOS batch file:

Code: Select all

setlocal
FOR /F "tokens=*" %%i in ('convert %1 -virtual-pixel edge -auto-level -fill black -gravity center -draw "point 0,0" -threshold 90%% -negate -morphology dilate octagon:10 -bordercolor black -border 1x1 -trim -format "%%wx%%H+%%X+0" info:') do SET IMTEST=%%i

convert %1  -bordercolor white -border 1x1 -crop %IMTEST% +repage %~n1_trim.tif

endlocal
The initial threshold setting is geared to making sure that fainter portions of the greyscale images are retained
The main adaptations are in the -format variables used to specify the crop parameters
The morphology operations are redundant but I left one in to provide a small margin around the text block

Re: Autocropping left/right margins only

Posted: 2014-12-01T07:51:18-07:00
by snibgo
[Mod note: thanks for your contribution. As it is about specific usage of IM, rather than generic image processing, I'm moving it to the Users forum.]

Re: Autocropping left/right margins only

Posted: 2014-12-01T14:15:37-07:00
by ozbigben
OK, thanks

Re: Autocropping left/right margins only

Posted: 2014-12-04T22:22:24-07:00
by ozbigben
Added a couple of minor edits. In our project we are leaving in blank pages to preserve the pagination for printing. To avoid problems with calculating the crop region of an empty page I added a single black pixel to the centre of the image.

While it didn't seem to cause any problems, I also ended up with an error "Maximum setlocal recursion level reached". To get rid of this I added "endlocal" at the end.