Python图像处理库PIL——resize()函数

        在神经网络的训练与测试中,不同的网络需要的图像大小不一样。

        所以,在将图像送入网络之前,我们需要将图像缩放到符合网络维度的大小。

        本文基于这个需求,使用python中的图像处理库PIL来实现图像的缩放。

resize()函数讲解

1.单张图片的缩放

        函数img.resize((width, height),Image.ANTIALIAS)
        第二个参数:

  •                 Image.NEAREST :低质量
  •                 Image.BILINEAR:双线性
  •                 Image.BICUBIC :三次样条插值
  •                 Image.ANTIALIAS:高质量
  • #function: 更改图片尺寸大小
     
    from PIL import Image
    '''
    filein: 输入图片
    fileout: 输出图片
    width: 输出图片宽度
    height:输出图片高度
    type:输出图片类型(png, gif, jpeg...)
    '''
    def ResizeImage(filein, fileout, width, height, type):
      img = Image.open(filein)
      out = img.resize((width, height),Image.ANTIALIAS) #resize image with high-quality
      out.save(fileout, type)
    if __name__ == "__main__":
      filein = r'0.jpg'
      fileout = r'testout.png'
      width = 6000
      height = 6000
      type = 'png'
      ResizeImage(filein, fileout, width, height, type)

    2.多张图片的缩放

            涉及到的一个重要函数glob.glob()

            例如:返回当前工程文件夹下所有的jpg路径可以编写如下代码

    glob.glob('./*.jpg')

            配合该函数,完整代码如下:

    from PIL import Image
    import os.path
    import glob
    def convertjpg(jpgfile,outdir,width=1280,height=720):
        img=Image.open(jpgfile)   
        new_img=img.resize((width,height),Image.BILINEAR)   
        new_img.save(os.path.join(outdir,os.path.basename(jpgfile)))
    for jpgfile in glob.glob("./source/*.jpg"):    # 来源文件夹
        convertjpg(jpgfile,"./target/")            # 目标文件夹

    来源:爱吹牛的小哥哥

    物联沃分享整理
    物联沃-IOTWORD物联网 » Python图像处理库PIL——resize()函数

    发表评论