使用 ImageMagick 裁剪具有焦点区域(脸部)的图像
我正在努力寻找带有焦点区域的调整大小、裁剪和图像的正确方法。就我而言,焦点区域是图像中检测到的脸部,我需要确保该区域在裁剪版本中可见。
我有例如给出的焦点区域。面部高度、面部宽度、面部中心x和面部中心y。这些值是原始图像尺寸的百分比。
我想做的是得到一个例如。 60x60 缩略图。正常的方法是调整大小,使图像的高度或宽度等于 60 像素,然后从中心裁剪 60x60,如下所示:
mogrify -resize 60x -gravity 'Center' -crop 60x60 image.jpg
可以采取什么方法将裁剪集中在给定区域周围?
我正在考虑一个包含多个路径的解决方案:
- 如果面部区域大于所需的缩略图,则调整图像大小足以使整个面部在 60x60 像素中可见,然后裁剪
- 如果面部区域小于所需的缩略图,然后裁剪“扩展”我的脸部区域,直到我想要的拇指可以放入该区域。然后裁剪。我想我需要确保这不会超出原始图像的范围。
有更聪明的方法吗?你能尝试制作一些示例代码吗?
谢谢!
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:
- If the face area is bigger than the wanted thumbnail, resize the image just enough to make the whole face visible in 60x60 pixels, then crop
- If the face area is smaller than the wanted thumbnail, then crop "expand" my face area until my wanted thumb can fit inside the area. Then crop. I guess I need to make sure that this doesn't exceed the bounds of the original image.
Is there a smarter approach? Can you try make some example code?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我首先在脚本或程序中进行算术运算,然后将精确的坐标输入 ImageMagick。
算术步骤:
face_height
、face_width
、face_center_x
和face_center_y
到像素值。您需要矩形缩略图,因此选择最长的边并进行操作:
longest_side = max(face_height,face_width)
现在您可以计算作物的左上角点:
crop_x = 面中心_x - 最长边 / 2
Crop_y = Face_center_y - Longest_side / 2
如果四个裁剪角中的任何一个超出图片尺寸,请进行调整:
crop_x
和crop_y
均应 >= 0crop_x + permanent_side
应小于图像宽度crop_y + 最长边
应小于图像高度计算完这些后,ImageMagick调用变得非常简单:
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
andface_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
andcrop_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: