PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. It was developed by Fredrik Lundh and several other contributors. Pillow is the friendly PIL fork and an easy to use library developed by Alex Clark and other contributors. We’ll be working with Pillow.
ImageDraw Module¶ The ImageDraw module provide simple 2D graphics for Image objects. You can use this module to create new images, annotate or retouch existing images, and to generate graphics on the fly for web use. For a more advanced drawing library for PIL, see the aggdraw module.
Installation:
- Linux: On linux terminal type the following:Installing pip via terminal:
- Windows:Download the appropriate Pillow package according to your python version. Make sure to download according to the python version you have.
We’ll be working with the Image Module here which provides a class of the same name and provides a lot of functions to work on our images.To import the Image module, our code should begin with the following line:
Operations with Images:
- Open a particular image from a path:
# On successful execution of this statement,
# an object of Image type is returned and stored in img variable)
try
:
except
IOError:
# Use the above statement within try block, as it can
# or image cannot be opened.
- Retrieve size of image: The instances of Image class that are created have many attributes, one of its useful attribute is size.
with Image.
open
(filename) as image:
#Image.size gives a 2-tuple and the width, height can be obtained
Some other attributes are: Image.width, Image.height, Image.format, Image.info etc. - Save changes in image: To save any changes that you have made to the image file, we need to give path as well as image format.
# format is optional, if no format is specified,
- Rotating an Image: The image rotation needs angle as parameter to get the image rotated.
try
:
img
=
Image.
open
(
'picture.jpg'
)
#Angle given
img.save(
'rotated_picture.jpg'
)
pass
if
__name__
=
=
'__main__'
:
Note: There is an optional expand flag available as one of the argument of the rotate method, which if set true, expands the output image to make it large enough to hold the full rotated image.
As seen in the above code snippet, I have used a relative path where my image is located in the same directory as my python code file, an absolute path can be used as well. - Cropping an Image: Image.crop(box) takes a 4-tuple (left, upper, right, lower) pixel coordinate, and returns a rectangular region from the used image.
try
:
img
=
Image.
open
(
'picture.jpg'
)
img
=
img.crop(area)
#Saved in the same relative location
pass
if
__name__
=
=
'__main__'
:
- Resizing an Image: Image.resize(size)- Here size is provided as a 2-tuple width and height.
try
:
img
=
Image.
open
(
'picture.jpg'
)
img.save(
'resized_picture.jpg'
)
pass
if
__name__
=
=
'__main__'
:
- Pasting an image on another image: The second argument can be a 2-tuple (specifying the top left corner), or a 4-tuple (left, upper, right, lower) – in this case the size of pasted image must match the size of this box region, or None which is equivalent to (0, 0).
try
:
#Image on which we want to paste
#Image which we want to paste
img.paste(img2, (
50
,
50
))
#Saved in the same relative location
pass
if
__name__
=
=
'__main__'
:
##An additional argument for an optional image mask image is also available.
- Getting a Histogram of an Image: This will return a histogram of the image as a list of pixel counts, one for each pixel in the image. (A histogram of an image is a graphical representation of the tonal distribution in a digital image. It contains what all the brightness values contained in an image are. It plots the number of pixels for each brightness value. It helps in doing the exposure settings.)
from PIL import Imagetry
:
img
=
Image.
open
(
'picture.jpg'
)
#Getting histogram of image
pass
if
__name__
=
=
'__main__'
:
- Transposing an Image: This feature gives us the mirror image of an image
try
:
img
=
Image.
open
(
'picture.jpg'
)
#transposing image
transposed_img
=
img.transpose(Image.FLIP_LEFT_RIGHT)
#Save transposed image
except
IOError:
main()
- Split an image into individual bands: Splitting an image in RGB mode, creates three new images each containing a copy of the original individual bands.
try
:
img
=
Image.
open
(
'picture.jpg'
)
#splitting the image
except
IOError:
main()
- tobitmap: Converting an image to an X11 bitmap (A plain text binary image format). It returns a string containing an X11 bitmap, it can only be used for mode “1” images, i.e. 1 bit pixel black and white images.
from PIL import Imagetry
:
img
=
Image.
open
(
'picture.jpg'
)
print
img.tobitmap()
print
type
(img.tobitmap())
pass
if
__name__
=
=
'__main__'
:
- Creating a thumbnail: This method creates a thumbnail of the image that is opened. It does not return a new image object, it makes in-place modification to the currently opened image object itself. If you do not want to change the original image object, create a copy and then apply this method. This method also evaluates the appropriate to maintain the aspect ratio of the image according to the size passed.
from PIL import Imagetry
:
img
=
Image.
open
(
'picture.jpg'
)
#In-place modification
except
IOError:
main()
This article is contributed by Mohit Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Recommended Posts:
![Pil image open Pil image open](/uploads/1/2/5/7/125756209/682737621.jpg)
Pillow tutorial shows how to use Pillow in Python to work with images. The sourcesare available at the author's Github repository.
Pillow
Pillow is a Python Imaging Library (PIL), which adds support for opening, manipulating, and saving images. The current version identifies and reads a large number of formats. Write support is intentionally restricted to the most commonly used interchange and presentation formats.
Showing image
In the first example we read an image file and show it in an external program.
show_image.py
The program reads a JPG image and displays it in an external application.
From the PIL module, we include the
Image
class.The
Image.open()
method reads the image file. Pillow can read over 30 different file formats.The
show()
method is mainly intended for debugging purposes.It saves the image into a temporary file and displays it in external program.This could be ImageMagic on Linux or Paint on Windows.Basic image information with Pillow
Pillow allows us to get some basic information about the image.
The example prints basic information about the image with Pillow.
We print the image format, its size and mode.
This is the output of the program.
Blurring image
The
ImageFilter
module contains definitions for a pre-defined set of filters, which can be used with the filter()
method.blur_image.py
The program loads an image, creates a blurred image from the original image, and saves the new image on disk.
We import the
Image
and ImageFilter
modules.![Pil Pil](/uploads/1/2/5/7/125756209/381380142.jpg)
We apply the
ImageFilter.BLUR
on the original image;the operation returns a new modified image.With the
save()
method, we save the blurred image ondisk.Converting image with Pillow
With the
save()
method, we can convert an image toa different format. The program reads a JPG image and converts it into PNG format.
The second parameter of the
save()
method specifies the imageformat.GrayScale image
With the
Image.convert()
method, we can producea black and white image.grayscale.py
The program reads an image and transforms it into agrayscale image.
The first parameter of the
convert()
method is the mode;the 'L' mode is black and white.Cropping image with Pillow
The
Image.crop()
crops the image.The program crops an image. The cropped image is saved on disk.
The
crop()
method takes a 4-tuple defining the left, upper, right, and lower pixel coordinates.Rotating image with Pillow
The
Image.rotate()
returns a rotated copy of the image. rotate_image.py
The program rotates an image by 180 degrees and saves the newlycreated image on disk.
Displaying image in Tkinter
The following program displays an image in a Tkinterprogram.
The program displays an image in the
Label
widgetof the Tkinter toolkit.The
ImageTk
is a Tkinter-compatible photo image. It can be used everywhere Tkinter expects an image object. We create a photo image.
The photoimage is given to the
image
parameter of the label widget. In order not to be garbage collected, the image reference must bestored.
The size of the window fits the image size.
Reading image from URL
The next example reads an image from URL.
read_from_url.py
The example reads an image from the URL and saves it ondisk.
We use the
requests
library to download the image.We read the image as raw data.
Image
is created from the response object.The image is saved.
Drawing to Pillow image
Pillow has some basic 2D graphics capabilities.
ImageDraw
module provides simple 2D graphics for Image
objects. We can create new images, annotate or retouch existing images, and generate graphics on the fly for web use.The example creates a new image and draws a blue rectangleon the image.
A new
Image
is created. The image mode is 'RGBA'. Its size is 200x200 and the background is white.From the image we create the
ImageDraw
object. Nowwe can perform some drawing operations on the image.With the
rectangle()
method, we draw a blue rectangleon the image.Creating watermark with Pillow
The following example creates a watermark.
watermark.py
We use the
ImageDraw
module to create watermark.We create an Arial font of 18 size.
The watermark is created with the
text()
method.The default colour of the text is white. We use the created font.In this tutorial, we have worked with the Python Pillow library.
You might also be interested in the following related tutorials: Tkinter tutorial,Matplotlib tutorial,Python arrow tutorial,PyQt5 tutorial, andPython tutorial.