Python图片自动缩放到指定大小(不拉伸不改变精度)

有时候需要把各种大小不一的图片,缩放到指定大小,但要保持不拉伸不改变精度。如果在PS里搞就是先新建个底层比如512x512,再将需要改变的图片等比缩放到该图层里。

但可以借助python的opencv

要保证路径是全英文的,这很重要,文件可以不用中文,可以做一些自动名字重命名再改回原来名字的操作。

import os
import cv2
import sys

#定义图像缩放函数
def process_image(img, min_side):
    size = img.shape
    h, w = size[0], size[1]
    #长边缩放为min_side
    scale = max(w, h) / float(min_side)
    new_w, new_h = int(w/scale), int(h/scale)
    resize_img = cv2.resize(img, (new_w, new_h))
    # 填充至min_side * min_side
    if new_w % 2 != 0 and new_h % 2 == 0:
        top, bottom, left, right = (min_side-new_h)/2, (min_side-new_h)/2, (min_side-new_w)/2 + 1, (min_side-new_w)/2
    elif new_h % 2 != 0 and new_w % 2 == 0:
        top, bottom, left, right = (min_side-new_h)/2 + 1, (min_side-new_h)/2, (min_side-new_w)/2, (min_side-new_w)/2
    elif new_h % 2 == 0 and new_w % 2 == 0:
        top, bottom, left, right = (min_side-new_h)/2, (min_side-new_h)/2, (min_side-new_w)/2, (min_side-new_w)/2
    else:
        top, bottom, left, right = (min_side-new_h)/2 + 1, (min_side-new_h)/2, (min_side-new_w)/2 + 1, (min_side-new_w)/2

    pad_img = cv2.copyMakeBorder(resize_img, int(top), int(bottom), int(left), int(right), cv2.BORDER_CONSTANT, value=[255,255,255]) #从图像边界向上,下,左,右扩的像素数目
    return pad_img


#你的图片文件夹路径
path = "D:/2018/aa/E/"


num = 0
yname = []
# 批量重命名 保证没有中文名字 后面会改回来
for filename in os.listdir(path):
    im = cv2.imread(filename)
    name = filename.split('.')
    yname.append(name[0])
    os.rename(os.path.join(path, filename), os.path.join(path, str(num) + '.JPG'))
    num+=1
# 批量转换
for filename in os.listdir(path):
    im = cv2.imread(path + filename)
    #输入图片和尺寸
    img_new = process_image(im, 128)
    cv2.imwrite(path + filename, img_new)
    num = filename.split('.')
    num = num[0]
    name = yname[eval(num)]
    os.rename(os.path.join(path, filename), os.path.join(path, name + '.JPG'))


评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值