python PIL库详解

官方网站:https://pillow.readthedocs.io/en/4.3.x/

参考链接:

https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014320027235877860c87af5544f25a8deeb55141d60c5000



PIL:Python Imaging Library,已经是Python平台事实上的图像处理标准库了。PIL功能非常强大,但API却非常简单易用。
由于PIL仅支持到Python 2.7,加上年久失修,于是一群志愿者在PIL的基础上创建了兼容的版本,名字叫Pillow,支持最新Python 3.x,又加入了许多新特性,因此,我们可以直接安装使用Pillow。


安装命令: pip3  install pillow

基本操作:

>>> from PIL import Image
>>> # 生成对应图片的img对象
>>> img = Image.open('C:/Users/Administrator/Desktop/g2.jpg')
>>> # 宽度和高度的像素值
>>> img.size
(320, 180)
>>> # 图像格式
>>> img.format
'JPEG'
>>> # 图片模式,有L,RGB和CMYK等
>>> img.mode
'RGB'
>>> # 获取(1, 2)坐标处的RGB通道值
>>> img.getpixel((1, 2))
(79, 123, 188)
>>> # 将图像转化为灰度图像
>>> img = img.convert('L')
>>> # 将图片的宽度和高度都变为(180, 180)
>>> img = img.resize((180, 180))
>>> # 展示图像
>>> img.show()
>>> # 保存图像
>>> img.save('C:/Users/Administrator/Desktop/g.jpg')

相关操作:

from PIL import Image, ImageFilter

img = Image.open('1.jpg')
# 模糊操作
img_blur = img.filter(ImageFilter.BLUR)
img_blur.show()

# 将三个通道分离的图像
r, g, b = img.split()
r.show()
g.show()
b.show()

# 滤镜操作
img_detail = img.filter(ImageFilter.DETAIL)
img_detail.show()

# 逆时针
img_rotate = img.rotate(90)
img_rotate.show()

生成图片验证码实例:
from PIL import Image, ImageDraw, ImageFont
import random


def random_color():
    return random.randint(64, 255), random.randint(64, 255), random.randint(64, 255)


def random_color2():
    return random.randint(32, 127), random.randint(32, 127), random.randint(32, 127)


def random_char():
    return chr(random.randint(65, 90))


# 创建图像,默认为黑色,可以修改参数color=(r, g, b)的值来赋予颜色
img = Image.new('RGB', (240, 60))
# 创建字体,使用系统自带的ttf字体文件
img_font = ImageFont.truetype(r'C:\Windows\Fonts\arial.ttf', 40)
# 生成ImageDraw对象,能对图像进行注释,修描等操作
draw = ImageDraw.Draw(img)
for x in range(240):
    for y in range(60):
        draw.point((x, y), fill=random_color())

for k in range(4):
    draw.text((60 * k + 10, 10), random_char(), font=img_font, fill=random_color2())

img.show()



Image对象与array之间的转换

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

img = np.array(Image.open('1.jpg'))
# 坐标(100, 100)RGB元组值
print(img[100, 100])
# array的类型:uint8
print(img.dtype)
# 展示array代表的图像
plt.imshow(img)
# 将array转换为Image对象
image = Image.fromarray(img)
image.show()
plt.show()



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值