Basic tutorials for using pillow to process images in Python programming

Source: Internet
Author: User
Installation
Just contact Pillow Friends First look at the installation method of pillow, here we take the Mac OS environment as an example:
(1), use PIP to install the Python library. Pip is a Python package management tool that installs/manages various libraries (PIP documents) directly from the command line once installed.

$ wget http://pypi.python.org/packages/source/p/pip/pip-0.7.2.tar.gz$ tar xzf pip-0.7.2.tar.gz$ cd pip-0.7.2$ python setup.py Install

(2), use pip download to get Pillow:

$ pip Install Pillow

(3), the command line during installation error prompt: "Error:command ' clang ' failed with exit status 1". Check online and find you need to update Command line Tool via Xcode. Then open the Xcode->preferences->downloads-components tab. Hey? There's no Command line Tools. Again, it is found that Xcode 5 and above now need to be installed with the command line:

$ xcode-select-install

The system will pop up the prompt to install the command line tool and click Install.

At this point, pip Install Pillow, the installation was successful.

The PIP freeze command looks at the Python packages that have been installed, and Pillow has lain there.

Okay, here's the tutorial to get started ~

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 (.) 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.splitex T (infile) outfile = f + ". jpg" if infile! = outfile:  try:   image.open (infile). Save (outfile)  except ioerror:< C5/>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 = (+, +) for infile in sys.argv[1:]: Outfi Le = 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 (i Nfile) 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 = (+, +, +) 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 imagedef roll (image, Delta): "Roll an image sideways" image = Image.copy () #复制图像 xsize, ysize = image.size delt A = 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 ((+, +)) out = Im.rotate (45) # Clockwise Angle indication

Displacement image

out = Im.transpose (image.flip_left_right) off = 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, c Select regions where red is less than 100mask = Source[r].point (lambda i:i < 255) # process the green bandout = Source[g].point (Lambda i:i * 0.7) # paste th E processed band back, but only where red is < 100source[g].paste (out, None, mask) # Build a new multiband Imageim = Im Age.merge (Im.mode, source)

Notice the statement that created the mask:

Mask = Source[r].point (lambda i:i < 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.tel L () +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 postscriptfrom 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 (at + dpi) Ps.ima GE (box, IM, page) ps.rectangle (box) # Draw centered Titleps.setfont ("Helveticanarrow-bold", $) W, h, B = ps.textsize (title) Ps.text ((4*72-W/2, 1*72-h), title) Ps.end_document ()

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)
  • 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.