Enhance image with Python PIL

petercour - Jul 15 '19 - - Dev Community

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
Enter fullscreen mode Exit fullscreen mode

To load and show an image:

image = Image.open('lena.jpg')
image.show()
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

Related links:

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player