彩色图像长短边等比例缩放并填零补成正方形

(适用于彩色图)

图像长短边等比例缩放并填零补成正方形说明:将图像长边缩放至固定尺寸,并将短边等比例缩放,空出部分两边对称填零,补成正方形。

以下是由于opencv读取和保存的通道顺序默认指的不一样,所以分隔通道后再融合。

pil_image = cv2.imread(path_image)
b, g, r = cv2.split(pil_image)  # 通道分离,再重新合并操作
pil_image = cv2.merge([r, g, b])
output_image = img_pad(pil_image)
output_image.save(path_output)

完整代码如下:

import os
import numpy as np
from PIL import Image
import cv2

def img_pad(pil_file):
    w, h,c= pil_file.shape
    fixed_size = 139  # 输出正方形图片的尺寸

    if h >= w:
        factor = h / float(fixed_size)
        new_w = int(w / factor)
        if new_w % 2 != 0:
            new_w -= 1
        pil_file = cv2.resize(pil_file,(new_w, fixed_size))
        pad_w = int((fixed_size - new_w) / 2)
        array_file = np.array(pil_file)
        # array_file = np.pad(array_file, ((0, 0), (pad_w, fixed_size-pad_w)), 'constant')
        array_file = cv2.copyMakeBorder(array_file, 0, 0, pad_w, fixed_size-new_w-pad_w, cv2.BORDER_CONSTANT, value=(0, 0, 0))
    else:
        factor = w / float(fixed_size)
        new_h = int(h / factor)
        if new_h % 2 != 0:
            new_h -= 1
        pil_file = cv2.resize(pil_file,(fixed_size, new_h))
        pad_h = int((fixed_size - new_h) / 2)
        array_file = np.array(pil_file)
        # array_file = np.pad(array_file, ((pad_h, fixed_size-pad_h), (0, 0)), 'constant')
        array_file = cv2.copyMakeBorder(array_file,  pad_h, fixed_size - new_h-pad_h,0, 0, cv2.BORDER_CONSTANT, value=(0, 0, 0))
    output_file = Image.fromarray(array_file)
    return output_file


if __name__ == "__main__":
    dir_image = 'data/positive'  # 图片所在文件夹
    dir_output = 'data/positiveres'  # 输出结果文件夹
    if not os.path.exists(dir_output):
        os.makedirs(dir_output)
    i = 0
    list_image = os.listdir(dir_image)
    for file in list_image:
        path_image = os.path.join(dir_image, file)
        path_output = os.path.join(dir_output, file)
        pil_image = cv2.imread(path_image)
        b, g, r = cv2.split(pil_image)  # 通道分离,再重新合并操作
        pil_image = cv2.merge([r, g, b])
        # pil_image = pil_image.load()
        output_image = img_pad(pil_image)
        output_image.save(path_output)
        i += 1
        if i%1000==0:
            print('The num of processed images:', i)

结果如下:

原图:

放缩后:

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值