记录一下小脚本吧,很久没写博客了。。
代码用来对照片进行等比缩放;
  • 原图(下载自百度图库)
    在这里插入图片描述
  • 代码
# 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格式
    在这里插入图片描述
希望博客对您有所帮助!
Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐