PythonLibs(3) -- PIL


PIL:Python Imaging Library,为Python图像处理常用的库。

PIL手册网站:http://effbot.org/imagingbook/pil-index.htm
PIL库中最重要的一个类:Image,可以通过这个类/模块 导入图像,处理图像,保存图像

import Image

1.图片导入Image.open()

img=Image.open(“xxx/xxx/lena.jpg”)

导入路径中的文件名后要带扩展名,不然会报一下错误:

IOError: [Errno 2] No such file or directory: ‘lena’

2.图像显示.show()

img.show()

在这里插入图片描述

4.查看图片属性.format,.size,.mode

图片源格式,图片尺寸,图片模式

print(img.format , img.size , img.mode)

输出

(‘JPEG’, (200, 200), ‘RGB’)

3.图像格式转换.convert()

img.convert('L")
img.show()

在这里插入图片描述
mode 从"RGB" 转变成"L"

4.图像模式“L”,“RGB”,“CYMK”

PIL中的图像有一下9种模式,使用.convert()函数,可以让图片在这9中模式中来回转换。(作为参数,模式要加引号)
· 1 (1-bit pixels, black and white, stored with one pixel per byte)
· L (8-bit pixels, black and white) # 灰度
· P (8-bit pixels, mapped to any other mode using a colour palette)
· RGB (3x8-bit pixels, true colour) # 彩色
· RGBA (4x8-bit pixels, true colour with transparency mask)
· CMYK (4x8-bit pixels, colour separation)
· YCbCr (3x8-bit pixels, colour video format)
· I (32-bit signed integer pixels)
· F (32-bit floating point pixels)
参考资料:https://www.cnblogs.com/shangpolu/p/8041848.html

5. 图片旋转.rotate()

旋转方式1:旋转不扩展

#在原图上旋转,旋转后的图像与原图大小一致,转出图像的部分会被丢弃,所以会造成信息丢失
img2=img.rotate(45)

在这里插入图片描述

旋转方式2:旋转扩展

#旋转后扩展,信息不丢失,图像尺寸变大
img3=img.rotate(45,expand=True)

在这里插入图片描述)

旋转方式3:旋转,扩展,白色填充

img_alpha=img.convert("RGBA")  # 将原图转换成RGBA的格式,四个通道,另一个通道表示透明度,默认为255,完全不透明
rot = img_alpha.rotate(45, expand = True) # 旋转图片

fff=Image.new("RGBA",rot.size,(255,255,255,255))
out=Image.composite(rot,fff,mask=rot)
out.convert(img.mode).show()
# RGBA模式需要转换成RGB,才能存储,不然会报错

在这里插入图片描述

参考资料:https://blog.csdn.net/luolinll1212/article/details/83059118

6.图片切割.crop()

box = (0, 0, 100, 150) #切割区域的四个坐标(left,top,right,bottom) 
region = img.crop(box)

在这里插入图片描述

PIL 图像坐标系以图像的左上角为(0,0)位置,第一维度为长,第二维度为高。

7.图片保存.save()

img.save(“…/testdir/img.jpg”)

如果文件目录不存在,就会报错

FileNotFoundError: [Errno 2] No such file or directory: ‘…/testdir/img.jpg’

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值