• 技术文章 >Python技术 >Python基础教程

    python如何实现图像等比缩放

    小妮浅浅小妮浅浅2021-09-24 09:44:29原创7993

    说明

    1、初始化目标尺寸的幕布,所有值都是一样的。

    2、计算出放缩比例。

    把原图中较长的边放缩到目标尺寸大小.

    3、使短边也能按此比例放缩,得到的图片就不会变形。

    4、缩放后的图像必须小于等于目标尺寸。

    因此必须能够粘贴在幕布的中心,这样幕布中没有被覆盖的地方就会自动变成留白,省去了填充步骤。

    5、得到想要的图片。

    实例

    import numpy as np
    from PIL import Image
     
     
     
    def resize(img, size):
        # 先创建一个目标大小的幕布,然后将放缩好的图片贴到中央,这样就省去了两边填充留白的麻烦。
        canvas = Image.new("RGB", size=size, color="#7777")  
        
        target_width, target_height = size
        width, height = img.size
        offset_x = 0
        offset_y = 0
        if height > width:              # 高 是 长边
            height_ = target_height     # 直接将高调整为目标尺寸
            scale = height_ / height    # 计算高具体调整了多少,得出一个放缩比例
            width_ = int(width * scale) # 宽以相同的比例放缩
            offset_x = (target_width - width_) // 2     # 计算x方向单侧留白的距离
        else:   # 同上
            width_ = target_width
            scale = width_ / width
            height_ = int(height * scale)
            offset_y = (target_height - height_) // 2
     
        img = img.resize((width_, height_), Image.BILINEAR) # 将高和宽放缩
        canvas.paste(img, box=(offset_x, offset_y))         # 将放缩后的图片粘贴到幕布上
        # box参数用来确定要粘贴的图片左上角的位置。offset_x是x轴单侧留白,offset_y是y轴单侧留白,这样就能保证能将图片填充在幕布的中央
        
        return canvas
     
     
    img= Image.open('1.jpg')
     
    target__size=(500,300)  # 目标尺寸:宽为500,高为300
    res = resize(img,target__size)
     
    res.save('new.jpg')

    以上就是python实现图像等比缩放的方法,希望对大家有所帮助。更多Python学习指路:python基础教程

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python图像缩放
    品易云
    上一篇:python判断字符串函数的归纳 下一篇:python setup和teardown的使用

    相关文章推荐

    • python索引的顺序和倒序• python循环遍历如何理解• python for语句的应用场景• python如何模拟用户自动打卡• python逻辑取反的实现• python Pytest有什么特点• python如何打印矩阵• Python Modules是什么意思• python三种导入模块的方式• python查找计算函数的整理• python填充压缩的函数总结• python分割拼接函数的介绍• python判断字符串函数的归纳

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网