DEV Community

loading...
Cover image for Enhance image with Python PIL

Enhance image with Python PIL

petercour
・2 min read

Python can be used to play around with images. This is a lot more fun than text. In this article we'll use a simple jpg image. That jpg image will be manipulated.

Images can be enhanced with Python PIL. What does enhanced mean?
It means change in:

  • Brightness(image)
  • Color(image)
  • Contrast(image)
  • Sharpness(image)

As input image we'll take the famous Lena image. This is an image that's often used in image processing.

And so you code

Load the PIL module like this:

from PIL import Image
from PIL import ImageEnhance

To load and show an image:

image = Image.open('lena.jpg')
image.show()

The image 'lena.jpg' must be in the same directory as program. If it's not, write a path to the image in front of it.

Enhancement

Ok so now you know how to load the PIL module, load an image and show it. What about the magic?

There are different methods to enhance an image:

ImageEnhance.Brightness(image)
ImageEnhance.Color(image)
ImageEnhance.Contrast(image)
ImageEnhance.Sharpness(image)

The app below does all the magic. The method enhance() takes a parameter that you can play around with.

#!/usr/bin/python3
#-*- coding: UTF-8 -*-   

from PIL import Image
from PIL import ImageEnhance

image = Image.open('lena.jpg')
image.show()

enh_bri = ImageEnhance.Brightness(image)
brightness = 1.5
image_brightened = enh_bri.enhance(brightness)
image_brightened.show()

enh_col = ImageEnhance.Color(image)
color = 1.5
image_colored = enh_col.enhance(color)
image_colored.show()

enh_con = ImageEnhance.Contrast(image)
contrast = 1.5
image_contrasted = enh_con.enhance(contrast)
image_contrasted.show()

enh_sha = ImageEnhance.Sharpness(image)
sharpness = 3.0
image_sharped = enh_sha.enhance(sharpness)
image_sharped.show()

Related links:

Discussion (1)

Collapse
lizard profile image
Lizard • Edited

Maybe you could show the output from one of the enhancement methods for comparison. Nice post 👍🏽