【问题标题】:What's a more elegant rephrasing of this cropping algorithm? (in Python)这种裁剪算法的更优雅的改写是什么? (在 Python 中)
【发布时间】:2010-10-17 02:24:47
【问题描述】:

我想在我的 Django 应用程序中裁剪缩略图图像,以便获得显示图像中心的二次图像。这不是很难,我同意。

我已经编写了一些代码来实现这一点,但不知何故它缺乏某种……优雅。我不想玩代码高尔夫,但我认为必须有一种方法来表达这种更短、更 Python 的方式。

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

【问题讨论】:

    标签: image python-imaging-library python crop


    【解决方案1】:

    我认为应该这样做。

    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.Size 的文档
    • 可能有image.Width和image.Height属性,但不知道。我只是从问题中推断出代码。
    【解决方案2】:

    PIL ImageOps 模块中的 fit() 函数可以满足您的需求:

    ImageOps.fit(image, (min(*image.size),) * 2, Image.ANTIALIAS, 0, (.5, .5))
    

    【讨论】:

    • 嗯.. 这似乎并没有真正产生方形图像。还是我错过了什么?
    • fit() 函数返回一个新的图像对象,我忘了说。也许是这样?
    【解决方案3】:
    width, height = image.size
    if width > height:
        crop_box = # something 1
    else:
        crop_box = # something 2
    image = image.crop(crop_box)
    image.thumbnail([x, x], Image.ANTIALIAS)   # explicitly show "square" thumbnail
    

    【讨论】:

      【解决方案4】:

      我想对 jepg 图像进行内容分析。我希望将 jpeg imafe 说成 251 x 261 并通过算法将其裁剪为 96 x 87。这个程序可以像编写智能裁剪算法一样做到这一点,并提示重新调整图像。

      【讨论】:

        猜你喜欢
        • 2018-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多