补边不失真的resize

RBG 加入灰条

def resize_image(image, size):
    iw, ih  = image.size
    w, h    = size
    scale   = min(w/iw, h/ih)
    nw      = int(iw*scale)
    nh      = int(ih*scale)
    image   = image.resize((nw,nh), Image.BICUBIC)
    new_image = Image.new('RGB', size, (128,128,128)) # 加入的灰条的值
    new_image.paste(image, ((w-nw)//2, (h-nh)//2))
    return new_image, nw, nh

加入黑条(标签)

# 不失真的resize
def letterbox_image(image, label, size):
    # 对图片进行resize,使图片不失真。在空缺的地方进行padding
    iw, ih = image.size
    w, h = size
    scale = min(w/iw, h/ih)
    nw = int(iw*scale)
    nh = int(ih*scale)
    image = image.resize((nw, nh), Image.BICUBIC)
    new_image = Image.new('RGB', [w, h], (128, 128, 128)) # 填充的是灰条[128,128,128]
    new_image.paste(image, ((w - nw) // 2, (h - nh) // 2))

    label = label.resize((nw, nh), Image.NEAREST)
    new_label = Image.new('RGB', [w, h], (0, 0, 0)) # # 填充的是黑色背景[0,0,0]
    new_label.paste(label, ((w - nw) // 2, (h - nh) // 2))
    
    return new_image,new_label

灰度加入边

def letterbox_image(image, label, size):
	iw, ih = image.size
	scale = min(w / iw, h / ih)
	 nw = int(iw * scale)
	 nh = int(ih * scale)
	
	 image = image.resize((nw, nh), Image.BICUBIC)
	 new_image = Image.new('RGB', [w, h], (128, 128, 128)) # RBG图像
	 new_image.paste(image, ((w - nw) // 2, (h - nh) // 2))
	
	 label = label.resize((nw, nh), Image.NEAREST)
	 new_label = Image.new('L', [w, h], (0)) # 灰度
	 new_label.paste(label, ((w - nw) // 2, (h - nh) // 2))
	 return new_image, new_label
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值