将图片补成正方形之后再放缩

原图
在这里插入图片描述
原图直接缩放,比例失调
在这里插入图片描述
将原图补成正方经,然后缩放

在这里插入图片描述

在这里插入图片描述

import numpy as np
from PIL import Image

path = "D:\\1.jpeg"

# 图片本身
img = Image.open(path)
img.show()

img = np.array(img)

# 直接缩放图片
old_img = Image.fromarray(img.astype('uint8')).convert('RGB').resize((200, 200))
old_img.show()

# 将图片用黑色填充为正方形
shape = img.shape
size = max(img.shape[0], img.shape[1])
new_img = np.zeros((size, size, 3))
height = img.shape[0]
weight = img.shape[1]
print(img.shape)
print(new_img.shape)
if height > weight:
    # 高
    print(int((height - weight) / 2), int((height - weight) / 2 + weight))
    # new_img[int((height - weight) / 2):int((height - weight) / 2) + weight][:][:] = np.swapaxes(img,0,1)
    new_img[:, int((height - weight) / 2):int((height - weight) / 2) + weight, :] = img
else:
    new_img[:,int((weight - height) / 2):int((weight - height) / 2) + height,:] = img

# 展示填充黑色的正方形图片
img = Image.fromarray(new_img.astype('uint8')).convert('RGB')
img.show()


# 对黑色正方形图片进行放缩
img = Image.fromarray(new_img.astype('uint8')).convert('RGB').resize((200, 200))
img.show()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值