As part of a program through my University and CoderdojoWA I’ve been asked to oversee a project relating to image manipulation in Python using the Python Image Library. While I wasn’t the one to write the guide, I have been asked to test and confirm I understand it well enough to be able to teach the content this coming February.
Base Code + Image
The following code was written with PIL (Python Imaging Library) that is currently only supported officially on Python2.7. Below is the base code that we will be using throughout the course of this lesson.
Below is the image we’ll be using to test; If you’d like to use your own, try to pick a 24-bit BMP for the best results.
You can find the original copy that was rendered by Wikimedia user Tesseract2Here.. The copy on that site is not in the correct format. You can convert the image by opening it in GIMP and exporting as Windows BMP.
Once you have the EarthRender.bmp in the same folder as your base code; run it using the following command from your terminal
The code now will export an identical copy of the original BMP file but with the new name OutputImage.bmp.
The rest of the tutorial will demonstrate the methods required to manipulate images in a number of different ways. Simply add the new function into your code and change the new_img = filter_name(img) line in your __main__ to match the method you’d like to execute.
Invert
Mask (Black and White)
Grayscale
Sepia Tone
Swap Channels
Flipping
Mirroring
Contrast
Get Block Average Function
For the remaining tasks we’ll be utilizing the following function. Be sure to add it into your project so we can reference it.
Blur
Stark Lines
Pixelize
Image Synthesis
Finally we can actually generate our own images using this library. Here’s an interesting one that uses XOR