Profile

Click to view full profile
Hi, I'm Veerapat Sriarunrungrueang, an expert in technology field, especially full stack web development and performance testing.This is my coding diary. I usually develop and keep code snippets or some tricks, and update to this diary when I have time. Nowadays, I've been giving counsel to many well-known firms in Thailand.
view more...

Tuesday, August 27, 2013

Convert a color image to a greyscale image using Python Imaging Library

Recently, I have a chance to do some image processing tasks because of my lacking in term of using application like GIMP. I just want to do very easy task to convert a color image to a greyscale image because my printer cannot do color printing and set for black and white. I know it is very easy task with we can use some programs to do it instead of Image Processing program like GIMP or Photoshop. For me, I can do some Python programming then decide to write a small program to convert a color image to grey scale image within 5 minutes (from start writing a code and done processing).

In Python, we can use a lightweight library but easy and powerful to use to do Image Processing tasks that is Python Imaging Library. Before do converting task, we need to know some basis about Image Processing first.

The first thing that we should know is the color mode. In Image Processing there are many color modes which each mode is appropriate for some kind of tasks such as binary image (just black or white like a picture in Game Boy), 8-bit black and white (greyscale image), RGB (3x8-bit), etc. for more details can look at http://effbot.org/imagingbook/concepts.htm.

Okay, we have just known the image color system in Python Imaging Library. To convert a color image (usually RGB image) to greyscale image, it is not difficult because Python Imaging Library already provide the function to convert image mode. The code to convert has shown below:
from PIL import Image 
input_filename = 'input.png'
output_filename = 'output.png'
image_file = Image.open(input_filename)
# L refers to 8-bit pixels, black and white in Python Imaging Library
image_file = image_file.convert('L')
image_file.save(output_filename)
The step is load an image to the buffer then convert an image mode and save to another image file.
It's not hard but quite fun if we can play more interesting features in Python Imaging Library. With this code, we can convert an image within a sec :)

Example (Asuna from SAO):
Before
After
Reference: The Python Imaging Library Handbook