Paras Sharma - Blog

Image Processing in Python using PIL

29 May 2017 • Paras Sharma

Image Processing mainly deals with processing digital images, performing a mathematical operation on image data to enhance, transform them. Image processing is widely used in the most field of science today. It is used in medical science (CT Scan, MRI), Satellite Imaging, Microscopic Imaging etc. Moreover, when you apply filters to your selfies on Instagram, the image goes through series of mathematical operation that changes color, contrast, the brightness of the image.

Image processing can be imagined as a workflow. The workflow begins with reading an image. The output is then processed using either low-level or high-level operation. Low-level operations operate on individual pixels, it includes filtering, morphology, thresholding etc. The high-level operation includes image understanding, pattern recognition etc. Once processed, the images are either written disk or visualized.

Through this post, I will give you an introduction of Image and various terminologies used in the field of imaging along with some code samples in Python to process image

Image and its terminologies:

A digital image is made up of pixels and it can be 2-D, 3-D or 4-D. A pixel is smallest element of an image and group of pixels with specific values make up an Image. Every pixel in an Image has a real number as its value, this is because practically it is easier to store int value than float value.

image pixel

Bit Depth

A pixel range of given image format is determined by its bit depth. The range is [0, 2bitdepth-1]. For example, an 8-Bit image will have a range of [0, 255]. An image with higher bit depth needs more storage in disk and memory. Most of the common format like PNG, JPEG etc. use 8-Bit for storage and only have positive values. A tiff microscope image has a bit depth of 16-Bit has 5-Channels, thus total bit-depth of 80.

Pixel and Voxel

As told earlier Pixels make up an image, the term Pixel is used for the 2-D image but in Medical or Microscopic image formats like DICOM, nifti there is Voxel which represents value (Volume) in 3-D Space.

Image Histogram

Those who use image editing tools like photoshop, lightroom etc. might be familiar with this histogram.

image histogram

It is basically graphical depiction of the distribution of pixel value in an image.

X-Axis: Value of pixel. Y-Axis: Frequency of pixel.

Types of Image Format:
  • JPEG: Joint Photographic Experts Group (.jpg or .jpeg)
  • PNG: Portable Network Graphics
  • TIFF: Tagged image file Format
  • DICOM: Digital Image and Communication in Medicine

Image Processing in Python using PIL

Image data is generally stored as mathematical matrix. So in general, a 2d image of size 640x640 is stored in a matrix of the same size. Similarly 3-D image is also stored in 3-D Matrix. We will python language to perform some image processing using PIL (Python Imaging Library).

Installing PIL:

$ pip install pillow

Reading and Viewing an Image:

from PIL import Image

img ="aventador.jpg")

Output: img aventa

Getting size of an Image:


#=> (640, 480) i.e width and height in px

Saving an image:"new_image", "PNG")  #saving image in PNG format.

Rotating an Image:

The image can be rotated by tranposing the matrix.

img_right = img.transpose(2)


img rotate

Converting image to gray-scale:

img_grey = img.convert("L")


img grey

Performing Operation on each pixle:

from PIL import Image

def apply_effect(img):
    width, height = img.size
    if img.mode != 'RGB':
        img = img.convert('RGB')
    pix = img.load()
    for w in range(width):
        for h in range(height):
            r, g, b = pix[w, h]
            pix[w, h] = tuple(map(lambda i: min(255, i),
                                  [abs(g - b + g + r) * r // 256,
                                   abs(b - g + b + r) * r // 256,
                                   abs(b - g + b + r) * r // 256]))
    return img

img  ="aventador.jpg")

img = apply_effect(img)


img effect

Using various filter in PIL:

There are predefined filters available in PIL.

from PIL import ImageFilter
from PIL import Image

img ="aventador.jpg")

#blur the image
blur = img.filter(ImageFilter.BLUR)

#enhance edges
edge = img.filter(ImageFilter.EDGE_ENHANCE)

#emboss image
edge_emboss = img.filter(ImageFilter.EMBOSS)

min_filter = img.filter(ImageFilter.MinFilter)

#view contour
countour_img = img.filter(ImageFilter.CONTOUR) 

Outputs: filter output

Enhancing contrast of an Image:

from PIL import ImageEnhance

contrast = ImageEnhance.Contrast(img)

contrast_img = contrast.enhance(2)


img contrast

These are some of the operation that you can apply on Images using PIL. There are lot of stuff that you can do with images, for more Information you can look at the Documentation of PIL. If you have any query, please ask it in the comments.