如何在不裁剪顶部/底部/侧面的情况下适应ImageOps.fit(source28x32, (128, 128))
?我是否真的必须找到该方面,并相应地调整大小以使放大版本不超过128x128,然后添加边框像素(或将图像居中放置在128x128画布中)?请注意,来源可以是任意比例,28x32只是一个示例。
源图像(28x32)
适合的图片(128x128)
到目前为止,这是我的尝试,并不十分优雅
def fit(im):
size = 128
x, y = im.size
ratio = float(x) / float(y)
if x > y:
x = size
y = size * 1 / ratio
else:
y = size
x = size * ratio
x, y = int(x), int(y)
im = im.resize((x, y))
new_im = Image.new('L', (size, size), 0)
new_im.paste(im, ((size - x) / 2, (size - y) / 2))
return new_im
新的拟合图像
答案 0 :(得分:1)
这是在PIL
和cv2
中实现的功能。输入可以是任何大小;该函数会找到将最大边缘适合所需宽度所需的比例,然后将其放到所需宽度的黑色正方形图像上。
在PIL中
def resize_PIL(im, output_edge):
scale = output_edge / max(im.size)
new = Image.new(im.mode, (output_edge, output_edge), (0, 0, 0))
paste = im.resize((int(im.width * scale), int(im.height * scale)), resample=Image.NEAREST)
new.paste(paste, (0, 0))
return new
在cv2中
def resize_cv2(im, output_edge):
scale = output_edge / max(im.shape[:2])
new = np.zeros((output_edge, output_edge, 3), np.uint8)
paste = cv2.resize(im, None, fx=scale, fy=scale, interpolation=cv2.INTER_NEAREST)
new[:paste.shape[0], :paste.shape[1], :] = paste
return new
所需宽度为128:
→
→
未显示:这些功能适用于大于所需尺寸的图像