gpt4 book ai didi

image - 这种裁剪算法更优雅的改写是什么? (在 Python 中)

转载 作者:太空狗 更新时间:2023-10-30 01:44:06 25 4
gpt4 key购买 nike

我想在我的 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)

SO,你有什么想法吗?

edit: 解释 x, y

最佳答案

我认为应该这样做。

size = min(image.Size)

originX = image.Size[0] / 2 - size / 2
originY = image.Size[1] / 2 - size / 2

cropBox = (originX, originY, originX + size, originY + size)

关于image - 这种裁剪算法更优雅的改写是什么? (在 Python 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/709388/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com