python - 如何拍摄图像并获得从中心裁剪的 3x2 比例图像?

标签 python algorithm image-processing python-imaging-library

有没有简单的方法来做到这一点? 在 Python 中,我创建了一个脚本来从图像中获取一个“方框”……基于中心。

但是,这杀死了我的一些脑细胞。对于基于中心的 3x2(3 宽,2 高),有没有一种简单的方法可以做到这一点?

这是我的“方框”脚本,但我不想为 3x2 修改它。

def letterbox(f,thumb_w=None,thumb_h=None):
    try:
        im = Image.open(StringIO(f))
        imagex = int(im.size[0])
        imagey = int(im.size[1])
        thumb_size = (thumb_w,thumb_h) #what if it is too small!?? fix it.
        if imagex > imagey:
            setlen = imagey
            left = (imagex - setlen)/2
            top = 0
            height = setlen
            width = setlen
        if imagey > imagex:
            setlen = imagex
            left = 0
            top = (imagey - setlen)/2
            heigth = setlen
            width = setlen
        if imagex == imagey:
            left = 0
            top = 0
            height = imagey
            width = imagex
        box = (left,top,left+width,top+height)
        im = im.crop(box)
        #im.thumbnail(thumb_size,Image.ANTIALIAS)
        new_file = StringIO()
        im.save(new_file,'JPEG')
        new_file.seek(0)
    except Exception, e:
        pass
    return new_file

是否有在线脚本可以满足我的需求?

最佳答案

使用定义为 imagex/imagey 的宽高比,因此您使用 3/2 表示 3:2,使用 16/9 表示 16:9 等。

def letterbox(f,aspect_ratio=1):
    try:
        im = Image.open(StringIO(f))
        imagex = int(im.size[0])
        imagey = int(im.size[1])
        width = min(imagex, imagey*aspect_ratio)
        height = min(imagex/aspect_ratio, imagey)
        left =(imagex - width)/2
        top = (imagey - height)/2
        box = (left,top,left+width,top+height)
        im = im.crop(box)
        new_file = StringIO()
        im.save(new_file,'JPEG')
        new_file.seek(0)
    except Exception, e:
        pass
    return new_file

您可能想在某个时候检查舍入错误,否则就可以了。

关于python - 如何拍摄图像并获得从中心裁剪的 3x2 比例图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4094744/

相关文章:

javascript - 是否有一种树结构或算法可以在树中的各个级别之间进行洗牌?

python - 有没有办法在 python 中简化这个 "n-way merge"

algorithm - Trie 实现 - 将元素插入到 trie 中

python - 灰度图像分割

matlab - 在Matlab中将二值图像转换为灰度图像

python - 在 python 中使用 cv2.findContours() 时出错

python - 将文件保存为没有表单的 FileField

python - 从 qrc 资源文件创建 pandas 数据框

python - 有没有办法构建一个正则表达式,仅列出某个子字符串一次?

python - Django、mod_wsgi 和虚拟环境