使用Python将图片转正方形的两种方法

一、将原图粘贴到一张正方形的背景上
def trans_square(image):
    r"""Open the image using PIL."""
    image = image.convert('RGB')
    w, h = image.size
    background = Image.new('RGB', size=(max(w, h), max(w, h)), color=(127, 127, 127))  # 创建背景图,颜色值为127
    length = int(abs(w - h) // 2)  # 一侧需要填充的长度
    box = (length, 0) if w < h else (0, length)  # 粘贴的位置
    background.paste(image, box)
    return background
二、切片填充的方式
  1. 使用numpy创建背景,使用切片将原图的值填充到背景中。
    def trans_square(image):
    	r"""Open the image using PIL."""
        img = image.convert('RGB')
        img = np.array(img, dtype=np.uint8)  # 图片转numpy
        img_h, img_w, img_c = img.shape
        if img_h != img_w:
            long_side = max(img_w, img_h)
            short_side = min(img_w, img_h)
            loc = abs(img_w - img_h) // 2
            img = img.transpose((1, 0, 2)) if img_w < img_h else img  # 如果高是长边则换轴,最后再换回来
            background = np.zeros((long_side, long_side, img_c), dtype=np.uint8)  # 创建正方形背景
            background[loc: loc + short_side] = img[...]  # 数据填充在中间位置
            img = background.transpose((1, 0, 2)) if img_w < img_h else background
        return Image.fromarray(img, 'RGB')
def trans_square(img):
    """
    图片转正方形,边缘使用0填充
    :param img: np.ndarray
    :return: np.ndarray
    """
    img_h, img_w, img_c = img.shape
    if img_h != img_w:
        long_side = max(img_w, img_h)
        short_side = min(img_w, img_h)
        loc = abs(img_w - img_h) // 2
        img = img.transpose((1, 0, 2)) if img_w < img_h else img  # 如果高是长边则换轴,最后再换回来
        background = np.zeros((long_side, long_side, img_c), dtype=np.uint8)  # 创建正方形背景
        background[loc: loc + short_side] = img[...]  # 数据填充在中间位置
        img = background.transpose((1, 0, 2)) if img_w < img_h else background
    return img
  1. 使用 nn.ZeroPad2d() 或者 nn.ConstantPad2d() 进行填充
def trans_square(image):
    r"""transform square.
    :return PIL image
    """
    img = transforms.ToTensor()(image)
    C, H, W = img.shape
    pad_1 = int(abs(H - W) // 2)  # 一侧填充长度
    pad_2 = int(abs(H - W) - pad_1)  # 另一侧填充长度
    img = img.unsqueeze(0)  # 加轴
    if H > W:
        img = nn.ZeroPad2d((pad_1, pad_2, 0, 0))(img)  # 左右填充,填充值是0
        # img = nn.ConstantPad2d((pad_1, pad_2, 0, 0), 127)(img)  # 左右填充,填充值是127
    elif H < W:
        img = nn.ZeroPad2d((0, 0, pad_1, pad_2))(img)  # 上下填充,填充值是0
        # img = nn.ConstantPad2d((0, 0, pad_1, pad_2), 127)(img)  # 上下填充,填充值是127
    img = img.squeeze(0)  # 减轴
    img = transforms.ToPILImage()(img)
    return img
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值