PIL简单使用

PIL简单使用

在Python中进行图像处理有PIL、OpenCV等工具。

PIL简介

PIL是Python Imaging Library的简称,目前已经是Python生态系统中图像处理的标准库。

PIL只支持Python 2.x版本,目前支持Python 3.x的是社区在PIL的基础上Fork的版本,项目叫Pillow。

接口
图像读写
  1. 从文件中读取图像数据

    Image.open():提供了打开图像文件和读取图像数据的功能。

    from PIL import Image 
    with open("./img/hand1.png", "rb") as fp: 
        im = Image.open(fp) 
    
  2. 从压缩文件中读取图像数据

    TarIO():提供了tar文件的读取功能,不用解压缩就可以直接从tar文件中读取图像数据。

    from PIL import Image, TarIO 
    fp = TarIO.TarIO("enjoy.tar", "enjoy.jpg") 
    im = Image.open(fp) 
    
  3. 将图像数据保存为JPEG格式

    Image.save():提供了图像数据的保存功能,可以保存成所需要的图像格式。

    import os, sys 
    from PIL import Image 
    
    for infile in sys.argv[1:]: 
    	f, e = os.path.splitext(infile) 
    	outfile = f + ".jpg" 
    	if infile ! = outfile: 
    	try: 
    		Image.open(infile).save(outfile) 
    	except IOError: 
    		print("cannot convert", infile) 
    
  4. 生成图像缩略图

    有时会遇到图像数据过大导致出现内存或者显存溢出的问题。

    im.thumbnai : 提供了将图像制作成缩略图的功能,在不改变主要图像特征的情况下对图像进行缩略变换,以减小图像数据。

    import os, sys 
    from PIL import Image 
    #初始化缩略图的尺寸 
    size = (128, 128) 
    #逐个读取图像并生成缩略图保存 
    for infile in sys.argv[1:]: 
        #初始化缩略图的保存路径 
        outfile = os.path.splitext(infile)[0] + ".jpg" 
        if infile != outfile: 
            try: 
                #读取图像并进行缩略转换,最好保存缩略图 
                im = Image.open(infile) 
                im.thumbnail(size) 
                im.save(outfile, "JPEG") 
            except IOError: 
                print("cannot create thumbnail for", infile) 
    
  5. 图像格式查询

    有时需要查看或者判别图像的格式,以防止出现因图像格式不一致引起的错误。

    im.format、im.size和im.mode分别提供了图像的格式、尺寸、色彩模式(RGB、L)信息的查询功能。

    import sys
    from PIL import Image 
    for infile in sys.argv[1:]: 
        with Image.open(infile) as im: 
            print(infile, im.format, "%dx%d" % im.size, im.mode) 
            
    ######
    ./img/hand1.png PNG 720x705 RGB
    
  6. 图像截取

    使用im.crop对图像进行截取。

    from PIL import Image 
    file="./img/hand1.png" 
    #读取图像数据 
    im=Image.open(file) 
    #初始化截取图像的范围 
    box = (100,100, 300, 200) 
    # box = (x1,y1, x2, y2)
    #完成图像的截取并保存图像 
    im2 = im.crop(box) 
    im2.save("enjoy_region.jpeg", "JPEG") 
    
图像显示

im.show()

from PIL import Image 
file="./img/hand1.png" 
im=Image.open(file) 
im.show()
图像尺寸变换

im.resize()提供了图像尺寸变换功能,可以按照需要变换源图像的尺寸。

im.rotate()提供了图像旋转功能,可以根据需要旋转不同的角度。

from PIL import Image 
file="./img/hand1.png" 
im=Image.open(file) 
im2 = im.resize((256,256)).rotate(90) #将图像重置为256px×256px,然后旋转90° 
im2.save("enjoy_rotate.jpeg", "JPEG") 
像素变换
  1. 像素色彩模式变换

    可以通过convert()对图像进行灰度化处理

    这个函数提供了将图像进行像素色彩模式转换的功能,可以在支持的像素色彩格式间进行转换。

    from PIL import Image 
    file="./img/hand1.png" 
    #将图像模式转换为灰度模式 
    im=Image.open(file).convert("L") 
    im.save("enjoy_convert.jpeg", "JPEG")
    im.show()
    
  2. 滤波

    im.filter()提供了图像滤波的功能

    ImageFilter中定义了支持的滤波

    • BLUR

      ImageFilter.BLUR为模糊滤波

    • CONTOUR

      ImageFilter.CONTOUR为轮廓滤波,将图像中的轮廓信息全部提取出来。

    • DETAIL

      ImageFilter.DETAIL为细节增强滤波,会使得图像中细节更加明显。

    • EDGE_ENHANCE

      ImageFilter.EDGE_ENHANCE为边缘增强滤波,突出、加强和改善图像中不同灰度区域之间的边界和轮廓的图像增强方法。

    • EDGE_ENHANCE_MORE

      ImageFilter.EDGE_ENHANCE_MORE为深度边缘增强滤波,会使得图像中边缘部分更加明显。

    from PIL import Image
    from PIL import ImageFilter
    file="./img/hand1.png" 
    im=Image.open(file) 
    im2 = im.filter(ImageFilter.BLUR) 
    im2.save("enjoy_filter.jpeg", "JPEG")
    im2.show()
    
    例子 – 转换为CIFAR-10数据集格式

    CIFAR-10数据集是8000万微⼩图⽚的标签⼦集, 由 6万张 32*32得彩色图片组成,一共有10个类别。每一个类别6000张图片。

    每个二进制文件的第一个字节是标记,后面的32x32x3是图片,前32x32是red channel 接着的32x32是green channel,然后32x32是blue channel ,依次类推。

    这里使用字典分别存储数据和标签。

    import pickle
    from PIL import Image 
    import numpy as np 
    import os 
    
    class DictSave(object): 
        def __init__(self, filenames, file): 
            self.filenames = filenames 
            self.file=file 
            self.arr = [] 
            self.all_arr = [] 
            self.label=[]
            self.all_label=[]
            
        #定义图像输入函数 
        def image_input(self, filenames, file): 
    
            for filename in filenames: 
                self.arr, self.label = self.read_file(filename, file) 
                if len(self.all_arr)==0:
                    self.all_arr = self.arr 
                    self.all_label=self.label
                else:
                    self.all_arr = np.concatenate((self.all_arr, self.arr))
                    self.all_label = np.concatenate((self.all_label, self.label))
    
        #定义文件读取函数 
        def read_file(self, filename, file): 
            im = Image.open(filename) #打开一个图像 
            #将图像的RGB分离 
            r, g, b = im.split() 
            #将PILLOW图像转成数组 
            r_arr = np.array(r).ravel() 
            g_arr = np.array(g).ravel()
            b_arr = np.array(b).ravel()
    
            #将3个一维数组合并成一个一维数组
            arr = np.concatenate((r_arr, g_arr, b_arr))
    
            label=[] 
            for i in file: 
                label.append(i[0]) 
            return arr, label 
        def pickle_save(self, arr, label): 
            print ("正在存储") 
            #构造字典,所有的图像数据都在arr数组里
            contact = {'data': arr, 'label':label} 
            f = open('data_batch', 'wb') 
     
            pickle.dump(contact, f) #把字典保存到文本中 
            f.close() 
            print ("存储完毕")
            
    if __name__ == "__main__": 
        file_dir='./img/' 
        L=[] 
        F=[] 
        for root, dirs, files in os.walk(file_dir): 
            for file in files:
                if os.path.splitext(file)[1] == '.jpeg': 
                    L.append(os.path.join(root, file)) 
                    F.append(os.path.splitext(file)) 
     
        ds = DictSave(L, F)
    
        ds.image_input(ds.filenames, ds.file)
        ds.pickle_save(ds.all_arr, ds.label) 
        print ("最终数组的大小:"+str(ds.all_arr.shape))
    
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

暴风雨中的白杨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值