使用PIL在中央裁剪图像 [英] Crop an image in the centre using PIL
本文介绍了使用PIL在中央裁剪图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在中央裁剪图像?因为我知道该框是一个四元组,定义了左,上,右和下像素坐标,但我不知道如何获取这些坐标,因此它会在中心裁剪.
How can I crop an image in the center? Because I know that the box is a 4-tuple defining the left, upper, right, and lower pixel coordinate but I don't know how to get these coordinates so it crops in the center.
推荐答案
假设您知道要裁剪的尺寸(new_width X new_height):
Assuming you know the size you would like to crop to (new_width X new_height):
import Image
im = Image.open(<your image>)
width, height = im.size # Get dimensions
left = (width - new_width)/2
top = (height - new_height)/2
right = (width + new_width)/2
bottom = (height + new_height)/2
# Crop the center of the image
im = im.crop((left, top, right, bottom))
如果您尝试裁切较大的小图像,这将会中断,但我将假定您不会尝试这样做(否则,您可能会遇到这种情况而不裁切图像).
This will break if you attempt to crop a small image larger, but I'm going to assume you won't be trying that (Or that you can catch that case and not crop the image).
这篇关于使用PIL在中央裁剪图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文