这种裁剪算法的更优雅的改写是什么? (Python)
我想在 Django 应用程序中裁剪缩略图,以便获得显示图像中心的二次图像。 这并不难,我同意。
我已经编写了一些代码来完成此任务,但不知怎的,它缺乏某种......优雅。 我不想玩代码高尔夫,但我认为必须有一种方法来表达这种更短、更Pythonic的方式。
x = y = 200 # intended size
image = Image.open(filename)
width = image.size[0]
height = image.size[1]
if (width > height):
crop_box = ( ((width - height)/2), 0, ((width - height)/2)+height, height )
image = image.crop(crop_box)
elif (height > width):
crop_box = ( 0, ((height - width)/2), width, ((height - width)/2)+width )
image = image.crop(crop_box)
image.thumbnail([x, y], Image.ANTIALIAS)
你有什么想法吗?
编辑:解释x,y
I want to crop a thumbnail image in my Django application, so that I get a quadratic image that shows the center of the image. This is not very hard, I agree.
I have already written some code that does exactly this, but somehow it lacks a certain ... elegance. I don't want to play code golf, but there must be a way to express this shorter and more pythonic, I think.
x = y = 200 # intended size
image = Image.open(filename)
width = image.size[0]
height = image.size[1]
if (width > height):
crop_box = ( ((width - height)/2), 0, ((width - height)/2)+height, height )
image = image.crop(crop_box)
elif (height > width):
crop_box = ( 0, ((height - width)/2), width, ((height - width)/2)+width )
image = image.crop(crop_box)
image.thumbnail([x, y], Image.ANTIALIAS)
Do you have any ideas, SO?
edit: explained x, y
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为这应该可以。
I think this should do.
PIL 中的
fit()
函数 ImageOps 模块执行您想要的操作:The
fit()
function in the PIL ImageOps module does what you want:我想要对 jepg 图像进行内容分析。 我希望采用 251 x 261 的 jpeg imafe,并通过算法将其裁剪为 96 x 87。这个程序可以像编写智能裁剪算法一样做到这一点,并提示重新调整图像。
I want to a content analysis of a jepg image. I wish to take a jpeg imafe say 251 x 261 and pass it through an algorithm to crop it to say 96 x 87. Can this program do that like t write an intelligent cropping algorithm, with a prompt to rezie the image.