Search code examples
imageimagemagickcropbatch-processing

Imagemagick position and size of a sub-image


Problem description:

In imagemagick, it is very easy to diff two images using compare, which produces an image with the same size as the two images being diff'd, with the diff data. I would like to use the diff data and crop that part from the original image, while maintaining the image size by filling the rest of the space with alpha.

The approach I am taking:

I am now trying to figure the bounding box of the diff, without luck. For example, below is the script I am using to produce the diff image, see below. Now, I need to find the bounding box of the red color part of the image. The bounding box is demonstrated below, too. Note that the numbers in the image are arbitrary and not the actual values I am seeking.

compare -density 300 -metric AE -fuzz 10% ${image} ${otherImage} -compose src ${OUTPUT_DIR}/diff${i}-${j}.png

enter image description here enter image description here


Solution

  • You asked quite a while ago - I found the question just today. Since I think the answer might still be of interest, I propose the following.

    The trim option of convert removes any edges that are the same color as the corner pixels. The page or virtual canvas information of the image is preserved. Therefore, if you run

    convert -trim edPdf.png - | identify -
    

    it gives you:

    PNG 157x146 512x406+144+32 8-bit PseudoClass 2c 1.08KB 0.000u 0:00.000
    

    and the values you are looking for are (144,228), where the latter is 406-146-32 because you looked for the lower left corner whereas (+144+32) gives the upper left corner.