from PIL import Image
import os
import matplotlib.pyplot as plt
def resize(image_,image_size_):
"""args:
image_: PIL image\n
image_size_: input_shape[:-1]
"""
old_size = image_.size
ratio = image_size_[0]/max(old_size)
new_size = tuple([int(x*ratio) for x in old_size])
# image
image_ = image_.resize(new_size,Image.Resampling.NEAREST)
new_image = Image.new("RGB",(image_size_[0],image_size_[1]))
new_image.paste(image_,((image_size_[0]-new_size[0])//2,
(image_size_[1]-new_size[1])//2))
return new_image
def resize_back(image_,image_size_):
"""args:\n
image_ : 预测得到的图片结果\n
image_size_: 预测图片的原始大小\n
return: 原始大小的预测结果图片\n
"""
old_size = image_.size
ratio = old_size[0]/max(image_size_)
new_size = tuple([int(x*ratio) for x in image_size_])
up_left_x = (old_size[0]-new_size[0])//2
up_left_y = (old_size[1]-new_size[1])//2
bottom_right_x = up_left_x + new_size[0]
bottom_right_y = up_left_y + new_size[1]
back_image = image_.crop((up_left_x,up_left_y,bottom_right_x,bottom_right_y))
back_image.resize(image_size_)
return back_image
if __name__ == '__main__':
test_filename = "Abyssinian_19"
image_dir = "/home/data/hablee_data_dir/seg_2d/val/JPEGImages/"
image_path = os.path.join(image_dir,test_filename+".jpg")
image = Image.open(image_path)
org_size = image.size
plt.subplot(1,3,1)
plt.title("orginal image")
plt.imshow(image)
desird_size = (512,512)
new_image = resize(image,desird_size)
plt.subplot(1,3,2)
plt.title("resized image")
plt.imshow(new_image)
back_image = resize_back(new_image,org_size)
plt.subplot(1,3,3)
plt.title("resize_back image")
plt.imshow(back_image)
plt.savefig("demonstrate.jpg")
利用PIL进行比例不失真的resize以及resize回去
最新推荐文章于 2024-07-25 22:02:25 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)