欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

Python模块(3)--PIL 简易使用教程

发布时间:2023/12/13 python 29 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Python模块(3)--PIL 简易使用教程 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

PIL模块-用与记

  • 1.图片导入Image.open()
  • 2.图像显示.show()
  • 4.查看图片属性.format,.size,.mode
  • 3.图像格式转换.convert()
  • 4.图像模式“L”,“RGB”,"CYMK"
  • 5. 图片旋转.rotate()
    • 旋转方式1:旋转不扩展
    • 旋转方式2:旋转扩展
    • 旋转方式3:旋转,扩展,白色填充
  • 6.图片切割.crop()
  • 7.图片保存.save()

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’

总结

以上是生活随笔为你收集整理的Python模块(3)--PIL 简易使用教程的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。