原图
原图直接缩放,比例失调
将原图补成正方经,然后缩放
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()