本篇文章介绍一种简单实用的小工具,将图片等比例缩放。在用 opencv 时有时拿捏不好尺寸,导致缩放的图片比例不均衡,图像看起来怪怪的,本篇文章将帮你解决这个问题。
示例图:
工具包代码:
#导入opencv库
import cv2 #pip install opencv
#传入图片,宽高可任选其一,传入想要调整的大小,inter默认不需要传入
def resize(image, width=None, height=None, inter=cv2.INTER_AREA):
dim = None
#获取传入图片的高宽尺寸
(h, w) = image.shape[:2]
if width is None and height is None:
return image
#当传入参数为高height时
if width is None:
r = height / float(h)
dim = (int(w * r), height)
#当传入参数为宽width时
else:
r = width / float(w)
dim = (width, int(h * r))
#按要求对图片缩放
resized = cv2.resize(image, dim, interpolation=inter)
return resized
参数1:原图;参数2:高宽任选其一,输入想要缩放的尺寸