zl程序教程

您现在的位置是:首页 >  后端

当前栏目

等比例缩放图片并填充图片为正方形(python附代码)

Python代码 图片 缩放 填充 比例 正方形
2023-09-11 14:22:51 时间
import os
import cv2
import shutil
def suofang(im,target_height,target_width):
    height, width = im.shape[:2]  # 取彩色图片的长、宽。

    ratio_h = height / target_height
    ration_w = width / target_width

    ratio = max(ratio_h, ration_w)

    # 缩小图像  resize(...,size)--size(width,height)
    size = (int(width / ratio), int(height / ratio))
    shrink = cv2.resize(im, size, interpolation=cv2.INTER_AREA)  # 双线性插值
    BLACK = [0, 0, 0]

    a = (target_width - int(width / ratio)) / 2
    b = (target_height - int(height / ratio)) / 2

    constant = cv2.copyMakeBorder(shrink, int(b), int(b), int(a), int(a), cv2.BORDER_CONSTANT, value=BLACK)
    constant = cv2.resize(constant, (target_width, target_height), interpolation=cv2.INTER_AREA)
    return constant
    
shutil.rmtree('你的输出路径')
os.mkdir('你的输出路径')
input0 = '你的输出路径'
output0 = '你的输入路径'

datalist = os.listdir(input0)
for i in datalist:
    id = i.split('.')[0]
    im_name = input0 + '/' + i
    outpath = output0 + '/'
    img = io.imread(im_name)
    img = cv2.cvtColor(img,cv2.COLOR_RGBA2RGB)#有个别图片是32位ARGB的,不去除透明通道的话填充边缘的会是白色的
    img = suofang(img,300,300)# 自己改大小
    io.imsave(outpath+id+'.png',img)