Basic tutorial on using Pillow to process images in Python programming, pythonpillow

Source: Internet
Author: User

Basic tutorial on using Pillow to process images in Python programming, pythonpillow

Install
If you are new to Pillow, let's take a 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. After installation, you can install and manage various libraries (pip document) in the command line ).

$ 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 to download and obtain Pillow:

$ pip install pillow

(3) The command line prompts an error during installation: "error: command 'clang 'failed with exit status 1 ". Check the Internet and find that the Command Line Tool needs to be updated through Xcode. Open the Xcode> Preferences> Downloads-Components tab. Why? Command Line Tools is missing. Check again and find that Xcode 5 and above now need to be installed using the command line:

$ xcode-select —install

The system prompts you to install the command line tool. Click Install.

Then pip install pillow.

Pip freeze command to check the installed Python package. Pillow is already there.

Now, let's start the tutorial ~

Image class
The most important class in Pillow is Image, which exists in modules with the same name. You can instantiate an image by reading an image from a file, processing other images, or directly creating an image.

Use the open function in the Image module to open an Image:

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

If the file is successfully opened, an Image object is returned. You can use the object attribute to check the file content.

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

The format attribute defines the image format. If the image is not opened from a file, the attribute value is None; the size attribute is a tuple, indicating the width and height of the image (in pixels ); the mode attribute indicates the image mode. The common mode is: L, RGB, true color, and CMYK.

If the file cannot be opened, an IOError is thrown.

When an Image object exists, you can use various methods of the Image class to process and operate the Image, such as displaying the Image:

>>> im.show()

Ps: The show () method in the standard version is not very efficient because it saves the image as a temporary file and then displays it using xv. If xv is not installed, the function cannot even work. However, this method is very convenient for debugging and test. (The default image Viewer should be called in windows)

Read/write Images
The Pillow Library supports many image formats. Directly use the open () function in the Image module to read images without processing the Image format first. The Pillow library automatically determines the format based on the file.

The save () function in the Image module can save images. Unless you specify the file format, the file name extension is used to specify the file format.

Convert image to 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 image format. If the file name does not provide a standard image format, the second parameter is required.

Create a thumbnail

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, unless necessary, Pillow does not decode or raster data. When you open a file, Pillow determines the file format, size, mode, and other data through the file header. The remaining data is not processed Until necessary.

This means that the file is opened very quickly and has nothing to do with the file size and compression format. The following program is used to quickly determine the image attributes:

Determine image attributes

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 Images
The Image class contains methods to operate more Image regions. For example, the crop () method can extract a child rectangle from an image.

Copy a sub-image from the image

Box = im. copy () # directly copy the image box = (100,100,400,400) region = im. crop (box)

The region is determined by 4-tuple. The information in this tuple is (left, upper, right, lower ). The system origin (0, 0) on the left side of Pillow is the upper left corner of the image. The number unit in the coordinate is pixel, so the size of the image captured in the preceding example is 300*300 pixels ^ 2.

Process the subgraph and paste it back to the source image.

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

When the subgraph paste is returned to the source image, the region of the subgraph must match the region of the given box. The region cannot exceed the source image. The mode of the source image and region does not need to be matched, and Pillow will automatically process it.

Another example

Rolling an imagedef roll (image, delta): "Roll an image sideways" image = image. copy () # copy image 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

Separate and merge Channels

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

For single-channel images, split () returns the image itself. To process a single-channel image, you must first convert the image to RGB.

Geometric Transformation
The Image classes include the resize (), rotate (), transpose (), and transform () methods for geometric transformation.

Simple geometric Transformation

Out = im. resize (128,128) out = im. rotate (45) # clockwise Angle

Replacement 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 transpose () and elephant rotate.

More common image transformation methods can use transform ()

Mode Conversion
Convert () method

Mode Conversion

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

Image Enhancement
Filter
The ImageFilter module contains many predefined enhancement filters, which are used by the filter () method.

Apply filters

from PIL import ImageFilterout = im.filter(ImageFilter.DETAIL) 

Pixel Processing
The point () method processes the pixels in the image (such as the contrast operation) using a function or a query table ).

Pixel Transform

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

The above method can use a simple expression for image processing. By combining point () and paste (), it can also selectively process a certain area of the image.

Process 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)

Note the statement for creating a mask:

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

This sentence can be expressed in the following sentence

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

If expression is false, the return value of expression is 0 (because the and statement can obtain the result); otherwise, 255 is returned. (Mask parameter usage: when it is 0, the current value is retained. 255 is the value that uses paste, and the intermediate value is used for the transparency effect)

Advanced Image Enhancement
To enhance other advanced images, use the ImageEnhance module. Once an Image object exists, the ImageEnhance object can be applied to set it quickly. You can use the following methods to adjust the contrast, brightness, color balance, and sharpness.

Image Enhancement

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

Dynamic Graph

Pillow supports some dynamic image formats, such as FLI/FLC, GIF, and some other formats in the experiment phase. A tiff file can also contain several images.

When reading a dynamic graph, PIL automatically reads the first frame of the dynamic graph. You 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.

The current version only allows seek to the next frame. You must open the file again before returning it.

Alternatively, you can use the following iterator class

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 images through 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 (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()

More image reading methods
The open () function of the Image module is enough for daily use. The parameter of this function can also be a file object.

Read from string

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

Read from the tar file

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

Draft Mode
The draft () method allows you to convert an image to a specified mode and size as much as possible (probably not equal to a given parameter) without reading the file content, this is very effective when generating thumbnails (when the speed requirement is higher than the quality requirement ).

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.