Python Image processing library: Pillow Beginner's Tutorial

Source: Internet
Author: User
Tags image processing library

Python Image processing library: Pillow Beginner's Tutorial

2014-09-14 translation http://pillow.readthedocs.org/en/latest/handbook/tutorial.html

Pillow is from PIL, so import the library using import PIL

The relevant code for this article: Https://github.com/445141126/pillow_example

Image class

The most important class in pillow is the image, which exists in a module of the same name. It can be instantiated in several ways: by reading a picture from a file, by processing another image, or by creating a picture directly.

Open a picture using the open function in the image module:

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

If successful, returns an Image object that can be used to check the contents of the file through object properties

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

The Format property defines how the image is formatted, and if the image is not open from a file, the property value is a tuple that represents the width and height (in pixels) of the image, and the mode attribute is the pattern for the image, the commonly used mode is: L is a grayscale, RGB is true color, none;size CMYK is a pre-press image.

If the file cannot be opened, a IOError exception is thrown.

When you have an image object, you can manipulate and manipulate the image using various methods of the image class, such as displaying a picture:

>>> im.show()

PS: The standard version of the show () method is not very efficient because it first saves the image as a temporary file and then displays it using XV. If XV is not installed, the function does not even work. However, this method is very convenient for debug and test. (The default picture viewer should be called in Windows to open)

Read and write pictures

The Pillow Library supports a considerable number of image formats. Use the open () function directly in the image module to read a picture without first having to work with the format of the picture, and the pillow library automatically determines the format based on the file.

The Save () function in the image module saves the picture, unless you specify a file format, and the extension in the file name is used to specify the file format.

Image into JPG format

from __future__ import print_functionimport os, sysfrom PIL import Imagefor 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)

The second parameter of the Save function can be used to specify the picture format, and the second parameter is required if a standard image format is not given in the file name.

Create a thumbnail image

from __future__ import print_functionimport os, sysfrom PIL import Imagesize = (128, 128)for infile in sys.argv[1:]:    outfile = os.path.splitext(infile)[0] + ".thumbnail"    if infile != outfile:        try:            im = Image.open(infile)            im.thumbnail(size)            im.save(outfile, "JPEG")        except IOError:            print("cannot create thumbnail for", infile)

It must be noted that pillow does not decode or raster data unless it is necessary. When you open a file, pillow determines the file format, size, mode and other data through the file header, and the remaining data is processed until needed.

This means that opening files is very fast, regardless of file size and compression format. The following program is used to quickly determine picture properties:

Determine picture properties

from __future__ import print_functionimport sysfrom PIL import Imagefor infile in sys.argv[1:]:    try:        with Image.open(infile) as im:            print(infile, im.format, "%dx%d" % im.size, im.mode)    except IOError:        pass
Crop, paste, and merge pictures

The image class contains methods that also manipulate the picture area more. such as the crop () method to extract a sub-rectangle from the picture

Copy a sub-image from a picture

box = im.copy() #直接复制图像box = (100, 100, 400, 400)region = im.crop(box)

The area is determined by 4-tuple and the information in the tuple is (left, upper, right, lower). Pillow The origin of the Left system (0,0) is the upper-left corner of the picture. The number units in coordinates are pixels, so the image size captured in the example above is 300*300 pixels ^2.

Working with sub-graphs, pasting back to original

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

When you paste the sub-map back to the original, the region of the sub-graph must match the region of the given box. The region cannot exceed the original image. The original and region mode does not need to be matched, and pillow is automatically processed.

Another example

Rolling an image

def roll(image, delta):    "Roll an image sideways"    image = image.copy() #复制图像    xsize, ysize = image.size    delta = delta % xsize    if delta == 0: return image    part1 = image.crop((0, 0, delta, ysize))    part2 = image.crop((delta, 0, xsize, ysize))    image.paste(part2, (0, 0, xsize-delta, ysize))    image.paste(part1, (xsize-delta, 0, xsize, ysize))    return image

Separating and merging channels

r, g, b = im.split()im = Image.merge("RGB", (b, g, r))

For a single-channel picture, split () returns the image itself. In order to process a single-channel picture, you must first turn the picture into RGB.

Geometric transformations

The Image class has resize (), rotate (), and transpose (), transform () Methods for geometric transformations.

Simple geometric transformations

out = im.resize((128, 128))out = im.rotate(45) # 顺时针角度表示

Displacement image

out = im.transpose(Image.FLIP_LEFT_RIGHT)out = im.transpose(Image.FLIP_TOP_BOTTOM)out = im.transpose(Image.ROTATE_90)out = im.transpose(Image.ROTATE_180)out = im.transpose(Image.ROTATE_270)

There is no performance difference between the transpose () and the Elephant's rotate ().

The more general image transformation method can be used transform ()

Mode conversion

Convert () method

Mode conversion

im = Image.open(‘lena.ppm‘).convert(‘L‘)
Image Enhancement Filter

The ImageFilter module contains a number of pre-defined enhanced filters, using the filter () method

Application Filters

Pixel Point Processing

The point () method processes pixels in an image (such as contrast operations) through a function or query table.

Pixel-point transformation

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

The above method can be used for image processing with simple expressions, and the combination of point () and paste () can also selectively process an area of a picture.

Handling individual channels

# split the image into individual bandssource = im.split()R, G, B = 0, 1, 2# select regions where red is less than 100mask = source[R].point(lambda i: i < 100 and 255)# process the green bandout = source[G].point(lambda i: i * 0.7)# paste the processed band back, but only where red was < 100source[G].paste(out, None, mask)# build a new multiband imageim = Image.merge(im.mode, source)

Notice the statement that created the mask:

mask = source[R].point(lambda i: i < 100 and 255)

The sentence can be expressed in the following sentence

imout = im.point(lambda i: expression and 255)

If expression is false, the value of return expression is 0 (because the and statement is already able to produce the result), otherwise 255 is returned. (Mask parameter usage: When 0 o'clock, the current value is preserved, 255 is the value entered using paste, and the middle is used for the transparency effect)

Advanced Image Enhancement

For other advanced image enhancements, you should use the Imageenhance module. Once you have an image object, you can quickly set it up by applying the Imageenhance object. You can use the following methods to adjust contrast, brightness, color balance, and sharpness.

Image enhancement

from PIL import ImageEnhanceenh = ImageEnhance.Contrast(im)enh.enhance(1.3).show("30% more contrast")

Dynamic graphs

Pillow supports a number of dynamic picture formats such as Fli/flc,gif and others in the experimental phase. A TIFF file can also contain several frames of images.

When reading a dynamic graph, PiL automatically reads the first frame of the dynamic graph, and can use the seek and tell methods to read different frames.

from PIL import Imageim = Image.open("animation.gif")im.seek(1) # skip to the second frametry:    while 1:        im.seek(im.tell()+1)        # do something to imexcept EOFError:    pass # end of sequence

When the last frame is read, pillow throws an Eoferror exception.

The current version only allows seek to the next frame. You must reopen the file in order to rewind it.

Alternatively, you can use the following iterator classes

Dynamic graph Iterator Class

class ImageSequence:    def __init__(self, im):        self.im = im    def __getitem__(self, ix):        try:            if ix:                self.im.seek(ix)            return self.im        except EOFError:            raise IndexError # end of sequencefor frame in ImageSequence(im):    # ...do something to frame...
Postscript Printing

Pillow allows you to add images, text, and graphics to a picture via PostScript printer.

Drawing Postscript

from PIL import Imagefrom PIL import PSDrawim = Image.open("lena.ppm")title = "lena"box = (1*72, 2*72, 7*72, 10*72) # in pointsps = PSDraw.PSDraw() # default is sys.stdoutps.begin_document(title)# draw the image (75 dpi)ps.image(box, im, 75)ps.rectangle(box)# draw centered titleps.setfont("HelveticaNarrow-Bold", 36)w, h, b = ps.textsize(title)ps.text((4*72-w/2, 1*72-h), title)ps.end_document()

Ps:textsize can't use it, who knows?

More ways to read pictures

Previously, the open () function of the image module was sufficient for daily use. The parameter of the function can also be a file object.

Read from string

import StringIOim = Image.open(StringIO.StringIO(buffer))

Read from tar file

from PIL import TarIOfp = TarIO.TarIO("Imaging.tar", "Imaging/test/lena.ppm")im = Image.open(fp)
Draft mode

The draft () method allows the picture to be converted to a given pattern and size without reading the contents of the file as much as possible (probably not exactly equal to a given parameter), which is very effective when generating thumbnails (higher speed requirements than high quality).

Draft mode

from __future__ import print_functionim = Image.open(file)print("original =", im.mode, im.size)im.draft("L", (100, 100))print("draft =", im.mode, im.size)
Reference documents
    1. Image module in the PIL

Python Image processing library: Pillow Beginner's Tutorial

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.