imagemagickimagemagick-convertimagemagick-montage

Imagemagick crop into equally sized tiles with overlap?


I want to split a large JPG into equally sized PNGs with a certain overlap:

convert total.jpg -crop 10x10@+10+10 split_%04d.png

This works fine... but unfortunately the output pictures do sometimes differ in size by one if the source image is not exactly divisible by 10 (or whatever number I choose).

Is it possible to split the original picture into tiles of EXACT equal size in a single command or do I have to extend to a size that is divisible by the number of tiles in x/y direction before splitting? (That's what I do now)

Would it also be possible to specify the size AND overlap of the output pictures and make imagemagick automatically extend the last pictures in a row/column to simply extend with a certain color (e.g. black) in order to get equally sized output pictures?


Solution

  • This command starts by calculating the canvas size required to crop the image evenly into, in this example, 7 units wide by 9 units high. Then it increases the canvas dimensions on the right and bottom edges if necessary, and shows a green background in any overflow. Then it crops the image and outputs the results with sequential filenames.

    convert logo: -background green -virtual-pixel background \
       -set option:distort:viewport "%[fx:ceil(w/7)*7]x%[fx:ceil(h/9)*9]" \
       -distort SRT 0 +repage -crop "7x9@" +repage split_%04d.png
    

    The input image here is ImageMagick's built-in "logo:". Use your image's file name instead.

    This is in *nix syntax. For Windows CMD change the continued line backslashes "\" to carets "^". For a Window BAT script double all the percent signs "%%".