一、将原图粘贴到一张正方形的背景上
def trans_square(image):
r"""Open the image using PIL."""
image = image.convert('RGB')
w, h = image.size
background = Image.new('RGB', size=(max(w, h), max(w, h)), color=(127, 127, 127))
length = int(abs(w - h) // 2)
box = (length, 0) if w < h else (0, length)
background.paste(image, box)
return background
二、切片填充的方式
- 使用numpy创建背景,使用切片将原图的值填充到背景中。
def trans_square(image):
r"""Open the image using PIL."""
img = image.convert('RGB')
img = np.array(img, dtype=np.uint8)
img_h, img_w, img_c = img.shape
if img_h != img_w:
long_side = max(img_w, img_h)
short_side = min(img_w, img_h)
loc = abs(img_w - img_h) // 2
img = img.transpose((1, 0, 2)) if img_w < img_h else img
background = np.zeros((long_side, long_side, img_c), dtype=np.uint8)
background[loc: loc + short_side] = img[...]
img = background.transpose((1, 0, 2)) if img_w < img_h else background
return Image.fromarray(img, 'RGB')
def trans_square(img):
"""
图片转正方形,边缘使用0填充
:param img: np.ndarray
:return: np.ndarray
"""
img_h, img_w, img_c = img.shape
if img_h != img_w:
long_side = max(img_w, img_h)
short_side = min(img_w, img_h)
loc = abs(img_w - img_h) // 2
img = img.transpose((1, 0, 2)) if img_w < img_h else img
background = np.zeros((long_side, long_side, img_c), dtype=np.uint8)
background[loc: loc + short_side] = img[...]
img = background.transpose((1, 0, 2)) if img_w < img_h else background
return img
- 使用 nn.ZeroPad2d() 或者 nn.ConstantPad2d() 进行填充
def trans_square(image):
r"""transform square.
:return PIL image
"""
img = transforms.ToTensor()(image)
C, H, W = img.shape
pad_1 = int(abs(H - W) // 2)
pad_2 = int(abs(H - W) - pad_1)
img = img.unsqueeze(0)
if H > W:
img = nn.ZeroPad2d((pad_1, pad_2, 0, 0))(img)
elif H < W:
img = nn.ZeroPad2d((0, 0, pad_1, pad_2))(img)
img = img.squeeze(0)
img = transforms.ToPILImage()(img)
return img