python 学习之 Pillow库

官方文档:https://pillow.readthedocs.io/en/3.3.x/handbook/tutorial.html#using-the-image-class

The most important class in the Python Imaging Library is the Image class, defined in the module with the same name. You can create instances of this class in several ways; either by loading images from files, processing other images, or creating images from scratch.(Image类是Pillow库中最重要的类,你可以通过两种方式得到这种类的实例:加载一个图片,或者从图片的一部分创造一个图片)

To load an image from a file, use the open() function in the Image module:(你可以通过以下方式载入一个图片)

>>> from PIL import Image
>>> im = Image.open("lena.ppm")

If successful, this function returns an Image object. You can now use instance attributes to examine the file contents:(如果载入成功,你可以调用类的以下成员变量)

>>> from __future__ import print_function
>>> print(im.format, im.size, im.mode)
PPM (512, 512) RGB

The format attribute identifies the source of an image. If the image was not read from a file, it is set to None. The size attribute is a 2-tuple containing width and height (in pixels). The mode attribute defines the number and names of the bands in the image, and also the pixel type and depth. Common modes are “L” (luminance) for greyscale images, “RGB” for true color images, and “CMYK” for pre-press images.(如果这个函数不是从文件中读取的,那么它的format就是none。size是一个2元元组,通过像素来表明了图像大小,mode说明了图像的色彩格式)

If the file cannot be opened, an IOError exception is raised.(如果不能正常打开,会抛出一个IOErroe异常)

Once you have an instance of the Image class, you can use the methods defined by this class to process and manipulate the image. For example, let’s display the image we just loaded:(注意,想要成功使用im.show()方法,需要xy这个软件的支持,经个人测试在mac中会调用默认的预览来实现show操作,本文末尾还有说明

>>> im.show()

Reading and writing images(读写图片)

The Python Imaging Library supports a wide variety of image file formats. To read files from disk, use the open() function in the Image module. You don’t have to know the file format to open a file. The library automatically determines the format based on the contents of the file.(Image的open方法无需制定图片格式,会自动识别图片格式)

To save a file, use the save() method of the Image class. When saving files, the name becomes important. Unless you specify the format, the library uses the filename extension to discover which file storage format to use.(你可以通过save方法来储存一张图片)

Convert files to JPEG(转换格式)

from __future__ import print_function
import os, sys
from PIL import Image

for infile in sys.argv[1:]:
    f, e = os.path.splitext(infile)
    outfile = f + ".jpg"
    if infile != outfile:
        try:
            Image.open(infile).save(outfile)
        except IOError:
            print("cannot convert", infile)
通过改变save方法的文件名后缀,你可以改变图片的格式


Create JPEG thumbnails(创建JPEG缓存)

It is important to note that the library doesn’t decode or load the raster data unless it really has to. When you open a file, the file header is read to determine the file format and extract things like mode, size, and other properties required to decode the file, but the rest of the file is not processed until later.(我们需要注意到,这个库只有在需要的时候才会解码整张图片。当我们调用open方法打开了一张图片,它在读取完图片的header获取了图片格式、图片色彩模式、图片的尺寸之后就停止解码)

This means that opening an image file is a fast operation, which is independent of the file size and compression type. 这意味着,打开图片这项工作并不会耗时很长)

Cutting, pasting, and merging images(切割、复制和合并图片)

The Image class contains methods allowing you to manipulate regions within an image. To extract a sub-rectangle from an image, use the crop() method.(Image类包含一些允许你操作图片区域的方法,你可以通过crop方法在图片上切割一个小矩形)

Copying a subrectangle from an image(从图片上复制一个小矩形)

box = (100, 100, 400, 400)
region = im.crop(box)

The region is defined by a 4-tuple, where coordinates are (left, upper, right, lower). The Python Imaging Library uses a coordinate system with (0, 0) in the upper left corner. Also note that coordinates refer to positions between the pixels, so the region in the above example is exactly 300x300 pixels.(这个区域是通过一个4个元素的元组定义的。Image库使用一个以左上角为(0,0)的坐标系统,上面的例子中的region其实包含了一个300*300像素的区域)

The region could now be processed in a certain manner and pasted back.

Processing a subrectangle, and pasting it back

region = region.transpose(Image.ROTATE_180)
im.paste(region, box)

When pasting regions back, the size of the region must match the given region exactly. In addition, the region cannot extend outside the image. However, the modes of the original image and the region do not need to match. If they don’t, the region is automatically converted before being pasted (see the section on Color transforms below for details).

(当把这个区域复制回去的时候,region的size必须和给定的图片的size完全相同。此外,这个region不能伸展到图片外面。但是,如果给定图片的色彩格式和region的色彩格式不同,这是没有关系的,因为pillow会帮助我们完成这个转换)


This is because cropping is a lazy operation. If load() was not called, then the crop operation would not be performed until the images were used in the paste commands. (如果我们多次使用crop,最好先调用Im.load,因为crop这个方法只有在需要复制图片的时候才完全加载我们切割下来的区域,这可能导致我们切割的图片已经被修改)

图片复制的方法:

Image.paste(imbox=Nonemask=NonePastes 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)). 

If a 4-tuple is given, the size of the pasted image must match the size of the region.(paste方法:把一个其他图片复制到调用这个方法的图片上

后面的box是制定复制的区域,如果是个4元素的元组,那么im打大小必须和4元素元组制定的大小相同


通过复制实现部分区域打马

from PIL import Image
from PIL import ImageFilter
im = Image.open('4.png')
im.show()
box = (0,0,100,100)
region = im.crop(box)
region = region.filter(ImageFilter.BLUR)
im.paste(region,box)
im.show()



Geometrical transforms(几何转换)

The PIL.Image.Image class contains methods to resize() and rotate() an image. The former takes a tuple giving the new size, the latter the angle in degrees counter-clockwise.(Image类包含了resize(改变图片尺寸)和rotate(旋转)方法)

(resize的参数是一个包含2个元素的元组,rotate方法需要过一个角度,rotate会按照这个角度顺时针旋转)

Simple geometry transforms(简单几何转换)

out = im.resize((128, 128))
out = im.rotate(45) # degrees counter-clockwise

To rotate the image in 90 degree steps, you can either use the rotate() method or the transpose()method. The latter can also be used to flip an image around its horizontal or vertical axis.

Color transforms(改变色彩模式)

The Python Imaging Library allows you to convert images between different pixel representations using the convert() method.(Image库同时允许你在不同的色彩模式之间转换)

Converting between modes

im = Image.open("lena.ppm").convert("L")

The library supports transformations between each supported mode and the “L” and “RGB” modes. To convert between other modes, you may have to use an intermediate image (typically an “RGB” image).(在L(灰度模式),和RGB(三原色模式)之间可以直接转换,其它格式之间的转换可能需要借助中间格式(通常这种中间格式是RGB模式))

Image enhancement(图片增强)

The Python Imaging Library provides a number of methods and modules that can be used to enhance images.(Image库提供了很多种图片增强方式)

Filters(滤镜)

The ImageFilter module contains a number of pre-defined enhancement filters that can be used with the filter() method.(在ImageFilter库中定义了很多常用滤镜看,你可以通过filter方法调用)

Applying filters(使用滤镜)
from PIL import ImageFilter
out = im.filter(ImageFilter.DETAIL)
(注意这些操作没有改变原来的im,都只是创建了一些副本)

Filters(常用滤镜)

The current version of the library provides the following set of predefined image enhancement filters:

  • BLUR(模糊)
  • CONTOUR
  • DETAIL
  • EDGE_ENHANCE
  • EDGE_ENHANCE_MORE
  • EMBOSS
  • FIND_EDGES
  • SMOOTH
  • SMOOTH_MORE
  • SHARPEN

Point Operations(点操作)

The point() method can be used to translate the pixel values of an image (e.g. image contrast manipulation). In most cases, a function object expecting one argument can be passed to this method. Each pixel is processed according to that function:(我们都知道,图片是由一个一个像素点构成的,而这个像素点的编码格式和色彩模式有关。而point方法能够直接改变每个像素点的值。通常情况下,我们会传入一个函数,这样我们可以通过这个函数处理每个像素点)

什么?你不知道像素点和色彩模式,可以戳下面这个链接http://www.16xx8.com/photoshop/xinshoujiaocheng/rumen/

官方文档中point这个方法的介绍

Image. point ( lutmode=None )

Maps this image through a lookup table or function.(可这是通过一个map函数处理每个像素点)

Parameters:
  • lut – A lookup table, containing 256 (or 65336 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.
  • 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 Image object.

Applying point transforms
# multiply each pixel by 1.2
out = im.point(lambda i: i * 1.2)

Using the above technique, you can quickly apply any simple expression to an image. You can also combine the point() and paste() methods to selectively modify an image:

(官方文档的例子是通过一个无名函数来使得每个像素点i变成i*1.2。你可以通过point和paste方法结合改变图片的部分区域)


Processing individual bands(单独改变一个颜色通道)
# split the image into individual bands
source = im.split()

R, G, B = 0, 1, 2

# select regions where red is less than 100
mask = source[R].point(lambda i: i < 100 and 255)

# process the green band
out = source[G].point(lambda i: i * 0.7)

# paste the processed band back, but only where red was < 100
source[G].paste(out, None, mask)

# build a new multiband image
im = Image.merge(im.mode, source)
(上文的例子通过im.spilt方法分割了3个通道)

Image sequences(打开动画(一连串Image))

The Python Imaging Library contains some basic support for image sequences (also called animation formats). Supported sequence formats include FLI/FLC, GIF, and a few experimental formats. TIFF files can also contain more than one frame.(Image库包含一些对动画格式的基本支持,支持的格式包括FLI/FLC/GIF)

When you open a sequence file, PIL automatically loads the first frame in the sequence. You can use the seek and tell methods to move between different frames:(当你打开一个动画的时候,PIL自动加载动画的第一帧,你可以使用seek和tell方法来在不同帧之间移动)


其他一些常用方法

Image. show ( title=Nonecommand=None )

Displays this image. This method is mainly intended for debugging purposes.

On Unix platforms, this method saves the image to a temporary PPM file, and calls either the xvutility or the display utility, depending on which one can be found.

OnOS X, this method saves the image to a temporary BMP file, and opens it with the native Preview application.

OnWindows, it saves the image to a temporary BMP file, and uses the standard BMP display utility to show it (usually Paint).

Parameters:
  • title – Optional title to use for the image window, where possible.
  • command – command used to show the image

Image. getpixel ( xy )

Returns the pixel value at a given position.

Parameters: xy – The coordinate, given as (x, y).
Returns: The pixel value. If the image is a multi-layer image, this method returns a tuple.
(获得一个像素点),注意这个参数应该是一个2个元素的元组,类似(255,5)
对于RGB格式,这个返回参数是一个四元元组(类似(255, 255, 255, 255))
Image. putpixel ( xyvalue )

(直接改变一个像素点,第一个参数是坐标,第二个参数是像素点的值)

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.

Note that this method is relatively slow. For more extensive changes, use paste() or theImageDraw module instead.

See:

Parameters:
  • xy – The pixel coordinate, given as (x, y).
  • value – The pixel value.
Image. close ( )

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 theload() method

Image. resize ( sizeresample=0 )

Returns a resized copy of this image.(关于后面一个参数的解释:Image.NEAREST使用四舍五入,BILINER使用线性逼近,默认是NEAREST)

Parameters:
  • size – The requested size in pixels, as a 2-tuple: (width, height).
  • resample – An optional resampling filter. This can be one of PIL.Image.NEAREST (use nearest neighbour), PIL.Image.BILINEAR (linear interpolation), PIL.Image.BICUBIC(cubic spline interpolation), or PIL.Image.LANCZOS (a high-quality downsampling filter). If omitted, or if the image has mode “1” or “P”, it is set PIL.Image.NEAREST.
Returns:

An Image object.


Image. getdata ( 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()).(这个方法返回的是一串PIL内置对象,想要把它转换成Python内置的list,请使用list(im.getdata()))

Parameters: 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).(可以通过制定R,G,B制定单独返回一个通道)
Returns: A sequence-like object.

Image. putdata ( datascale=1.0offset=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. (这个data参数可以用python内置的列表)

Parameters:
  • data – A sequence object.
  • scale – An optional scale value. The default is 1.0.
  • offset – An optional offset value. The default is 0.0.

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值