Python Imaging Library PIL

Mise à jour: 25 juin 2009
Version: 1.0
Author: Jean-Louis Bicquelet-Salaün
Location: http://jlbicquelet.free.fr
Copyright: (c) 2009 Jean-Louis BICQUELET-SALAÜN

PIL Frequently-Asked Questions


FAQ Revised: Friday 26 June 2009 18:17:03


Table of Contents

1. generality
2. information
3. transformation
4. manipulation

1. generality

1.1. What is PIL ?
The Python Imaging Library (PIL) adds image processing capabilities to your Python interpreter. This library supports many file formats, and provides powerful image processing and graphics capabilities. Information can be found on that site.


2. information

2.1. How can I get the format and size of an image with PIL ?

Note the use of try / except in order to properly handle errors. Thereafter, the PIL examples go to the essentials. It would be good to manage the exceptions in this way.

from PIL import Image

file='cours.png'
try:
   im = Image.open(file)
   print file, im.format, "%dx%d" % im.size, im.mode
except IOError:
   pass

The display shows the following:

cours.png PNG 230x150 RGB


2.2. How can I view an image with PIL ?
from PIL import Image
import ImageFilter

im = Image.open('cours.png')
im.show()



3. transformation

3.1. How can I break down a color image into red, green, blue ?
import Image
img = Image.open("presentation.png")  #  Ouverture de l'image
r,g,b = img.split()  # Récupération des différentes composantes de l'image
r.save('r.jpg') ## Sauvegarde des différents images composantes
g.save('v.jpg')
b.save('b.jpg')

Example:



3.2. How can I convert the image using PIL?

The possible formats are :

JPEG
PNG
BMP

Example:

from PIL import Image

im = Image.open('cours.png')
im.save('cours.jpg', "JPEG")
im.save('cours.bmp', "BMP")

image JPEG BMP


3.3. How can I create a thumbnail with PIL?

Simply use the thumbnail function in the following way:

from PIL import Image

im = Image.open('aider.png')
im.thumbnail([128,128], Image.ANTIALIAS)
im.save('aider_small.png', "PNG")

or

from PIL import Image

size=128,128
im = Image.open('aider.png')
im.thumbnail(size, Image.ANTIALIAS)
im.save('aider_small.png', "PNG")

image thumbnail


3.4. How can I create thumbnails of all the images of a directory ?
from PIL import Image
import glob, os

size = 128, 128

for infile in glob.glob("*.jpg"):
    file, ext = os.path.splitext(infile)
    im = Image.open(infile)
    im.thumbnail(size, Image.ANTIALIAS)
    im.save(file + "_thumbnail.jpg", "JPEG")


3.5. How can I rotate an image ?

We use rotate followed by the rotation angle.

from PIL import Image

im = Image.open('explication.png')
out = im.rotate(45)
out.save('rotate.png')
image rotation


3.6. How to perform a geometric transformation of an image ?

We use transpose.

Il existe des flag pour indiquer les opérations:

FLIP_LEFT_RIGHT
FLIP_TOP_BOTTOM
ROTATE_90rotation de 90°
ROTATE_180rotation de 180°
ROTATE_270rotation de 270°

A transformation with ROTATE_90 option is equivalent to a rotation with the rotate function.

from PIL import Image

im = Image.open('explication.png')
out = im.rotate(45)
out.save('rotate.png')
out = im.transpose(Image.FLIP_LEFT_RIGHT)
out.save('flip.png')
image geometric transformation


3.7. How can I resize an image ?
from PIL import Image

im = Image.open('explication.png')
out = im.resize((100,120))
out.save('resize.png'
image result


3.8. How can I filter an image ?

The ImageFilter module can apply several filter. The url imagefilter describes what can be done. (min, max, médian, blur filters...).

from PIL import Image
import ImageFilter

im = Image.open('cours.png')
out = im.filter(ImageFilter.BLUR)
out.save('blur.jpg', "JPEG")
out2 = im.filter(ImageFilter.MinFilter)
out2.save('min.jpg', "JPEG")
out3 = im.filter(ImageFilter.MedianFilter)
out3.save('median.jpg', "JPEG")
image blur
min median



4. manipulation

4.1. How can I create an image with its symmetrical ?
The example of that boxing match is a perfect example of manipulation. It creates an image of double size, it generates an axial mirror image of the original image and copy all the parts into the new image.
from PIL import Image

im = Image.open('boxe.png')
w,h=im.size
box = (0, 0, w, h)
src = im.crop(box)
out = im.resize((w*2,h))
out.paste(src,(0,0,w,h))
src=im.transpose(Image.FLIP_LEFT_RIGHT)
out.paste(src,(w,0,2*w,h))
out.save('combat.png')
image result


4.2. How can I create an image with a given background color?
Give the size and color either by the name, either with RGB values..
from PIL import Image
import ImageDraw

im = Image.new("RGB", (400,200), "blue")
im = Image.new("RGB", (400,200), "#3FA03D")
draw = ImageDraw.Draw(im)
del draw
im.save("create.png", "PNG")
generated image


4.3. How can I draw an image ?
The information for drawing with PIL are here.
from PIL import Image
import ImageDraw

im = Image.new("RGB", (400,200), "lightgrey")
draw = ImageDraw.Draw(im)
draw.line((0, 0) + im.size, fill="red")
draw.rectangle(((100,100),(130,200)),fill="blue")
del draw
im.save("trace.png", "PNG")
generated image


4.4. How can I copy several images in an image?
from PIL import Image
import ImageDraw


im = Image.new("RGB", (500,400), "white")
draw = ImageDraw.Draw(im)
into = Image.open("explication.png")
w,h=into.size
im.paste(into, (0,0,w,h))
im.paste(into, (300,0,300+w,h))
im.paste(into, (200,200,200+w,200+h))
del draw
im.save("dessin.jpg", "JPEG")
image result


4.5. How can I write text in an image ?
#-*- coding:utf8 -*-
import sys
import Image
import ImageDraw
import ImageFont

txt = 'C\'est mon texte!'
txt2 = '??,??!'

font = ImageFont.truetype('verdanai.ttf',24)
font2 = ImageFont.truetype('simsun.ttc',24)
im = Image.new("RGBA",(300,200),(100,155,100))

draw = ImageDraw.Draw(im)

#draw.text( (0,50), u'??,??!', font=font)
draw.text( (0,50), unicode(txt,'UTF-8'), font=font)
draw.text( (0,100), unicode(txt2,'UTF-8'), font=font2)
del draw

im.save('font.png', "PNG")
generated image



Copyright (c) 2009 Jean-Louis BICQUELET

This list of questions and answers was generated by makefaq.