python - 如何使 ImageOps.fit 不裁剪?
问题描述
如何在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
新的拟合图像
解决方案
这是在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:
→
→
未显示:这些功能适用于大于所需尺寸的图像
推荐阅读
- haskell - `sum [] = 0` 是什么意思?
- java - 如何从房间数据库中返回单个对象?
- javascript - BarChart vAxis 可以向右吗?
- postgresql - R2DBC spring postgres枚举映射
- python - 按条件分离列表
- python - 在python中对数据使用分类器时出错
- java - 如何在选择 Spinner 时更新 Recyclerview oderBy().startAt()
- c++ - C++ - 一个“私人”单身人士?
- xamarin - Xamarin iOS INVoiceShortcutCenter 崩溃
- c++ - 错误 c2373 使用模板类重新定义不同的类型修饰符