网站首页 文章专栏 python PIL 操作图片
python PIL 操作图片
创建于:2019-06-18 07:23:19 更新于:2024-04-19 02:36:03 羽瀚尘 1825
python python

python中对图片的操作多种多样,本文介绍其中一种:PIL

Image 类是 PIL 库中一个非常重要的类,通过这个类来创建实例可以有直接载入图像文件,读取处理过的图像和通过抓取的方法得到的图像这三种方法。

安装

PIL并不是包名,要使用该包需要首先安装pillow包。

pip install pillow

博文指出PIL和pillow不是同一个事物,且PIL和pillow不能共存,暂没有查证。目前通过安装pillow包使用PIL没有发现问题。

从文件中读取图片

from PIL import Image
myimg = Image.open('python.png')
myimg
# output: <PIL.PngImagePlugin.PngImageFile image mode=RGBA size=1890x800 at 0x26D5E8B8828>
dir(myimg)
# output: ['_Image__transformer', '_PngImageFile__idat', '__array_interface__', '__class__', '__copy__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_close_exclusive_fp_after_loading', '_copy', '_crop', '_dump', '_ensure_mutable', '_exclusive_fp', '_expand', '_min_frame', '_new', '_open', '_repr_png_', '_seek_check', 'alpha_composite', 'category', 'close', 'convert', 'copy', 'crop', 'decoderconfig', 'decodermaxblock', 'draft', 'effect_spread', 'filename', 'filter', 'format', 'format_description', 'fp', 'frombytes', 'fromstring', 'getbands', 'getbbox', 'getchannel', 'getcolors', 'getdata', 'getextrema', 'getim', 'getpalette', 'getpixel', 'getprojection', 'height', 'histogram', 'im', 'info', 'load', 'load_end', 'load_prepare', 'load_read', 'mode', 'offset', 'palette', 'paste', 'png', 'point', 'putalpha', 'putdata', 'putpalette', 'putpixel', 'pyaccess', 'quantize', 'readonly', 'remap_palette', 'resize', 'rotate', 'save', 'seek', 'show', 'size', 'split', 'tell', 'text', 'thumbnail', 'tile', 'tobitmap', 'tobytes', 'toqimage', 'toqpixmap', 'tostring', 'transform', 'transpose', 'verify', 'width']
myimg.show()
# 使用默认看图软件打开

从矩阵生成图片

注意矩阵的下述属性: 1. 维度 要么是两维的(黑白),要么是三维的(彩色)且第三维为3 2. 数据类型 必须为uint8型,建议使用numpy

彩色(三通道)

from PIL import Image
import numpy as np
Image.fromarray(np.zeros([3,3,3],np.uint8))
# output: <PIL.Image.Image image mode=RGB size=3x3 at 0x26D5ED0FB70>

黑白(单通道)

from PIL import Image
import numpy as np
Image.fromarray(np.zeros([3,3],np.uint8))
# output: <PIL.Image.Image image mode=L size=3x3 at 0x26D5ECCAE80>

注意如果第三维通道数为1,会报错

图片resize

myimg
# output: <PIL.PngImagePlugin.PngImageFile image mode=RGBA size=1890x800 at 0x26D5E8B8828>
myimg.resize((4,4))
# output: <PIL.Image.Image image mode=RGBA size=4x4 at 0x26D5FB4AD68>

图片保存

myimg.resize((4,4)).save('hello.png')

报错信息

TypeError: Cannot handle this data type

这种一般是通道数不对