I'm struggling to find the right approach to resize and crop and image, with a focus area. In my case the focus area is a face detected in the image, and I need to make sure that this area is visible in the cropped version.
I have focus area given by eg. face_height, face_width, face_center_x and face_center_y. These values are percentages of dimensions of the original image.
What I want to do, is getting a eg. 60x60 thumbnail. The normal approach would be to resize so either height or width of the image is equal 60px and then crop a 60x60 from center, like this:
mogrify -resize 60x -gravity 'Center' -crop 60x60 image.jpg
What approach can be taken focus my crop around a given area instead?
I'm thinking of a solution that includes several paths:
Is there a smarter approach? Can you try make some example code?
Thanks!
I'd first do the arithmetic in script or program, then feed exact coordinates to ImageMagick.
The arithmetic steps:
face_height
, face_width
, face_center_x
and face_center_y
to pixel values.You'll want rectangular thumbnail, so pick the longest side and operate with that:
longest_side = max(face_height, face_width)
Now you can calculate top left point for your crop:
crop_x = face_center_x - longest_side / 2
crop_y = face_center_y - longest_side / 2
If any of the four crop corners fall outside your picture dimensions, adjust for that:
crop_x
and crop_y
should both be >= 0crop_x + longest_side
should be less than image widthcrop_y + longest_side
should be less than image heightHaving calculated these, ImageMagick call gets quite straightforward:
mogrify -crop {longest_side}x{longest_side}+{crop_x}+{crop_y} -resize 60x60 image.jpg
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With