I’m still a newbie to Python and would like to learn Python Imaging Library(PIL) with some small project. After thinking awhile, I decided to take PIL a ride to convert image from Jpeg to Png, blur it and mask it with a semi opaque black layer.
Here’s how I do it:
#!/usr/bin/python import sys, os import Image import ImageFilter inputFile = sys.argv outputFile = os.path.splitext(inputFile) + ".png" im = Image.open(inputFile) im = im.filter(ImageFilter.BLUR) mask = Image.new((im.mode), (im.size)) out = Image.blend(im, mask, 0.3) out.save(outputFile)
save the code in a file called xxx.py which xxx is the filename of your choice. Image.open() opens a image as an object(im). You can apply a filter (blur) using Image.filter(ImageFilter.BLUR).
The Image.new() function takes 3 parameter which is the image mode, image size and colour. For example if you want to create a blue colour rectangular with size 400×300, use Image.new((“RGB”), (400,300), (0,0,255)). Please note that if you leave the colour parameter as empty, it will create a black (default) colour image.
The function Image.blend() blends the two images (first and second parameter). The 2 images must have the same size and mode. The 3rd parameter refers to percentage of blending. For instance, 0.0 refers to 100% im and 0% mask and so on.
The last line out.save(outputFile) saves the out image object as outputFile filename.
If you want to make this python file executable, in terminal, cd to the directory containing this python file and enter:
chmod +x xxx.py
So if you want to blur, mask and convert a Jpeg file called scene.jpg, just enter in terminal:
You will notice there is a image file called scene.png at the same directory. If you wonder how it looks like, here’s the before and after comparison.
Here it is, a simple introduction tutorial to PIL. Have fun 🙂
P/S: If you get error message like “no module Image found”, you need to install the PIL module, for example, in fedora, type in terminal sudo yum install python-imaging