图像补边不失真的resize
import cv2
import numpy as np
import torch
import torch.nn.functional as F
from PIL import Image
import copy
from nets.deeplabv3_plus import DeepLab
import colorsys
from matplotlib import pyplot as plt
def preprocess_input(image):
image /= 255.0
return image
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
def cvtColor(image):
if len(np.shape(image)) == 3 and np.shape(image)[2] == 3:
return image
else:
image = image.convert('RGB')
return image
def detect_image(image, count=False, name_classes=None):
input_shape = [512, 512]
image = cvtColor(image)
old_img = copy.deepcopy(image)
orininal_h = np.array(image).shape[0]
orininal_w = np.array(image).shape[1]
image_data, nw, nh = resize_image(image, (input_shape[1], input_shape[0]))
pr = np.array(image_data)
pr = pr[int((input_shape[0] - nh) // 2): int((input_shape[0] - nh) // 2 + nh), \
int((input_shape[1] - nw) // 2): int((input_shape[1] - nw) // 2 + nw)]
pr = cv2.resize(pr, (orininal_w, orininal_h), interpolation=cv2.INTER_LINEAR)
return old_img, image_data, pr, nw, nh
if __name__ == '__main__':
img = "F:/rock_project/deeplabv3-plus-pytorch-main/img/street.jpg"
img = Image.open(img)
old_img,image_data,pr, nw, nh = detect_image(img, count=False, name_classes=None)
print("old_img,image_data:",old_img.size, image_data.size)
plt.figure(figsize=(10, 10))
plt.subplot(1, 3, 1)
plt.imshow(old_img)
plt.title("original ground")
plt.subplot(1, 3, 2)
plt.imshow(image_data)
plt.title("RGB img")
plt.subplot(1, 3, 3)
plt.imshow(pr)
plt.title("pr img")
plt.show()
