python培训之如何实现图像等比缩放

发布时间:2022-12-22 09:42:02 人气:77 作者:多测师

  python如何实现图像等比缩放

  说明

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

  2、计算出放缩比例。

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

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

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

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

  5、得到想要的图片。

  实例

  import numpy as np

  from PIL import Image

  def resize(img, size):

python培训之如何实现图像等比缩放

  # 先创建一个目标大小的幕布,然后将放缩好的图片贴到中央,这样就省去了两边填充留白的麻烦。

  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学习指路:请关注多测师。https://www.e70w.com/xwzx/




返回列表
在线客服
联系方式

热线电话

17727591462

上班时间

周一到周五

二维码
线