Python PIL.Image模块:图片变更尺寸大小(宽x高)

现实需求:变更图片尺寸

要求:原图为建行一广告图片(来源于网络),缩小为800x600的小图片。

>>> import os
>>> from PIL import Image
>>> f_in = 'd:\\ccb.png'
>>> img = Image.open(f_in)
>>> out = img.resize((800, 600),Image.ANTIALIAS)
>>> fout = 'd:\\png800x600.png'
>>> out.save(fout,'png')
>>> img
<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=3307x2244 at 0x2B31E80>
>>> img.show()
>>> img.close()

图片原尺寸 3307x2244 大小4690KB,转换后: 800x600 大小548KB 

变更尺寸大小: .resize()方法

第一个参数:
(width, height): 宽高二元组

第二个参数:
Image.NEAREST :低质量 
Image.BILINEAR:双线性 
Image.BICUBIC :三次样条插值 
Image.ANTIALIAS:高质量

获取图片属性:

import os
from PIL import Image

path = os.path.join(os.getcwd(),"d:\\ccb.png")
img = Image.open(path)
>>> print(img.format)
PNG
>>> print(img.size)
(3307, 2244)
>>> print(img.mode)
RGBA
>>> print(img.palette)
None
>>> print(list(img.info))
['dpi', 'icc_profile', 'chromaticity']
>>> print(img.info['dpi'])
(72, 72)
>>> print(img.info['chromaticity'])
(0.31269, 0.32899, 0.63999, 0.33001, 0.3, 0.6, 0.15, 0.05999)
# icc_profile 文档二进制代码,太长略

获取网络图片信息:

>>> from urllib import request
>>> from PIL import Image
>>> url = 'https://img-blog.csdnimg.cn/20210615142650803.png'
>>> req = request.urlopen(url)
>>> img = Image.open(req)
>>> print(url,img.format,img.size)
https://img-blog.csdnimg.cn/20210615142650803.png PNG (3307, 2244)
>>> 

以下扩展整理一下IMG模块的内容,来源于网络

PIL.Image模块详情:

Image模块是PIL中最重要的模块,它有一个类叫做image,与模块名称相同

一、Image类的属性:

1、Format   2、Mode   3、Size    4、Palette    5、Info

二、Image类的函数:

1、New   2、Open   3、Blend   4、Composite   5、Eval   6、Frombuffer   7、Fromstring   8、Merge

三、Image类的方法:

1、Convert   2、Copy   3、Crop   4、Draft   5、Filter   6、Fromstring   7、Getbands   8、Getbbox   9、Getcolors  10、Getdata     11、 Getextrema    12、Getpixel    13、Histogram    14、Load    15、Paste

PIL基本概念

通道(bands)、模式(mode)、尺寸(size)、坐标系统(coordinate system)、调色板(palette)、信息(info)和滤波器(filters)

1、通道

每张图片都是由一个或者多个数据通道构成。PIL允许在单张图片中合成相同维数和深度的多个通道。

以RGB图像为例,每张图片都是由三个数据通道构成,分别为R、G和B通道。而对于灰度图像,则只有一个通道。

对于一张图片的通道数量和名称,可以通过方法getbands()来获取。方法getbands()是Image模块的方法,它会返回一个字符串元组(tuple)。该元组将包括每一个通道的名称。

Python的元组与列表类似,不同之处在于元组的元素不能修改,元组使用小括号,列表使用方括号,元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。

from PIL import Image
im = Image.open("ccb.png")
print(im.getbands())
输出:
('R', 'G', 'B')

2、模式

图像的模式定义了图像的类型和像素的位宽。当前支持如下模式:

1:1位像素,表示黑和白,但是存储的时候每个像素存储为8bit。
L:8位像素,表示黑和白。
P:8位像素,使用调色板映射到其他模式。
RGB:3x8位像素,为真彩色。
RGBA:4x8位像素,有透明通道的真彩色。
CMYK:4x8位像素,颜色分离。
YCbCr:3x8位像素,彩色视频格式。
I:32位整型像素。
F:32位浮点型像素。
PIL也支持一些特殊的模式,包括RGBX(有padding的真彩色)和RGBa(有自左乘alpha的真彩色)。
可以通过mode属性读取图像的模式。其返回值是包括上述模式的字符串。

from PIL import Image
im = Image.open("ccb.png")
print(im.mode)
输出:
'RGB'

3、尺寸

通过size属性可以获取图片的尺寸。这是一个二元组,包含水平和垂直方向上的像素数。

from PIL import Image
im = Image.open("ccb.png")
print(im.size)
输出:
(800, 600)

 4、坐标系统

PIL使用笛卡尔像素坐标系统,坐标(0,0)位于左上角。注意:坐标值表示像素的角;位于坐标(0,0)处的像素的中心实际上位于(0.5,0.5)。

坐标经常用于二元组(x,y)。长方形则表示为四元组,前面是左上角坐标。

5、调色板

调色板模式 ("P")使用一个颜色调色板为每个像素定义具体的颜色值

6、信息

使用info属性可以为一张图片添加一些辅助信息。这个是字典对象。加载和保存图像文件时,多少信息需要处理取决于文件格式。

from PIL import Image
im = Image.open("ccb.png")
print(im.info)
输出:
{}

7、  滤波器

对于将多个输入像素映射为一个输出像素的几何操作,PIL提供了4个不同的采样滤波器:

NEAREST:最近滤波。从输入图像中选取最近的像素作为输出像素。它忽略了所有其他的像素。
BILINEAR:双线性滤波。在输入图像的2x2矩阵上进行线性插值。注意:PIL的当前版本,做下采样时该滤波器使用了固定输入模板。
BICUBIC:双立方滤波。在输入图像的4x4矩阵上进行立方插值。注意:PIL的当前版本,做下采样时该滤波器使用了固定输入模板。
ANTIALIAS:平滑滤波。这是PIL 1.1.3版本中新的滤波器。对所有可以影响输出像素的输入像素进行高质量的重采样滤波,以计算输出像素值。在当前的PIL版本中,这个滤波器只用于改变尺寸和缩略图方法。
注意:在当前的PIL版本中,ANTIALIAS滤波器是下采样(例如,将一个大的图像转换为小图)时唯一正确的滤波器。BILIEAR和BICUBIC滤波器使用固定的输入模板,用于固定比例的几何变换和上采样是最好的。
Image模块中的方法resize()和thumbnail()用到了滤波器。

方法resize()的定义为:resize(size, filter=None)=> image

from PIL import Image
im = Image.open("ccb.png")
print(im.size)
im_resize = im.resize((640,480))
print(im_resize.size)
输出:
(800, 600)
(640, 480)

对参数filter不赋值的话,方法resize()默认使用NEAREST滤波器。如果要使用其他滤波器可以通过下面的方法来实现: 

from PIL import Image
im = Image.open("ccb.png")
print(im.size)
im_resize0 = im.resize((640,480), Image.BILINEAR)
print(im_resize0.size)
im_resize1 = im.resize((640,480), Image.BICUBIC)
print(im_resize1.size)
im_resize2 = im.resize((640,480), Image.ANTIALIAS)
print(im_resize2.size)
输出:
(800, 600)
(640, 480)
(640, 480)
(640, 480)

Image类的属性

1、  Format

定义:im.format ⇒ string or None
含义:源文件的文件格式。如果是由PIL创建的图像,则其文件格式为None。

2、  Mode

定义:im.mode ⇒ string
含义:图像的模式。这个字符串表明图像所使用像素格式。该属性典型的取值为“1”,“L”,“RGB”或“CMYK”。

3、  Size

定义:im.size ⇒ (width, height)
含义:图像的尺寸,按照像素数计算。它的返回值为宽度和高度的二元组(width, height)。

4、  Palette

定义:im.palette ⇒ palette or None
含义:颜色调色板表格。如果图像的模式是“P”,则返回ImagePalette类的实例;否则,将为None。

 5、  Info

定义:im.info ⇒ dictionary
含义:存储图像相关数据的字典。文件句柄使用该字典传递从文件中读取的各种非图像信息。大多数方法在返回新的图像时都会忽略这个字典;因为字典中的键并非标准化的,对于一个方法,它不能知道自己的操作如何影响这个字典。
     如果用户需要这些信息,需要在方法open()返回时保存这个字典。

from PIL import Image
im= Image.open("test.png")
print(im.format)
输出:
'png'


from PIL import Image
im = Image.open("test.jpg")
print(im.mode)
print(im.palette)
输出: 
RGB
None

 Image类的函数

1、  New

定义:Image.new(mode,size) ⇒ image
     Image.new(mode, size, color) ⇒ image
含义:使用给定的变量mode和size生成新的图像。Size是给定的宽/高二元组,这是按照像素数来计算的。对于单通道图像,变量color只给定一个值;对于多通道图像,变量color给定一个元组(每个通道对应一个值)。
     在版本1.1.4及其之后,用户也可以用颜色的名称,比如给变量color赋值为“red”。如果没有对变量color赋值,图像内容将会被全部赋值为0(图像即为黑色)。如果变量color是空,图像将不会被初始化,即图像的内容全为0。
     这对向该图像复制或绘制某些内容是有用的。

2、  Open

定义:Image.open(file) ⇒ image
     Image.open(file, mode) ⇒ image
含义:打开并确认给定的图像文件。这个是一个懒操作;该函数只会读文件头,而真实的图像数据直到试图处理该数据才会从文件读取(调用load()方法将强行加载图像数据)。如果变量mode被设置,那必须是“r”。
     用户可以使用一个字符串(表示文件名称的字符串)或者文件对象作为变量file的值。文件对象必须实现read(),seek()和tell()方法,并且以二进制模式打开。

3、  Blend

定义:Image.blend(image1,image2, alpha) ⇒ image
含义:使用给定的两张图像及透明度变量alpha,插值出一张新的图像。这两张图像必须有一样的尺寸和模式。
     合成公式为:out = image1 *(1.0 - alpha) + image2 * alpha
     如果变量alpha为0.0,将返回第一张图像的拷贝。如果变量alpha为1.0,将返回第二张图像的拷贝。对变量alpha的值没有限制。

4、  Composite

定义:Image.composite(image1,image2, mask) ⇒ image
含义:使用给定的两张图像及mask图像作为透明度,插值出一张新的图像。变量mask图像的模式可以为“1”,“L”或者“RGBA”。所有图像必须有相同的尺寸。

5、  Eval

定义:Image.eval(image,function) ⇒ image
含义:使用变量function对应的函数(该函数应该有一个参数)处理变量image所代表图像中的每一个像素点。如果变量image所代表图像有多个通道,那变量function对应的函数作用于每一个通道。
     注意:变量function对每个像素只处理一次,所以不能使用随机组件和其他生成器。

注:图像im_eval与im01比较,其像素值均为im01的一半,则其亮度自然也会比im01暗一些。

6、  Frombuffer

定义:Image.frombuffer(mode,size, data) ⇒ image
     Image.frombuffer(mode, size,data, decoder, parameters) ⇒ image
含义:(New in PIL 1.1.4)使用标准的“raw”解码器,从字符串或者buffer对象中的像素数据产生一个图像存储。对于一些模式,这个图像存储与原始的buffer(这意味着对原始buffer对象的改变体现在图像本身)共享内存。
      并非所有的模式都可以共享内存;支持的模式有“L”,“RGBX”,“RGBA”和“CMYK”。对于其他模式,这个函数与fromstring()函数一致。
注意:版本1.1.6及其以下,这个函数的默认情况与函数fromstring()不同。这有可能在将来的版本中改变,所以为了最大的可移植性,当使用“raw”解码器时,推荐用户写出所有的参数,如下所示:
im =Image.frombuffer(mode, size, data, "raw", mode, 0, 1)
函数Image.frombuffer(mode,size, data, decoder, parameters)与函数fromstring()的调用一致。

7、  Fromstring

定义:Image.fromstring(mode,size, data) ⇒ image
     Image.fromstring(mode, size,data, decoder, parameters) ⇒ image
含义:函数Image.fromstring(mode,size, data),使用标准的“raw”解码器,从字符串中的像素数据产生一个图像存储。
函数Image.fromstring(mode,size, data, decoder, parameters)也一样,但是允许用户使用PIL支持的任何像素解码器。更多信息可以参考:Writing YourOwn File Decoder.
注意:这个函数只对像素数据进行解码,而不是整个图像。如果用户的字符串包含整个图像,可以将该字符串包裹在StringIO对象中,使用函数open()来加载。

8、  Merge

定义:Image.merge(mode,bands) ⇒ image
含义:使用一些单通道图像,创建一个新的图像。变量bands为一个图像的元组或者列表,每个通道的模式由变量mode描述。所有通道必须有相同的尺寸。
变量mode与变量bands的关系:
len(ImageMode.getmode(mode).bands)= len(bands)

from PIL import Image
im = Image.new("RGB", (128, 128), "#FF0000")
im.save("test1.png")
#图像im为128x128大小的红色图像。
im = Image.new("RGB", (128, 128))
#图像im为128x128大小的黑色图像,因为变量color不赋值的话,图像内容被设置为0,即黑色。
im.save("test2.png")
im = Image.new("RGB", (128, 128), "red")
#图像im为128x128大小的红色图像。
im.save("test3.png")


from PIL import Image
im1 = Image.open("test1.jpg")
im2 = Image.open("test2.jpg")
im = Image.blend(im1,im2,0.5)
im.save("test3.jpg")


from PIL import Image
im1 = Image.open("test1.jpg")
im2 = Image.open("test2.jpg")
r,g,b = im1.split()
print(g.mode)
im = Image.composite(im1,im2,b)
im.save("test3.jpg")
b.save("test4.jpg")


from PIL import Image
im = Image.open("test1.jpg")
def deffun(c):
    return c*0.89   #改变了亮度
im_eval = Image.eval(im,deffun)  
im_eval.save("test2.jpg")


from PIL import Image
im1 = Image.open("test1.jpg")
im2 = Image.open("test2.jpg")
r1,g1,b1 = im1.split()
r2,g2,b2 = im2.split()
imgs =[r1,g2,b2]
im_merge = Image.merge("RGB",imgs)
im_merge.save("test3.jpg")

Image类的方法

除非另作说明,Image类的所有方法都将返回一个Image类的新实例,这个实例对应于结果图像。

1、Convert

定义1:im.convert(mode)⇒ image
含义1:将当前图像转换为其他模式,并且返回新的图像。
当从一个调色板图像转换时,这个方法通过这个调色板来转换像素。如果不对变量mode赋值,该方法将会选择一种模式,在没有调色板的情况下,使得图像和调色板中的所有信息都可以被表示出来。
当从一个颜色图像转换为黑白图像时,PIL库使用ITU-R601-2 luma转换公式:
L = R * 299/1000 + G * 587/1000 + B * 114/1000
当转换为2位图像(模式“1”)时,源图像首先被转换为黑白图像。结果数据中大于127的值被设置为白色,其他的设置为黑色;这样图像会出现抖动。如果要使用其他阈值,更改阈值127,可以使用方法point()。
为了去掉图像抖动现象,可以使用dither选项。
 
定义2:im.convert(“P”,**options) ⇒ image
含义2:这个与第一个方法定义一样,但是当“RGB”图像转换为8位调色板图像时能更好的处理。可供选择的选项为:
      Dither=. 控制颜色抖动。默认是FLOYDSTEINBERG,与邻近的像素一起承担错误。不使能该功能,则赋值为NONE。
      Palette=. 控制调色板的产生。默认是WEB,这是标准的216色的“web palette”。要使用优化的调色板,则赋值为ADAPTIVE。
      Colors=. 当选项palette为ADAPTIVE时,控制用于调色板的颜色数目。默认是最大值,即256种颜色。
 
定义3:im.convert(mode,matrix) ⇒ image
含义3:使用转换矩阵将一个“RGB”图像转换为“L”或者“RGB”图像。变量matrix为4或者16元组。

#将一个RGB图像(根据ITU-R709线性校准,使用D65亮度)转换到CIE XYZ颜色空间:
from PIL import Image
im1 = Image.open("test1.jpg")
im1.mode
rgb2xyz = (
    0.412453, 0.357580, 0.180423, 0,
    0.212671, 0.715160, 0.072169, 0,
    0.019334, 0.119193, 0.950227, 0 )
im_c3 = im1.convert("L", rgb2xyz)
im_c3.save("test2.jpg")
print(im_c3.mode)
输出:
L

#将“RGB”模式的test1图像,转换为“1”模式的test2图像
from PIL import Image
im1 = Image.open("test1.jpg")
print(im1.mode)
out = im1.convert("1")
out.save("test2.jpg")
print(out.mode)
输出:
1

 2、Copy

定义:im.copy() ⇒ image
含义:拷贝这个图像。如果用户想粘贴一些数据到这张图,可以使用这个方法,但是原始图像不会受到影响。

from PIL import Image
im1 = Image.open("test1.jpg")
im2 = im1.copy()
im2.save("test2.jpg")

3、Crop

定义:im.crop(box) ⇒ image
含义:从当前的图像中返回一个矩形区域的拷贝。变量box是一个四元组,定义了左、上、右和下的像素坐标。
这是一个懒操作。对源图像的改变可能或者可能不体现在裁减下来的图像中。为了获取一个分离的拷贝,对裁剪的拷贝调用方法load()。

from PIL import Image
im1 = Image.open("test1.jpg")
print(im1.size)
box = [0,0,640,480]   #640x480
im_crop = im1.crop(box)
im_crop.save("test2.jpg")

4、Draft

定义:im.draft(mode,size)
含义:配置图像文件加载器,使得返回一个与给定的模式和尺寸尽可能匹配的图像的版本。例如,用户可以使用这个方法,在加载一个彩色JPEG图像时将其转换为灰色图像,或者从一个PCD文件中提取一个128x192的版本。
注意:这个方法会适时地修改图像对象(精确地说,它会重新配置文件的读取器)。如果图像已经被加载,那这个方法就没有作用了。

from PIL import Image
im1 = Image.open("test1.jpg")
im_draft = im1.draft("L",(500,500))
print(im_draft.size)
im_draft.save("test2.jpg")
输出:
(650, 650)

5、Filter

定义:im.filter(filter) ⇒ image
含义:返回一个使用给定滤波器处理过的图像的拷贝。可用滤波器需要参考ImageFilter模块。

from PIL import Image,ImageFilter
im1 = Image.open("test1.jpg")
im_filter = im1.filter(ImageFilter.BLUR)
im_filter.save("test2.jpg")

6、Fromstring

定义:im.fromstring(data)
     im.fromstring(data, decoder,parameters)
含义:与函数fromstring()一样,但是这个方法会将data加载到当前的图像中。 

7、Getbands

定义:im.getbands()⇒ tuple of strings
含义:返回包括每个通道名称的元组。例如,对于RGB图像将返回(“R”,“G”,“B”)。

8、Getbbox

定义:im.getbbox() ⇒ 4-tuple or None
含义:计算图像非零区域的包围盒。这个包围盒是一个4元组,定义了左、上、右和下像素坐标。如果图像是空的,这个方法将返回空。

from PIL import Image
im1 = Image.open("test.jpg")
print(im1.getbbox())
输出:
(0, 0, 640, 480)

9、  Getcolors

定义:im.getcolors() ⇒ a list of(count, color) tuples or None
     im.getcolors(maxcolors) ⇒ a list of (count, color) tuples or None
含义:(New in 1.1.5)返回一个(count,color)元组的无序list,其中count是对应颜色在图像中出现的次数。
如果变量maxcolors的值被超过,该方法将停止计算并返回空。变量maxcolors默认值为256。为了保证用户可以获取图像中的所有颜色,you can pass in size[0]*size[1](请确保有足够的内存做这件事)。

from PIL import Image
im1 = Image.open("test.png")
print(im1.getcolors(8888888))
输出:
[(2, (255, 255, 255, 233)), (9, (0, 0, 0, 136)), (1, (0, 0, 0, 64)), (2, (0, 0, 0, 24)), (5, (0, 0, 0, 56)).......

10、Getdata

定义:im.getdata() ⇒ sequence
含义:以包含像素值的sequence对象形式返回图像的内容。这个sequence对象是扁平的,以便第一行的值直接跟在第零行的值后面,等等。
注意:这个方法返回的sequence对象是PIL内部数据类型,它只支持某些sequence操作,包括迭代和基础sequence访问。使用list(im.getdata()),将它转换为普通的sequence。

from PIL import Image
im1 = Image.open("test.jpg")
seq = im1.getdata()
print(seq[0])
seq0 = list(seq)
print(seq0[0])
print(len(seq0))
输出:
(41, 183, 197)
(41, 183, 197)
422500        #这个值是长和高之积

注:Sequence对象的每一个元素对应一个像素点的R、G和B三个值。

11、Getextrema

定义:im.getextrema() ⇒ 2-tuple
含义:返回R/G/B三个通道的最小和最大值的2元组,包括该图像中的最小和最大值。

from PIL import Image
im1 = Image.open("test.jpg")
print(im1.getextrema())
输出:
((0, 255), (0,255), (0, 255)) 

12、Getpixel

定义:im.getpixel(xy) ⇒ value or tuple
含义:返回给定位置的像素值。如果图像为多通道,则返回一个元组。
注意:该方法执行比较慢;如果用户需要使用python处理图像中较大部分数据,可以使用像素访问对象(见load),或者方法getdata()。

from PIL import Image
im1 = Image.open("test.jpg")
print(im1.getpixel((1,1)))
print(im1.getpixel((649,649)))
输出:
(41, 183, 197)
(236, 210, 153)
注:im.getpixel(xy)中的X,Y表示坐标,从0开始。

13、Histogram

定义1:im.histogram()⇒ list
含义1:返回一个图像的直方图。这个直方图是关于像素数量的list,图像中的每个象素值对应一个成员。如果图像有多个通道,所有通道的直方图会连接起来(例如,“RGB”图像的直方图有768个值)。
      二值图像(模式为“1”)当作灰度图像(模式为“L”)处理。

from PIL import Image
im1 = Image.open("test.jpg")
ls = im1.histogram()
print(len(ls))
print(ls[767])
输出:
768
1471

14、Load

定义:im.load()
含义:为图像分配内存并从文件中加载它(或者从源图像,对于懒操作)。正常情况下,用户不需要调用这个方法,因为在第一次访问图像时,Image类会自动地加载打开的图像。

     (New in 1.1.6)在1.1.6及以后的版本,方法load()返回一个用于读取和修改像素的像素访问对象。这个访问对象像一个二维队列,如:
      pix = im.load()
      print pix[x, y]
      pix[x, y] =value
      通过这个对象访问比方法getpixel()和putpixel()快很多。

from PIL import Image
im1 = Image.open("test.jpg")
lm_load = im1.load()
print(lm_load[649,649])
输出:
(236, 210, 153)

15、Paste

定义1:im.paste(image,box)
含义1:将一张图粘贴到另一张图像上。变量box或者是一个给定左上角的2元组,或者是定义了左,上,右和下像素坐标的4元组,或者为空(与(0,0)一样)。如果给定4元组,被粘贴的图像的尺寸必须与区域尺寸一样。
如果模式不匹配,被粘贴的图像将被转换为当前图像的模式。

定义2:im.paste(colour,box)
含义2:它与定义1一样,但是它使用同一种颜色填充变量box对应的区域。对于单通道图像,变量colour为单个颜色值;对于多通道,则为一个元组。

定义3:im.paste(image,box, mask)
含义3:与定义1一样,但是它使用变量mask对应的模板图像来填充所对应的区域。可以使用模式为“1”、“L”或者“RGBA”的图像作为模板图像。模板图像的尺寸必须与变量image对应的图像尺寸一致。
      如果变量mask对应图像的值为255,则模板图像的值直接被拷贝过来;如果变量mask对应图像的值为0,则保持当前图像的原始值。变量mask对应图像的其他值,将对两张图像的值进行透明融合。
注意:如果变量image对应的为“RGBA”图像,即粘贴的图像模式为“RGBA”,则alpha通道被忽略。用户可以使用同样的图像作为原图像和模板图像。

定义4:im.paste(colour,box, mask)
含义4:与定义3一样,只是使用变量colour对应的单色来填充区域。

from PIL import Image
im1 = Image.open("test1.jpg")
box = [0,0,200,200]
im_crop = im1.crop(box)
im1.paste(im_crop,(200,200,400,400))  #等价于im1.paste(im_crop,(200,200))
im1.save("test2.jpg")


from PIL import Image
im1 = Image.open("test1.jpg")
im1.paste((256,256,256),(200,100,500,200))
im1.save("test2.jpg")
#注:图像im1的(200,100)位置将出现一个300x100的白色方块,对于多通道的图像,如果变量colour只给定一个数值,将只会应用于图像的第一个通道。如果是“RGB”模式的图像,将应用于红色通道。


from PIL import Image
im1 = Image.open("test1.jpg")
box = [100,100,200,200]
im_crop = im1.crop(box)
r,g,b = im_crop.split()
im1.paste(im_crop,(200,100,300,200),b)
im1.save("test2.jpg")
#注:在图像im1的(0,0)位置将出现一个半透明的100x100的方块。


from PIL import Image
im1 = Image.open("test1.jpg")
box = [100,100,200,200]
im_crop = im1.crop(box)
r,g,b = im_crop.split()
im1.paste((0,256,0),(200,100,300,200),b)
im1.save("test2.jpg")
#注:在图像im1的(0,0)位置将出现一个100x100的绿色方块。

例子汇编:

from PIL import Image
from PIL import ImageEnhance
 
img = Image.open(r'E:\img\f1.png')
img.show()
# 图像二值化
img = img.convert('L')
# 图像放大
img = img.resize((img.width * int(3), img.height * int(4)), Image.ANTIALIAS)
# 对比度增强
enh_con = ImageEnhance.Contrast(img)
contrast = 2
img_contrasted = enh_con.enhance(contrast)
# 亮度增强
enh_bri = ImageEnhance.Brightness(img_contrasted)
brightness = 2.5
image_brightened = enh_bri.enhance(brightness)
# 色度增强
enh_col = ImageEnhance.Color(img)
color = 50
image_colored = enh_col.enhance(color)
# 锐度增强
enh_sha = ImageEnhance.Sharpness(img)
sharpness = 2
image_sharped = enh_sha.enhance(sharpness)
image_sharped.save(r'E:\img\f22.png', dpi=(300, 300), quality=95)
# image_sharped.save(r'E:\img\f22.png')
# 图片汉字识别
img2 = Image.open(r'E:\img\f22.png')
code2 = pytesseract.image_to_string(img2, lang='chi_sim')
# print(code2)

# 图片裁剪
image_cro = Image.open(r'E:\img\f24.png')
image_cropped = image_cro.crop(res)
image_cropped.save(u'E:\img\\f25.png')

# 黑白处理
img_main = Image.open(u'E:/login1.png')
img_main = img_main.convert('L')
threshold1 = 138
table1 = []
for i in range(256):
    if i < threshold1:
        table1.append(0)
    else:
        table1.append(1)
img_main = img_main.point(table1, "1")
img_main.save(u'E:/login3.png')

# 定位图片
def get_screenxy_from_bmp(main_bmp, son_bmp):
    # 获取屏幕上匹配指定截图的坐标->(x,y,width,height)
 
    img_main = Image.open(main_bmp)
    img_main = img_main.convert('L')
    threshold1 = 138
    table1 = []
    for i in range(256):
        if i < threshold1:
            table1.append(0)
        else:
            table1.append(1)
    img_main = img_main.point(table1, "1")
 
    img_son = Image.open(son_bmp)
    img_son = img_son.convert('L')
    threshold2 = 138
    table2 = []
    for i in range(256):
        if i < threshold2:
            table2.append(0)
        else:
            table2.append(1)
    img_son = img_son.point(table2, "1")
 
    datas_a = list(img_main.getdata())
    datas_b = list(img_son.getdata())
    for i, item in enumerate(datas_a):
        if datas_b[0] == item and datas_a[i + 1] == datas_b[1]:
            yx = divmod(i, img_main.size[0])
            main_start_pos = yx[1] + yx[0] * img_main.size[0]
 
            match_test = True
            for n in range(img_son.size[1]):
                main_pos = main_start_pos + n * img_main.size[0]
                son_pos = n * img_son.size[0]
 
                if datas_b[son_pos:son_pos + img_son.size[0]] != datas_a[main_pos:main_pos + img_son.size[0]]:
                    match_test = False
                    break
            if match_test:
                return (yx[1], yx[0], img_son.size[0], img_son.size[1])
    return False

PIL.Image模块——英文版帮助:

>>> help(PIL.Image)
Help on module PIL.Image in PIL:

NAME
    PIL.Image

DESCRIPTION
    # The Python Imaging Library.
    # $Id$
    #
    # the Image class wrapper
    #
    # partial release history:
    # 1995-09-09 fl   Created
    # 1996-03-11 fl   PIL release 0.0 (proof of concept)
    # 1996-04-30 fl   PIL release 0.1b1
    # 1999-07-28 fl   PIL release 1.0 final
    # 2000-06-07 fl   PIL release 1.1
    # 2000-10-20 fl   PIL release 1.1.1
    # 2001-05-07 fl   PIL release 1.1.2
    # 2002-03-15 fl   PIL release 1.1.3
    # 2003-05-10 fl   PIL release 1.1.4
    # 2005-03-28 fl   PIL release 1.1.5
    # 2006-12-02 fl   PIL release 1.1.6
    # 2009-11-15 fl   PIL release 1.1.7
    #
    # Copyright (c) 1997-2009 by Secret Labs AB.  All rights reserved.
    # Copyright (c) 1995-2009 by Fredrik Lundh.
    #
    # See the README file for information on usage and redistribution.
    #

CLASSES
    builtins.Exception(builtins.BaseException)
        DecompressionBombError
    builtins.RuntimeWarning(builtins.Warning)
        DecompressionBombWarning
    builtins.object
        Image
        ImagePointHandler
        ImageTransformHandler
    collections.abc.MutableMapping(collections.abc.Mapping)
        Exif
    
    class DecompressionBombError(builtins.Exception)
     |  Common base class for all non-exit exceptions.
     |  
     |  Method resolution order:
     |      DecompressionBombError
     |      builtins.Exception
     |      builtins.BaseException
     |      builtins.object
     |  
     |  Data descriptors defined here:
     |  
     |  __weakref__
     |      list of weak references to the object (if defined)
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from builtins.Exception:
     |  
     |  __init__(self, /, *args, **kwargs)
     |      Initialize self.  See help(type(self)) for accurate signature.
     |  
     |  ----------------------------------------------------------------------
     |  Static methods inherited from builtins.Exception:
     |  
     |  __new__(*args, **kwargs) from builtins.type
     |      Create and return a new object.  See help(type) for accurate signature.
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from builtins.BaseException:
     |  
     |  __delattr__(self, name, /)
     |      Implement delattr(self, name).
     |  
     |  __getattribute__(self, name, /)
     |      Return getattr(self, name).
     |  
     |  __reduce__(...)
     |      Helper for pickle.
     |  
     |  __repr__(self, /)
     |      Return repr(self).
     |  
     |  __setattr__(self, name, value, /)
     |      Implement setattr(self, name, value).
     |  
     |  __setstate__(...)
     |  
     |  __str__(self, /)
     |      Return str(self).
     |  
     |  with_traceback(...)
     |      Exception.with_traceback(tb) --
     |      set self.__traceback__ to tb and return self.
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors inherited from builtins.BaseException:
     |  
     |  __cause__
     |      exception cause
     |  
     |  __context__
     |      exception context
     |  
     |  __dict__
     |  
     |  __suppress_context__
     |  
     |  __traceback__
     |  
     |  args
    
    class DecompressionBombWarning(builtins.RuntimeWarning)
     |  Base class for warnings about dubious runtime behavior.
     |  
     |  Method resolution order:
     |      DecompressionBombWarning
     |      builtins.RuntimeWarning
     |      builtins.Warning
     |      builtins.Exception
     |      builtins.BaseException
     |      builtins.object
     |  
     |  Data descriptors defined here:
     |  
     |  __weakref__
     |      list of weak references to the object (if defined)
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from builtins.RuntimeWarning:
     |  
     |  __init__(self, /, *args, **kwargs)
     |      Initialize self.  See help(type(self)) for accurate signature.
     |  
     |  ----------------------------------------------------------------------
     |  Static methods inherited from builtins.RuntimeWarning:
     |  
     |  __new__(*args, **kwargs) from builtins.type
     |      Create and return a new object.  See help(type) for accurate signature.
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from builtins.BaseException:
     |  
     |  __delattr__(self, name, /)
     |      Implement delattr(self, name).
     |  
     |  __getattribute__(self, name, /)
     |      Return getattr(self, name).
     |  
     |  __reduce__(...)
     |      Helper for pickle.
     |  
     |  __repr__(self, /)
     |      Return repr(self).
     |  
     |  __setattr__(self, name, value, /)
     |      Implement setattr(self, name, value).
     |  
     |  __setstate__(...)
     |  
     |  __str__(self, /)
     |      Return str(self).
     |  
     |  with_traceback(...)
     |      Exception.with_traceback(tb) --
     |      set self.__traceback__ to tb and return self.
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors inherited from builtins.BaseException:
     |  
     |  __cause__
     |      exception cause
     |  
     |  __context__
     |      exception context
     |  
     |  __dict__
     |  
     |  __suppress_context__
     |  
     |  __traceback__
     |  
     |  args
    
    class Exif(collections.abc.MutableMapping)
     |  Method resolution order:
     |      Exif
     |      collections.abc.MutableMapping
     |      collections.abc.Mapping
     |      collections.abc.Collection
     |      collections.abc.Sized
     |      collections.abc.Iterable
     |      collections.abc.Container
     |      builtins.object
     |  
     |  Methods defined here:
     |  
     |  __contains__(self, tag)
     |  
     |  __delitem__(self, tag)
     |  
     |  __getitem__(self, tag)
     |  
     |  __init__(self)
     |      Initialize self.  See help(type(self)) for accurate signature.
     |  
     |  __iter__(self)
     |  
     |  __len__(self)
     |  
     |  __setitem__(self, tag, value)
     |  
     |  __str__(self)
     |      Return str(self).
     |  
     |  get_ifd(self, tag)
     |  
     |  load(self, data)
     |  
     |  tobytes(self, offset=8)
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors defined here:
     |  
     |  __dict__
     |      dictionary for instance variables (if defined)
     |  
     |  __weakref__
     |      list of weak references to the object (if defined)
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes defined here:
     |  
     |  __abstractmethods__ = frozenset()
     |  
     |  endian = '<'
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from collections.abc.MutableMapping:
     |  
     |  clear(self)
     |      D.clear() -> None.  Remove all items from D.
     |  
     |  pop(self, key, default=<object object at 0x0000000000474140>)
     |      D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
     |      If key is not found, d is returned if given, otherwise KeyError is raised.
     |  
     |  popitem(self)
     |      D.popitem() -> (k, v), remove and return some (key, value) pair
     |      as a 2-tuple; but raise KeyError if D is empty.
     |  
     |  setdefault(self, key, default=None)
     |      D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
     |  
     |  update(self, other=(), /, **kwds)
     |      D.update([E, ]**F) -> None.  Update D from mapping/iterable E and F.
     |      If E present and has a .keys() method, does:     for k in E: D[k] = E[k]
     |      If E present and lacks .keys() method, does:     for (k, v) in E: D[k] = v
     |      In either case, this is followed by: for k, v in F.items(): D[k] = v
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from collections.abc.Mapping:
     |  
     |  __eq__(self, other)
     |      Return self==value.
     |  
     |  get(self, key, default=None)
     |      D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.
     |  
     |  items(self)
     |      D.items() -> a set-like object providing a view on D's items
     |  
     |  keys(self)
     |      D.keys() -> a set-like object providing a view on D's keys
     |  
     |  values(self)
     |      D.values() -> an object providing a view on D's values
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes inherited from collections.abc.Mapping:
     |  
     |  __hash__ = None
     |  
     |  __reversed__ = None
     |  
     |  ----------------------------------------------------------------------
     |  Class methods inherited from collections.abc.Collection:
     |  
     |  __subclasshook__(C) from abc.ABCMeta
     |      Abstract classes can override this to customize issubclass().
     |      
     |      This is invoked early on by abc.ABCMeta.__subclasscheck__().
     |      It should return True, False or NotImplemented.  If it returns
     |      NotImplemented, the normal algorithm is used.  Otherwise, it
     |      overrides the normal algorithm (and the outcome is cached).
    
    class Image(builtins.object)
     |  This class represents an image object.  To create
     |  :py:class:`~PIL.Image.Image` objects, use the appropriate factory
     |  functions.  There's hardly ever any reason to call the Image constructor
     |  directly.
     |  
     |  * :py:func:`~PIL.Image.open`
     |  * :py:func:`~PIL.Image.new`
     |  * :py:func:`~PIL.Image.frombytes`
     |  
     |  Methods defined here:
     |  
     |  __copy__ = copy(self)
     |  
     |  __enter__(self)
     |      # Context manager support
     |  
     |  __eq__(self, other)
     |      Return self==value.
     |  
     |  __exit__(self, *args)
     |  
     |  __getstate__(self)
     |  
     |  __init__(self)
     |      Initialize self.  See help(type(self)) for accurate signature.
     |  
     |  __repr__(self)
     |      Return repr(self).
     |  
     |  __setstate__(self, state)
     |  
     |  alpha_composite(self, im, dest=(0, 0), source=(0, 0))
     |      'In-place' analog of Image.alpha_composite. Composites an image
     |      onto this image.
     |      
     |      :param im: image to composite over this one
     |      :param dest: Optional 2 tuple (left, top) specifying the upper
     |        left corner in this (destination) image.
     |      :param source: Optional 2 (left, top) tuple for the upper left
     |        corner in the overlay source image, or 4 tuple (left, top, right,
     |        bottom) for the bounds of the source rectangle
     |      
     |      Performance Note: Not currently implemented in-place in the core layer.
     |  
     |  close(self)
     |      Closes the file pointer, if possible.
     |      
     |      This operation will destroy the image core and release its memory.
     |      The image data will be unusable afterward.
     |      
     |      This function is only required to close images that have not
     |      had their file read and closed by the
     |      :py:meth:`~PIL.Image.Image.load` method. See
     |      :ref:`file-handling` for more information.
     |  
     |  convert(self, mode=None, matrix=None, dither=None, palette=0, colors=256)
     |      Returns a converted copy of this image. For the "P" mode, this
     |      method translates pixels through the palette.  If mode is
     |      omitted, a mode is chosen so that all information in the image
     |      and the palette can be represented without a palette.
     |      
     |      The current version supports all possible conversions between
     |      "L", "RGB" and "CMYK." The ``matrix`` argument only supports "L"
     |      and "RGB".
     |      
     |      When translating a color image to greyscale (mode "L"),
     |      the library uses the ITU-R 601-2 luma transform::
     |      
     |          L = R * 299/1000 + G * 587/1000 + B * 114/1000
     |      
     |      The default method of converting a greyscale ("L") or "RGB"
     |      image into a bilevel (mode "1") image uses Floyd-Steinberg
     |      dither to approximate the original image luminosity levels. If
     |      dither is :data:`NONE`, all values larger than 128 are set to 255 (white),
     |      all other values to 0 (black). To use other thresholds, use the
     |      :py:meth:`~PIL.Image.Image.point` method.
     |      
     |      When converting from "RGBA" to "P" without a ``matrix`` argument,
     |      this passes the operation to :py:meth:`~PIL.Image.Image.quantize`,
     |      and ``dither`` and ``palette`` are ignored.
     |      
     |      :param mode: The requested mode. See: :ref:`concept-modes`.
     |      :param matrix: An optional conversion matrix.  If given, this
     |         should be 4- or 12-tuple containing floating point values.
     |      :param dither: Dithering method, used when converting from
     |         mode "RGB" to "P" or from "RGB" or "L" to "1".
     |         Available methods are :data:`NONE` or :data:`FLOYDSTEINBERG` (default).
     |         Note that this is not used when ``matrix`` is supplied.
     |      :param palette: Palette to use when converting from mode "RGB"
     |         to "P".  Available palettes are :data:`WEB` or :data:`ADAPTIVE`.
     |      :param colors: Number of colors to use for the :data:`ADAPTIVE` palette.
     |         Defaults to 256.
     |      :rtype: :py:class:`~PIL.Image.Image`
     |      :returns: An :py:class:`~PIL.Image.Image` object.
     |  
     |  copy(self)
     |      Copies this image. Use this method if you wish to paste things
     |      into an image, but still retain the original.
     |      
     |      :rtype: :py:class:`~PIL.Image.Image`
     |      :returns: An :py:class:`~PIL.Image.Image` object.
     |  
     |  crop(self, box=None)
     |      Returns a rectangular region from this image. The box is a
     |      4-tuple defining the left, upper, right, and lower pixel
     |      coordinate. See :ref:`coordinate-system`.
     |      
     |      Note: Prior to Pillow 3.4.0, this was a lazy operation.
     |      
     |      :param box: The crop rectangle, as a (left, upper, right, lower)-tuple.
     |      :rtype: :py:class:`~PIL.Image.Image`
     |      :returns: An :py:class:`~PIL.Image.Image` object.
     |  
     |  draft(self, mode, size)
     |      Configures the image file loader so it returns a version of the
     |      image that as closely as possible matches the given mode and
     |      size. For example, you can use this method to convert a color
     |      JPEG to greyscale while loading it.
     |      
     |      If any changes are made, returns a tuple with the chosen ``mode`` and
     |      ``box`` with coordinates of the original image within the altered one.
     |      
     |      Note that this method modifies the :py:class:`~PIL.Image.Image` object
     |      in place. If the image has already been loaded, this method has no
     |      effect.
     |      
     |      Note: This method is not implemented for most images. It is
     |      currently implemented only for JPEG and MPO images.
     |      
     |      :param mode: The requested mode.
     |      :param size: The requested size.
     |  
     |  effect_spread(self, distance)
     |      Randomly spread pixels in an image.
     |      
     |      :param distance: Distance to spread pixels.
     |  
     |  entropy(self, mask=None, extrema=None)
     |      Calculates and returns the entropy for the image.
     |      
     |      A bilevel image (mode "1") is treated as a greyscale ("L")
     |      image by this method.
     |      
     |      If a mask is provided, the method employs the histogram for
     |      those parts of the image where the mask image is non-zero.
     |      The mask image must have the same size as the image, and be
     |      either a bi-level image (mode "1") or a greyscale image ("L").
     |      
     |      :param mask: An optional mask.
     |      :param extrema: An optional tuple of manually-specified extrema.
     |      :returns: A float value representing the image entropy
     |  
     |  filter(self, filter)
     |      Filters this image using the given filter.  For a list of
     |      available filters, see the :py:mod:`~PIL.ImageFilter` module.
     |      
     |      :param filter: Filter kernel.
     |      :returns: An :py:class:`~PIL.Image.Image` object.
     |  
     |  frombytes(self, data, decoder_name='raw', *args)
     |      Loads this image with pixel data from a bytes object.
     |      
     |      This method is similar to the :py:func:`~PIL.Image.frombytes` function,
     |      but loads data into this image instead of creating a new image object.
     |  
     |  getbands(self)
     |      Returns a tuple containing the name of each band in this image.
     |      For example, ``getbands`` on an RGB image returns ("R", "G", "B").
     |      
     |      :returns: A tuple containing band names.
     |      :rtype: tuple
     |  
     |  getbbox(self)
     |      Calculates the bounding box of the non-zero regions in the
     |      image.
     |      
     |      :returns: The bounding box is returned as a 4-tuple defining the
     |         left, upper, right, and lower pixel coordinate. See
     |         :ref:`coordinate-system`. If the image is completely empty, this
     |         method returns None.
     |  
     |  getchannel(self, channel)
     |      Returns an image containing a single channel of the source image.
     |      
     |      :param channel: What channel to return. Could be index
     |        (0 for "R" channel of "RGB") or channel name
     |        ("A" for alpha channel of "RGBA").
     |      :returns: An image in "L" mode.
     |      
     |      .. versionadded:: 4.3.0
     |  
     |  getcolors(self, maxcolors=256)
     |      Returns a list of colors used in this image.
     |      
     |      :param maxcolors: Maximum number of colors.  If this number is
     |         exceeded, this method returns None.  The default limit is
     |         256 colors.
     |      :returns: An unsorted list of (count, pixel) values.
     |  
     |  getdata(self, band=None)
     |      Returns the contents of this image as a sequence object
     |      containing pixel values.  The sequence object is flattened, so
     |      that values for line one follow directly after the values of
     |      line zero, and so on.
     |      
     |      Note that the sequence object returned by this method is an
     |      internal PIL data type, which only supports certain sequence
     |      operations.  To convert it to an ordinary sequence (e.g. for
     |      printing), use ``list(im.getdata())``.
     |      
     |      :param band: What band to return.  The default is to return
     |         all bands.  To return a single band, pass in the index
     |         value (e.g. 0 to get the "R" band from an "RGB" image).
     |      :returns: A sequence-like object.
     |  
     |  getexif(self)
     |  
     |  getextrema(self)
     |      Gets the the minimum and maximum pixel values for each band in
     |      the image.
     |      
     |      :returns: For a single-band image, a 2-tuple containing the
     |         minimum and maximum pixel value.  For a multi-band image,
     |         a tuple containing one 2-tuple for each band.
     |  
     |  getim(self)
     |      Returns a capsule that points to the internal image memory.
     |      
     |      :returns: A capsule object.
     |  
     |  getpalette(self)
     |      Returns the image palette as a list.
     |      
     |      :returns: A list of color values [r, g, b, ...], or None if the
     |         image has no palette.
     |  
     |  getpixel(self, xy)
     |      Returns the pixel value at a given position.
     |      
     |      :param xy: The coordinate, given as (x, y). See
     |         :ref:`coordinate-system`.
     |      :returns: The pixel value.  If the image is a multi-layer image,
     |         this method returns a tuple.
     |  
     |  getprojection(self)
     |      Get projection to x and y axes
     |      
     |      :returns: Two sequences, indicating where there are non-zero
     |          pixels along the X-axis and the Y-axis, respectively.
     |  
     |  histogram(self, mask=None, extrema=None)
     |      Returns a histogram for the image. The histogram is returned as
     |      a list of pixel counts, one for each pixel value in the source
     |      image. If the image has more than one band, the histograms for
     |      all bands are concatenated (for example, the histogram for an
     |      "RGB" image contains 768 values).
     |      
     |      A bilevel image (mode "1") is treated as a greyscale ("L") image
     |      by this method.
     |      
     |      If a mask is provided, the method returns a histogram for those
     |      parts of the image where the mask image is non-zero. The mask
     |      image must have the same size as the image, and be either a
     |      bi-level image (mode "1") or a greyscale image ("L").
     |      
     |      :param mask: An optional mask.
     |      :param extrema: An optional tuple of manually-specified extrema.
     |      :returns: A list containing pixel counts.
     |  
     |  load(self)
     |      Allocates storage for the image and loads the pixel data.  In
     |      normal cases, you don't need to call this method, since the
     |      Image class automatically loads an opened image when it is
     |      accessed for the first time.
     |      
     |      If the file associated with the image was opened by Pillow, then this
     |      method will close it. The exception to this is if the image has
     |      multiple frames, in which case the file will be left open for seek
     |      operations. See :ref:`file-handling` for more information.
     |      
     |      :returns: An image access object.
     |      :rtype: :ref:`PixelAccess` or :py:class:`PIL.PyAccess`
     |  
     |  paste(self, im, box=None, mask=None)
     |      Pastes another image into this image. The box argument is either
     |      a 2-tuple giving the upper left corner, a 4-tuple defining the
     |      left, upper, right, and lower pixel coordinate, or None (same as
     |      (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size
     |      of the pasted image must match the size of the region.
     |      
     |      If the modes don't match, the pasted image is converted to the mode of
     |      this image (see the :py:meth:`~PIL.Image.Image.convert` method for
     |      details).
     |      
     |      Instead of an image, the source can be a integer or tuple
     |      containing pixel values.  The method then fills the region
     |      with the given color.  When creating RGB images, you can
     |      also use color strings as supported by the ImageColor module.
     |      
     |      If a mask is given, this method updates only the regions
     |      indicated by the mask.  You can use either "1", "L" or "RGBA"
     |      images (in the latter case, the alpha band is used as mask).
     |      Where the mask is 255, the given image is copied as is.  Where
     |      the mask is 0, the current value is preserved.  Intermediate
     |      values will mix the two images together, including their alpha
     |      channels if they have them.
     |      
     |      See :py:meth:`~PIL.Image.Image.alpha_composite` if you want to
     |      combine images with respect to their alpha channels.
     |      
     |      :param im: Source image or pixel value (integer or tuple).
     |      :param box: An optional 4-tuple giving the region to paste into.
     |         If a 2-tuple is used instead, it's treated as the upper left
     |         corner.  If omitted or None, the source is pasted into the
     |         upper left corner.
     |      
     |         If an image is given as the second argument and there is no
     |         third, the box defaults to (0, 0), and the second argument
     |         is interpreted as a mask image.
     |      :param mask: An optional mask image.
     |  
     |  point(self, lut, mode=None)
     |      Maps this image through a lookup table or function.
     |      
     |      :param lut: A lookup table, containing 256 (or 65536 if
     |         self.mode=="I" and mode == "L") values per band in the
     |         image.  A function can be used instead, it should take a
     |         single argument. The function is called once for each
     |         possible pixel value, and the resulting table is applied to
     |         all bands of the image.
     |      
     |         It may also be an :py:class:`~PIL.Image.ImagePointHandler`
     |         object::
     |      
     |             class Example(Image.ImagePointHandler):
     |               def point(self, data):
     |                 # Return result
     |      :param mode: Output mode (default is same as input).  In the
     |         current version, this can only be used if the source image
     |         has mode "L" or "P", and the output has mode "1" or the
     |         source image mode is "I" and the output mode is "L".
     |      :returns: An :py:class:`~PIL.Image.Image` object.
     |  
     |  putalpha(self, alpha)
     |      Adds or replaces the alpha layer in this image.  If the image
     |      does not have an alpha layer, it's converted to "LA" or "RGBA".
     |      The new layer must be either "L" or "1".
     |      
     |      :param alpha: The new alpha layer.  This can either be an "L" or "1"
     |         image having the same size as this image, or an integer or
     |         other color value.
     |  
     |  putdata(self, data, scale=1.0, offset=0.0)
     |      Copies pixel data to this image.  This method copies data from a
     |      sequence object into the image, starting at the upper left
     |      corner (0, 0), and continuing until either the image or the
     |      sequence ends.  The scale and offset values are used to adjust
     |      the sequence values: **pixel = value*scale + offset**.
     |      
     |      :param data: A sequence object.
     |      :param scale: An optional scale value.  The default is 1.0.
     |      :param offset: An optional offset value.  The default is 0.0.
     |  
     |  putpalette(self, data, rawmode='RGB')
     |      Attaches a palette to this image.  The image must be a "P", "PA", "L"
     |      or "LA" image.
     |      
     |      The palette sequence must contain either 768 integer values, or 1024
     |      integer values if alpha is included. Each group of values represents
     |      the red, green, blue (and alpha if included) values for the
     |      corresponding pixel index. Instead of an integer sequence, you can use
     |      an 8-bit string.
     |      
     |      :param data: A palette sequence (either a list or a string).
     |      :param rawmode: The raw mode of the palette.
     |  
     |  putpixel(self, xy, value)
     |      Modifies the pixel at the given position. The color is given as
     |      a single numerical value for single-band images, and a tuple for
     |      multi-band images. In addition to this, RGB and RGBA tuples are
     |      accepted for P images.
     |      
     |      Note that this method is relatively slow.  For more extensive changes,
     |      use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw`
     |      module instead.
     |      
     |      See:
     |      
     |      * :py:meth:`~PIL.Image.Image.paste`
     |      * :py:meth:`~PIL.Image.Image.putdata`
     |      * :py:mod:`~PIL.ImageDraw`
     |      
     |      :param xy: The pixel coordinate, given as (x, y). See
     |         :ref:`coordinate-system`.
     |      :param value: The pixel value.
     |  
     |  quantize(self, colors=256, method=None, kmeans=0, palette=None, dither=1)
     |      Convert the image to 'P' mode with the specified number
     |      of colors.
     |      
     |      :param colors: The desired number of colors, <= 256
     |      :param method: :data:`MEDIANCUT` (median cut),
     |                     :data:`MAXCOVERAGE` (maximum coverage),
     |                     :data:`FASTOCTREE` (fast octree),
     |                     :data:`LIBIMAGEQUANT` (libimagequant; check support using
     |                     :py:func:`PIL.features.check_feature`
     |                     with ``feature="libimagequant"``).
     |      :param kmeans: Integer
     |      :param palette: Quantize to the palette of given
     |                      :py:class:`PIL.Image.Image`.
     |      :param dither: Dithering method, used when converting from
     |         mode "RGB" to "P" or from "RGB" or "L" to "1".
     |         Available methods are :data:`NONE` or :data:`FLOYDSTEINBERG` (default).
     |         Default: 1 (legacy setting)
     |      :returns: A new image
     |  
     |  reduce(self, factor, box=None)
     |      Returns a copy of the image reduced ``factor`` times.
     |      If the size of the image is not dividable by ``factor``,
     |      the resulting size will be rounded up.
     |      
     |      :param factor: A greater than 0 integer or tuple of two integers
     |         for width and height separately.
     |      :param box: An optional 4-tuple of ints providing
     |         the source image region to be reduced.
     |         The values must be within ``(0, 0, width, height)`` rectangle.
     |         If omitted or ``None``, the entire source is used.
     |  
     |  remap_palette(self, dest_map, source_palette=None)
     |      Rewrites the image to reorder the palette.
     |      
     |      :param dest_map: A list of indexes into the original palette.
     |         e.g. ``[1,0]`` would swap a two item palette, and ``list(range(256))``
     |         is the identity transform.
     |      :param source_palette: Bytes or None.
     |      :returns:  An :py:class:`~PIL.Image.Image` object.
     |  
     |  resize(self, size, resample=3, box=None, reducing_gap=None)
     |      Returns a resized copy of this image.
     |      
     |      :param size: The requested size in pixels, as a 2-tuple:
     |         (width, height).
     |      :param resample: An optional resampling filter.  This can be
     |         one of :py:data:`PIL.Image.NEAREST`, :py:data:`PIL.Image.BOX`,
     |         :py:data:`PIL.Image.BILINEAR`, :py:data:`PIL.Image.HAMMING`,
     |         :py:data:`PIL.Image.BICUBIC` or :py:data:`PIL.Image.LANCZOS`.
     |         Default filter is :py:data:`PIL.Image.BICUBIC`.
     |         If the image has mode "1" or "P", it is
     |         always set to :py:data:`PIL.Image.NEAREST`.
     |         See: :ref:`concept-filters`.
     |      :param box: An optional 4-tuple of floats providing
     |         the source image region to be scaled.
     |         The values must be within (0, 0, width, height) rectangle.
     |         If omitted or None, the entire source is used.
     |      :param reducing_gap: Apply optimization by resizing the image
     |         in two steps. First, reducing the image by integer times
     |         using :py:meth:`~PIL.Image.Image.reduce`.
     |         Second, resizing using regular resampling. The last step
     |         changes size no less than by ``reducing_gap`` times.
     |         ``reducing_gap`` may be None (no first step is performed)
     |         or should be greater than 1.0. The bigger ``reducing_gap``,
     |         the closer the result to the fair resampling.
     |         The smaller ``reducing_gap``, the faster resizing.
     |         With ``reducing_gap`` greater or equal to 3.0, the result is
     |         indistinguishable from fair resampling in most cases.
     |         The default value is None (no optimization).
     |      :returns: An :py:class:`~PIL.Image.Image` object.
     |  
     |  rotate(self, angle, resample=0, expand=0, center=None, translate=None, fillcolor=None)
     |      Returns a rotated copy of this image.  This method returns a
     |      copy of this image, rotated the given number of degrees counter
     |      clockwise around its centre.
     |      
     |      :param angle: In degrees counter clockwise.
     |      :param resample: An optional resampling filter.  This can be
     |         one of :py:data:`PIL.Image.NEAREST` (use nearest neighbour),
     |         :py:data:`PIL.Image.BILINEAR` (linear interpolation in a 2x2
     |         environment), or :py:data:`PIL.Image.BICUBIC`
     |         (cubic spline interpolation in a 4x4 environment).
     |         If omitted, or if the image has mode "1" or "P", it is
     |         set to :py:data:`PIL.Image.NEAREST`. See :ref:`concept-filters`.
     |      :param expand: Optional expansion flag.  If true, expands the output
     |         image to make it large enough to hold the entire rotated image.
     |         If false or omitted, make the output image the same size as the
     |         input image.  Note that the expand flag assumes rotation around
     |         the center and no translation.
     |      :param center: Optional center of rotation (a 2-tuple).  Origin is
     |         the upper left corner.  Default is the center of the image.
     |      :param translate: An optional post-rotate translation (a 2-tuple).
     |      :param fillcolor: An optional color for area outside the rotated image.
     |      :returns: An :py:class:`~PIL.Image.Image` object.
     |  
     |  save(self, fp, format=None, **params)
     |      Saves this image under the given filename.  If no format is
     |      specified, the format to use is determined from the filename
     |      extension, if possible.
     |      
     |      Keyword options can be used to provide additional instructions
     |      to the writer. If a writer doesn't recognise an option, it is
     |      silently ignored. The available options are described in the
     |      :doc:`image format documentation
     |      <../handbook/image-file-formats>` for each writer.
     |      
     |      You can use a file object instead of a filename. In this case,
     |      you must always specify the format. The file object must
     |      implement the ``seek``, ``tell``, and ``write``
     |      methods, and be opened in binary mode.
     |      
     |      :param fp: A filename (string), pathlib.Path object or file object.
     |      :param format: Optional format override.  If omitted, the
     |         format to use is determined from the filename extension.
     |         If a file object was used instead of a filename, this
     |         parameter should always be used.
     |      :param params: Extra parameters to the image writer.
     |      :returns: None
     |      :exception ValueError: If the output format could not be determined
     |         from the file name.  Use the format option to solve this.
     |      :exception OSError: If the file could not be written.  The file
     |         may have been created, and may contain partial data.
     |  
     |  seek(self, frame)
     |      Seeks to the given frame in this sequence file. If you seek
     |      beyond the end of the sequence, the method raises an
     |      ``EOFError`` exception. When a sequence file is opened, the
     |      library automatically seeks to frame 0.
     |      
     |      See :py:meth:`~PIL.Image.Image.tell`.
     |      
     |      If defined, :attr:`~PIL.Image.Image.n_frames` refers to the
     |      number of available frames.
     |      
     |      :param frame: Frame number, starting at 0.
     |      :exception EOFError: If the call attempts to seek beyond the end
     |          of the sequence.
     |  
     |  show(self, title=None, command=None)
     |      Displays this image. This method is mainly intended for debugging purposes.
     |      
     |      This method calls :py:func:`PIL.ImageShow.show` internally. You can use
     |      :py:func:`PIL.ImageShow.register` to override its default behaviour.
     |      
     |      The image is first saved to a temporary file. By default, it will be in
     |      PNG format.
     |      
     |      On Unix, the image is then opened using the **display**, **eog** or
     |      **xv** utility, depending on which one can be found.
     |      
     |      On macOS, the image is opened with the native Preview application.
     |      
     |      On Windows, the image is opened with the standard PNG display utility.
     |      
     |      :param title: Optional title to use for the image window, where possible.
     |  
     |  split(self)
     |      Split this image into individual bands. This method returns a
     |      tuple of individual image bands from an image. For example,
     |      splitting an "RGB" image creates three new images each
     |      containing a copy of one of the original bands (red, green,
     |      blue).
     |      
     |      If you need only one band, :py:meth:`~PIL.Image.Image.getchannel`
     |      method can be more convenient and faster.
     |      
     |      :returns: A tuple containing bands.
     |  
     |  tell(self)
     |      Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`.
     |      
     |      If defined, :attr:`~PIL.Image.Image.n_frames` refers to the
     |      number of available frames.
     |      
     |      :returns: Frame number, starting with 0.
     |  
     |  thumbnail(self, size, resample=3, reducing_gap=2.0)
     |      Make this image into a thumbnail.  This method modifies the
     |      image to contain a thumbnail version of itself, no larger than
     |      the given size.  This method calculates an appropriate thumbnail
     |      size to preserve the aspect of the image, calls the
     |      :py:meth:`~PIL.Image.Image.draft` method to configure the file reader
     |      (where applicable), and finally resizes the image.
     |      
     |      Note that this function modifies the :py:class:`~PIL.Image.Image`
     |      object in place.  If you need to use the full resolution image as well,
     |      apply this method to a :py:meth:`~PIL.Image.Image.copy` of the original
     |      image.
     |      
     |      :param size: Requested size.
     |      :param resample: Optional resampling filter.  This can be one
     |         of :py:data:`PIL.Image.NEAREST`, :py:data:`PIL.Image.BOX`,
     |         :py:data:`PIL.Image.BILINEAR`, :py:data:`PIL.Image.HAMMING`,
     |         :py:data:`PIL.Image.BICUBIC` or :py:data:`PIL.Image.LANCZOS`.
     |         If omitted, it defaults to :py:data:`PIL.Image.BICUBIC`.
     |         (was :py:data:`PIL.Image.NEAREST` prior to version 2.5.0).
     |         See: :ref:`concept-filters`.
     |      :param reducing_gap: Apply optimization by resizing the image
     |         in two steps. First, reducing the image by integer times
     |         using :py:meth:`~PIL.Image.Image.reduce` or
     |         :py:meth:`~PIL.Image.Image.draft` for JPEG images.
     |         Second, resizing using regular resampling. The last step
     |         changes size no less than by ``reducing_gap`` times.
     |         ``reducing_gap`` may be None (no first step is performed)
     |         or should be greater than 1.0. The bigger ``reducing_gap``,
     |         the closer the result to the fair resampling.
     |         The smaller ``reducing_gap``, the faster resizing.
     |         With ``reducing_gap`` greater or equal to 3.0, the result is
     |         indistinguishable from fair resampling in most cases.
     |         The default value is 2.0 (very close to fair resampling
     |         while still being faster in many cases).
     |      :returns: None
     |  
     |  tobitmap(self, name='image')
     |      Returns the image converted to an X11 bitmap.
     |      
     |      .. note:: This method only works for mode "1" images.
     |      
     |      :param name: The name prefix to use for the bitmap variables.
     |      :returns: A string containing an X11 bitmap.
     |      :raises ValueError: If the mode is not "1"
     |  
     |  tobytes(self, encoder_name='raw', *args)
     |      Return image as a bytes object.
     |      
     |      .. warning::
     |      
     |          This method returns the raw image data from the internal
     |          storage.  For compressed image data (e.g. PNG, JPEG) use
     |          :meth:`~.save`, with a BytesIO parameter for in-memory
     |          data.
     |      
     |      :param encoder_name: What encoder to use.  The default is to
     |                           use the standard "raw" encoder.
     |      :param args: Extra arguments to the encoder.
     |      :returns: A :py:class:`bytes` object.
     |  
     |  toqimage(self)
     |      Returns a QImage copy of this image
     |  
     |  toqpixmap(self)
     |      Returns a QPixmap copy of this image
     |  
     |  transform(self, size, method, data=None, resample=0, fill=1, fillcolor=None)
     |      Transforms this image.  This method creates a new image with the
     |      given size, and the same mode as the original, and copies data
     |      to the new image using the given transform.
     |      
     |      :param size: The output size.
     |      :param method: The transformation method.  This is one of
     |        :py:data:`PIL.Image.EXTENT` (cut out a rectangular subregion),
     |        :py:data:`PIL.Image.AFFINE` (affine transform),
     |        :py:data:`PIL.Image.PERSPECTIVE` (perspective transform),
     |        :py:data:`PIL.Image.QUAD` (map a quadrilateral to a rectangle), or
     |        :py:data:`PIL.Image.MESH` (map a number of source quadrilaterals
     |        in one operation).
     |      
     |        It may also be an :py:class:`~PIL.Image.ImageTransformHandler`
     |        object::
     |      
     |          class Example(Image.ImageTransformHandler):
     |              def transform(self, size, data, resample, fill=1):
     |                  # Return result
     |      
     |        It may also be an object with a ``method.getdata`` method
     |        that returns a tuple supplying new ``method`` and ``data`` values::
     |      
     |          class Example:
     |              def getdata(self):
     |                  method = Image.EXTENT
     |                  data = (0, 0, 100, 100)
     |                  return method, data
     |      :param data: Extra data to the transformation method.
     |      :param resample: Optional resampling filter.  It can be one of
     |         :py:data:`PIL.Image.NEAREST` (use nearest neighbour),
     |         :py:data:`PIL.Image.BILINEAR` (linear interpolation in a 2x2
     |         environment), or :py:data:`PIL.Image.BICUBIC` (cubic spline
     |         interpolation in a 4x4 environment). If omitted, or if the image
     |         has mode "1" or "P", it is set to :py:data:`PIL.Image.NEAREST`.
     |         See: :ref:`concept-filters`.
     |      :param fill: If ``method`` is an
     |        :py:class:`~PIL.Image.ImageTransformHandler` object, this is one of
     |        the arguments passed to it. Otherwise, it is unused.
     |      :param fillcolor: Optional fill color for the area outside the
     |         transform in the output image.
     |      :returns: An :py:class:`~PIL.Image.Image` object.
     |  
     |  transpose(self, method)
     |      Transpose image (flip or rotate in 90 degree steps)
     |      
     |      :param method: One of :py:data:`PIL.Image.FLIP_LEFT_RIGHT`,
     |        :py:data:`PIL.Image.FLIP_TOP_BOTTOM`, :py:data:`PIL.Image.ROTATE_90`,
     |        :py:data:`PIL.Image.ROTATE_180`, :py:data:`PIL.Image.ROTATE_270`,
     |        :py:data:`PIL.Image.TRANSPOSE` or :py:data:`PIL.Image.TRANSVERSE`.
     |      :returns: Returns a flipped or rotated copy of this image.
     |  
     |  verify(self)
     |      Verifies the contents of a file. For data read from a file, this
     |      method attempts to determine if the file is broken, without
     |      actually decoding the image data.  If this method finds any
     |      problems, it raises suitable exceptions.  If you need to load
     |      the image after using this method, you must reopen the image
     |      file.
     |  
     |  ----------------------------------------------------------------------
     |  Readonly properties defined here:
     |  
     |  __array_interface__
     |  
     |  height
     |  
     |  size
     |  
     |  width
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors defined here:
     |  
     |  __dict__
     |      dictionary for instance variables (if defined)
     |  
     |  __weakref__
     |      list of weak references to the object (if defined)
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes defined here:
     |  
     |  __hash__ = None
     |  
     |  format = None
     |  
     |  format_description = None
    
    class ImagePointHandler(builtins.object)
     |  Used as a mixin by point transforms
     |  (for use with :py:meth:`~PIL.Image.Image.point`)
     |  
     |  Data descriptors defined here:
     |  
     |  __dict__
     |      dictionary for instance variables (if defined)
     |  
     |  __weakref__
     |      list of weak references to the object (if defined)
    
    class ImageTransformHandler(builtins.object)
     |  Used as a mixin by geometry transforms
     |  (for use with :py:meth:`~PIL.Image.Image.transform`)
     |  
     |  Data descriptors defined here:
     |  
     |  __dict__
     |      dictionary for instance variables (if defined)
     |  
     |  __weakref__
     |      list of weak references to the object (if defined)

FUNCTIONS
    __getattr__(name)
    
    alpha_composite(im1, im2)
        Alpha composite im2 over im1.
        
        :param im1: The first image. Must have mode RGBA.
        :param im2: The second image.  Must have mode RGBA, and the same size as
           the first image.
        :returns: An :py:class:`~PIL.Image.Image` object.
    
    blend(im1, im2, alpha)
        Creates a new image by interpolating between two input images, using
        a constant alpha.::
        
            out = image1 * (1.0 - alpha) + image2 * alpha
        
        :param im1: The first image.
        :param im2: The second image.  Must have the same mode and size as
           the first image.
        :param alpha: The interpolation alpha factor.  If alpha is 0.0, a
           copy of the first image is returned. If alpha is 1.0, a copy of
           the second image is returned. There are no restrictions on the
           alpha value. If necessary, the result is clipped to fit into
           the allowed output range.
        :returns: An :py:class:`~PIL.Image.Image` object.
    
    coerce_e(value)
    
    composite(image1, image2, mask)
        Create composite image by blending images using a transparency mask.
        
        :param image1: The first image.
        :param image2: The second image.  Must have the same mode and
           size as the first image.
        :param mask: A mask image.  This image can have mode
           "1", "L", or "RGBA", and must have the same size as the
           other two images.
    
    effect_mandelbrot(size, extent, quality)
        Generate a Mandelbrot set covering the given extent.
        
        :param size: The requested size in pixels, as a 2-tuple:
           (width, height).
        :param extent: The extent to cover, as a 4-tuple:
           (x0, y0, x1, y2).
        :param quality: Quality.
    
    effect_noise(size, sigma)
        Generate Gaussian noise centered around 128.
        
        :param size: The requested size in pixels, as a 2-tuple:
           (width, height).
        :param sigma: Standard deviation of noise.
    
    eval(image, *args)
        Applies the function (which should take one argument) to each pixel
        in the given image. If the image has more than one band, the same
        function is applied to each band. Note that the function is
        evaluated once for each possible pixel value, so you cannot use
        random components or other generators.
        
        :param image: The input image.
        :param function: A function object, taking one integer argument.
        :returns: An :py:class:`~PIL.Image.Image` object.
    
    fromarray(obj, mode=None)
        Creates an image memory from an object exporting the array interface
        (using the buffer protocol).
        
        If ``obj`` is not contiguous, then the ``tobytes`` method is called
        and :py:func:`~PIL.Image.frombuffer` is used.
        
        If you have an image in NumPy::
        
          from PIL import Image
          import numpy as np
          im = Image.open('hopper.jpg')
          a = np.asarray(im)
        
        Then this can be used to convert it to a Pillow image::
        
          im = Image.fromarray(a)
        
        :param obj: Object with array interface
        :param mode: Mode to use (will be determined from type if None)
          See: :ref:`concept-modes`.
        :returns: An image object.
        
        .. versionadded:: 1.1.6
    
    frombuffer(mode, size, data, decoder_name='raw', *args)
        Creates an image memory referencing pixel data in a byte buffer.
        
        This function is similar to :py:func:`~PIL.Image.frombytes`, but uses data
        in the byte buffer, where possible.  This means that changes to the
        original buffer object are reflected in this image).  Not all modes can
        share memory; supported modes include "L", "RGBX", "RGBA", and "CMYK".
        
        Note that this function decodes pixel data only, not entire images.
        If you have an entire image file in a string, wrap it in a
        :py:class:`~io.BytesIO` object, and use :py:func:`~PIL.Image.open` to load it.
        
        In the current version, the default parameters used for the "raw" decoder
        differs from that used for :py:func:`~PIL.Image.frombytes`.  This is a
        bug, and will probably be fixed in a future release.  The current release
        issues a warning if you do this; to disable the warning, you should provide
        the full set of parameters.  See below for details.
        
        :param mode: The image mode. See: :ref:`concept-modes`.
        :param size: The image size.
        :param data: A bytes or other buffer object containing raw
            data for the given mode.
        :param decoder_name: What decoder to use.
        :param args: Additional parameters for the given decoder.  For the
            default encoder ("raw"), it's recommended that you provide the
            full set of parameters::
        
                frombuffer(mode, size, data, "raw", mode, 0, 1)
        
        :returns: An :py:class:`~PIL.Image.Image` object.
        
        .. versionadded:: 1.1.4
    
    frombytes(mode, size, data, decoder_name='raw', *args)
        Creates a copy of an image memory from pixel data in a buffer.
        
        In its simplest form, this function takes three arguments
        (mode, size, and unpacked pixel data).
        
        You can also use any pixel decoder supported by PIL.  For more
        information on available decoders, see the section
        :ref:`Writing Your Own File Decoder <file-decoders>`.
        
        Note that this function decodes pixel data only, not entire images.
        If you have an entire image in a string, wrap it in a
        :py:class:`~io.BytesIO` object, and use :py:func:`~PIL.Image.open` to load
        it.
        
        :param mode: The image mode. See: :ref:`concept-modes`.
        :param size: The image size.
        :param data: A byte buffer containing raw data for the given mode.
        :param decoder_name: What decoder to use.
        :param args: Additional parameters for the given decoder.
        :returns: An :py:class:`~PIL.Image.Image` object.
    
    fromqimage(im)
        Creates an image instance from a QImage image
    
    fromqpixmap(im)
        Creates an image instance from a QPixmap image
    
    getmodebandnames(mode)
        Gets a list of individual band names.  Given a mode, this function returns
        a tuple containing the names of individual bands (use
        :py:method:`~PIL.Image.getmodetype` to get the mode used to store each
        individual band.
        
        :param mode: Input mode.
        :returns: A tuple containing band names.  The length of the tuple
            gives the number of bands in an image of the given mode.
        :exception KeyError: If the input mode was not a standard mode.
    
    getmodebands(mode)
        Gets the number of individual bands for this mode.
        
        :param mode: Input mode.
        :returns: The number of bands in this mode.
        :exception KeyError: If the input mode was not a standard mode.
    
    getmodebase(mode)
        Gets the "base" mode for given mode.  This function returns "L" for
        images that contain grayscale data, and "RGB" for images that
        contain color data.
        
        :param mode: Input mode.
        :returns: "L" or "RGB".
        :exception KeyError: If the input mode was not a standard mode.
    
    getmodetype(mode)
        Gets the storage type mode.  Given a mode, this function returns a
        single-layer mode suitable for storing individual bands.
        
        :param mode: Input mode.
        :returns: "L", "I", or "F".
        :exception KeyError: If the input mode was not a standard mode.
    
    init()
        Explicitly initializes the Python Imaging Library. This function
        loads all available file format drivers.
    
    isImageType(t)
        Checks if an object is an image object.
        
        .. warning::
        
           This function is for internal use only.
        
        :param t: object to check if it's an image
        :returns: True if the object is an image
    
    linear_gradient(mode)
        Generate 256x256 linear gradient from black to white, top to bottom.
        
        :param mode: Input mode.
    
    merge(mode, bands)
        Merge a set of single band images into a new multiband image.
        
        :param mode: The mode to use for the output image. See:
            :ref:`concept-modes`.
        :param bands: A sequence containing one single-band image for
            each band in the output image.  All bands must have the
            same size.
        :returns: An :py:class:`~PIL.Image.Image` object.
    
    new(mode, size, color=0)
        Creates a new image with the given mode and size.
        
        :param mode: The mode to use for the new image. See:
           :ref:`concept-modes`.
        :param size: A 2-tuple, containing (width, height) in pixels.
        :param color: What color to use for the image.  Default is black.
           If given, this should be a single integer or floating point value
           for single-band modes, and a tuple for multi-band modes (one value
           per band).  When creating RGB images, you can also use color
           strings as supported by the ImageColor module.  If the color is
           None, the image is not initialised.
        :returns: An :py:class:`~PIL.Image.Image` object.
    
    open(fp, mode='r', formats=None)
        Opens and identifies the given image file.
        
        This is a lazy operation; this function identifies the file, but
        the file remains open and the actual image data is not read from
        the file until you try to process the data (or call the
        :py:meth:`~PIL.Image.Image.load` method).  See
        :py:func:`~PIL.Image.new`. See :ref:`file-handling`.
        
        :param fp: A filename (string), pathlib.Path object or a file object.
           The file object must implement ``file.read``,
           ``file.seek``, and ``file.tell`` methods,
           and be opened in binary mode.
        :param mode: The mode.  If given, this argument must be "r".
        :param formats: A list or tuple of formats to attempt to load the file in.
           This can be used to restrict the set of formats checked.
           Pass ``None`` to try all supported formats. You can print the set of
           available formats by running ``python -m PIL`` or using
           the :py:func:`PIL.features.pilinfo` function.
        :returns: An :py:class:`~PIL.Image.Image` object.
        :exception FileNotFoundError: If the file cannot be found.
        :exception PIL.UnidentifiedImageError: If the image cannot be opened and
           identified.
        :exception ValueError: If the ``mode`` is not "r", or if a ``StringIO``
           instance is used for ``fp``.
        :exception TypeError: If ``formats`` is not ``None``, a list or a tuple.
    
    preinit()
        Explicitly load standard file format drivers.
    
    radial_gradient(mode)
        Generate 256x256 radial gradient from black to white, centre to edge.
        
        :param mode: Input mode.
    
    register_decoder(name, decoder)
        Registers an image decoder.  This function should not be
        used in application code.
        
        :param name: The name of the decoder
        :param decoder: A callable(mode, args) that returns an
                        ImageFile.PyDecoder object
        
        .. versionadded:: 4.1.0
    
    register_encoder(name, encoder)
        Registers an image encoder.  This function should not be
        used in application code.
        
        :param name: The name of the encoder
        :param encoder: A callable(mode, args) that returns an
                        ImageFile.PyEncoder object
        
        .. versionadded:: 4.1.0
    
    register_extension(id, extension)
        Registers an image extension.  This function should not be
        used in application code.
        
        :param id: An image format identifier.
        :param extension: An extension used for this format.
    
    register_extensions(id, extensions)
        Registers image extensions.  This function should not be
        used in application code.
        
        :param id: An image format identifier.
        :param extensions: A list of extensions used for this format.
    
    register_mime(id, mimetype)
        Registers an image MIME type.  This function should not be used
        in application code.
        
        :param id: An image format identifier.
        :param mimetype: The image MIME type for this format.
    
    register_open(id, factory, accept=None)
        Register an image file plugin.  This function should not be used
        in application code.
        
        :param id: An image format identifier.
        :param factory: An image file factory method.
        :param accept: An optional function that can be used to quickly
           reject images having another format.
    
    register_save(id, driver)
        Registers an image save function.  This function should not be
        used in application code.
        
        :param id: An image format identifier.
        :param driver: A function to save images in this format.
    
    register_save_all(id, driver)
        Registers an image function to save all the frames
        of a multiframe format.  This function should not be
        used in application code.
        
        :param id: An image format identifier.
        :param driver: A function to save images in this format.
    
    registered_extensions()
        Returns a dictionary containing all file extensions belonging
        to registered plugins

DATA
    ADAPTIVE = 1
    AFFINE = 0
    ANTIALIAS = 1
    BICUBIC = 3
    BILINEAR = 2
    BOX = 4
    CONTAINER = 2
    CUBIC = 3
    DECODERS = {}
    DEFAULT_STRATEGY = 0
    ENCODERS = {}
    EXTENSION = {'.apng': 'PNG', '.bmp': 'BMP', '.dib': 'DIB', '.gif': 'GI...
    EXTENT = 1
    FASTOCTREE = 2
    FILTERED = 1
    FIXED = 4
    FLIP_LEFT_RIGHT = 0
    FLIP_TOP_BOTTOM = 1
    FLOYDSTEINBERG = 3
    HAMMING = 5
    HUFFMAN_ONLY = 2
    ID = ['BMP', 'DIB', 'GIF', 'TIFF', 'JPEG', 'PPM', 'PNG']
    LANCZOS = 1
    LIBIMAGEQUANT = 3
    LINEAR = 2
    MAXCOVERAGE = 1
    MAX_IMAGE_PIXELS = 89478485
    MEDIANCUT = 0
    MESH = 4
    MIME = {'BMP': 'image/bmp', 'DIB': 'image/bmp', 'GIF': 'image/gif', 'J...
    MODES = ['1', 'CMYK', 'F', 'HSV', 'I', 'L', 'LAB', 'P', 'RGB', 'RGBA',...
    NEAREST = 0
    NONE = 0
    NORMAL = 0
    OPEN = {'BMP': (<class 'PIL.BmpImagePlugin.BmpImageFile'>, <function _...
    ORDERED = 1
    PERSPECTIVE = 2
    QUAD = 3
    RASTERIZE = 2
    RLE = 3
    ROTATE_180 = 3
    ROTATE_270 = 4
    ROTATE_90 = 2
    SAVE = {'BMP': <function _save>, 'DIB': <function _dib_save>, 'GIF': <...
    SAVE_ALL = {'GIF': <function _save_all>, 'PNG': <function _save_all>, ...
    SEQUENCE = 1
    TRANSPOSE = 5
    TRANSVERSE = 6
    USE_CFFI_ACCESS = False
    WEB = 0
    logger = <Logger PIL.Image (WARNING)>

VERSION
    8.1.2

FILE
    d:\python\lib\site-packages\pillow-8.1.2-py3.8-win-amd64.egg\pil\image.py

 更多详细介绍见博主[章子雎Kevin]的文章: 《Python图像处理PIL各模块详细介绍

  • 15
    点赞
  • 53
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hann Yang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值