记录一下小脚本吧,很久没写博客了。。
代码用来对照片进行等比缩放;
- 原图(下载自百度图库)
- 代码
"""
1. 图片的等比缩放;(m,n) <- (scale_size, scale_size)
2. 缩放后的图片放置在中间区域,其它区域像素填0;
"""
import cv2
from PIL import Image
import numpy as np
class UniformScale:
def __init__(self, img_file, scale_size):
"""
:param img_file: 图片文件
:param scale_size: 对照片进行缩放的尺寸 (scale_size, scale_size)
"""
self.img_file = img_file
self.scale_size = scale_size
def pil_scale(self):
img = Image.open(self.img_file).convert('RGB')
h = img.height
w = img.width
ratio = min(self.scale_size / h, self.scale_size / w)
new = img.resize((int(w * ratio), int(h * ratio)))
new = np.asarray(new, np.uint8)
img_pad = np.zeros((self.scale_size, self.scale_size, 3))
dw = int((self.scale_size - int(w * ratio)) / 2)
dh = int((self.scale_size - int(h * ratio)) / 2)
img_pad[dh: int(h * ratio) + dh, dw: int(w * ratio) + dw, :] = new
img_pad = Image.fromarray(np.uint8(img_pad))
img_pad.save('test_PIL.jpg')
return img_pad
def cv2_scale(self):
img = cv2.imread(self.img_file)
h, w = img.shape[:2]
ratio = min(self.scale_size / h, self.scale_size / w)
new = cv2.resize(img, (int(w * ratio), int(h * ratio)), interpolation=cv2.INTER_CUBIC)
img_pad = np.full((self.scale_size, self.scale_size, 3), 0, np.uint8)
dw = int((self.scale_size - int(w * ratio)) / 2)
dh = int((self.scale_size - int(h * ratio)) / 2)
img_pad[dh: int(h * ratio) + dh, dw: int(w * ratio) + dw, :] = new
cv2.imwrite('test_cv2.jpg', img_pad)
return img_pad
if __name__ == '__main__':
UniformScale(img_file='ok.jpeg', scale_size=256).pil_scale()
- 效果图一: pil格式
- 效果图二:cv2格式
希望博客对您有所帮助!