python使用Pillow/Opencv对图片进行等比缩放

记录一下小脚本吧,很久没写博客了。。
代码用来对照片进行等比缩放;
  • 原图(下载自百度图库)
    在这里插入图片描述
  • 代码
# coding: utf-8
# author: hxy
# 2021-8-5
"""
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格式
    在这里插入图片描述
希望博客对您有所帮助!
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值