import numpy as np from PIL import Image from matplotlib import pyplot as plt def img_pad(pil_file, fixed_size=300): w, h = pil_file.size if h >= w: factor = h / float(fixed_size) new_w = int(w / factor) if new_w % 2 != 0: new_w -= 1 pil_file = pil_file.resize((new_w, fixed_size)) pad_w = int((fixed_size - new_w) / 2) array_file = np.array(pil_file) array_file = np.pad(array_file, ((0, 0), (pad_w, pad_w), (0, 0)), 'constant') else: factor = w / float(fixed_size) new_h = int(h / factor) if new_h % 2 != 0: new_h -= 1 pil_file = pil_file.resize((fixed_size, new_h)) pad_h = int((fixed_size - new_h) / 2) array_file = np.array(pil_file) array_file = np.pad(array_file, ((pad_h, pad_h), (0, 0), (0, 0)), 'constant') output_file = Image.fromarray(array_file) return output_file if __name__ == '__main__': img_path = r'.\1402.jpeg' img0 = Image.open(img_path) img1 = img_pad(img0) axs = plt.figure().subplots(1, 2) axs[0].imshow(img0) axs[0].set_title('src') axs[0].axis('off') axs[1].imshow(img1) axs[1].set_title('pad') axs[1].axis('off') plt.show()
效果:

浙公网安备 33010602011771号