pickle和pillow基础使用

 

1.pickle模块

python的pickle模块实现了基本的数据序列化和反序列化。(序列化即将对象用二进制表示)过pickle模块的序列化操作我们能够将程序中运行的对象信息保存到文件中去,永久存储;通过pickle模块的反序列化操作,我们能够从文件中创建上一次程序保存的对象。

函数pickle.dump(obj, file, [, protocol])

将对象obj保存到文件file中。

函数pickle.load(file)

从字节流中回复一个对象

import pickle
f = open('somedata.pkl', 'wb')
pickle.dump([1, 2, 3, 4], f)
pickle.dump('hello', f)
pickle.dump({'Apple', 'Pear', 'Banana'})
f.close()

pickle不能处理超过4G.

 

2.pillow模块

使用 Image 类

PIL最重要的类是 Image class, 你可以通过多种方法创建这个类的实例;你可以从文件加载图像,或者处理其他图像, 或者从 scratch 创建。

打开图片,获取图片属性,显示图片示例。

图像和数组互相转换

%matplotlib inline


import matplotlib.pyplot as plt
from PIL import Image


import numpy as np
img = Image.open('crop001522.png')
img.thumbnail((64, 64), Image.ANTIALIAS)
print(img.format, img.size, img.mode)#PPM (512, 512) RGB
img_array = np.array(img)
im = Image.fromarray(np.uint8(img_array))
imgplot = plt.imshow(im)

 

读写、缩放图片示例

import os, sys
from PIL import Image

for infile in sys.argv[1:]:
    f, e = os.path.splitext(file)
    outfile = f + '.jpg'
    if omfo;e != outfile:
        try:
            Image.open(infile).save(outfile)
            
        except IOError:
            print('cannot convert ', infile)

缩放图像并另存为其他格式

import os, sys
from PIL import Image

size= (128, 128)

for infile in sys.argv[1]:
    outfile = os.path.splitext(infile)[0] + '.thumbnail'
    if infile != outfile:
        try:
            im = Image.open(infile)
            im.thumbnail(size)
            im.save(outfile, 'JPEG')
        except IOError:
            print('cannot create thumbnail for ', infile)

剪切,粘贴,合并图像

box = [100, 100, 400, 400]
region = im.crop(box)
region = region.transpose(Image.ROTATE_180)
im.paste(region, box)

分离和合并颜色通道

r, g, b = im.split()
im = Image.merge("RGB", (b, g, r))

简单几何变换

out = im.resize((128, 128))
out = im.rotate(45)

旋转图像,颜色变换

out = im.transpose(Image.FLIP_LEFT_RIGHT)
im = Image.open("lean.ppm").convert("L")

颜色增强,应用过滤器,点操作

from PIL import ImageFilter
out = im.filter(ImageFilter.DETAIL)
point_operation = im.point(lambda i: i*1.2)

处理个别bands

source = im.split()

R, G, B = 0, 1, 2
#如果i小鱼10返回255否则返回0

mask = source[R].point(lambda i: i < 100 and 255)

out = source[G].point(lambda I: i * 0.7)

source[G].paste(out, None, mask)
 
im = Image.merge(im.mode, source)

图像增强

一旦创建图像,可以通过ImageEnhance模块,调节亮度,对比度,颜色空间和锐化。

from PIL import ImageEnhance

enh = ImageEnhance.Contrast(im)
enh.enhance(1.3).show("30% more contrast")

python中不同模块读取图片的方法

参考:https://www.cnblogs.com/skyfsm/p/8276501.html

参考中文文档:https://pillow-cn.readthedocs.io/zh_CN/latest/handbook/tutorial.html

参考英文文档:https://pillow.readthedocs.io/en/stable/reference/Image.html?highlight=open

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值