python---以不变形的方式调整图片大小

转自
http://www.cnblogs.com/neo-T/p/6477378.html

import os, sys
import cv2

#按照指定图像大小调整尺寸
def resize_image(image, height, width):
     top, bottom, left, right = (0, 0, 0, 0)

     #获取图像尺寸
     h, w, _ = image.shape

     #对于长宽不相等的图片,找到最长的一边
     longest_edge = max(h, w)    

     #计算短边需要增加多上像素宽度使其与长边等长
     if h < longest_edge:
         dh = longest_edge - h
         top = dh // 2
         bottom = dh - top
     elif w < longest_edge:
         dw = longest_edge - w
         left = dw // 2
         right = dw - left
     else:
         pass 

     #RGB颜色
     BLACK = [0, 0, 0]

     #给图像增加边界,是图片长、宽等长,cv2.BORDER_CONSTANT指定边界颜色由value指定
     constant = cv2.copyMakeBorder(image, top , bottom, left, right, cv2.BORDER_CONSTANT, value = BLACK)

     #调整图像大小并返回
     return cv2.resize(constant, (height, width))

def resizeImg(path_name, newpath):    
     for dir_item in os.listdir(path_name):
         #从初始路径开始叠加,合并成可识别的操作路径
         full_path = os.path.abspath(os.path.join(path_name, dir_item))

         if os.path.isdir(full_path):    #如果是文件夹,继续递归调用
             read_path(full_path)
         else:   #文件
             if dir_item.endswith('.jpg'):
                 image = cv2.imread(full_path)                
                 image = resize_image(image, 64, 64)
                 cv2.imwrite(newpath + '/' + dir_item, image)

def main():
    # 调整图片大小
    f = 'E:/bd/train/val2/23'
    fnew = 'E:/bd/train/val3/23'
    resizeImg(f, fnew)

if __name__ == "__main__":
    main()
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值