Introduction
At some point, we've all probably used some image modification software, whether that be an image filter or an online background remover.
In this guide, we'll take a look at Python's pillow module and how it can perform simple operations like blurring and rotating images.
Import PIL
Before we go any further, we first need to tell our program to load external code and functions using the keyword import.
Since we just need to access the 'Image' capability of the library, we can instead just import that one item directly:
from PIL import Image
def main():
...
main()
*Here, PIL stands for Python Imaging Library, of which Pillow is just a branch.
Now, assume we have this image of a waterfall stored in some jpeg file in our codespace.
To access this image, we must use the following code associated with opening files in Python:
from PIL import Image
def main():
with Image.open("falls.jpeg") as pic:
...
main()
Now, the program will refer to this opened "falls.jpeg" file as "pic," kind of like a nick-name.
Rotating and Blurring
Amongst the many things you can do with pillow, rotating and blurring are a couple of them:
from PIL import Image
from PIL import ImageFilter
def main():
with Image.open("falls.jpeg") as pic:
pic = pic.rotate(90)
pic = pic.filter(ImageFilter.BLUR)
img.save("out.jpeg")
main()
To rotate an image, we can simply use the rotate function that comes with importing Image, and entering a number of degrees as a parameter.
However, applying a filter is a little different in that it requires importing the "ImageFilter" capability of PIL.
Finally, we made sure to use the save( ) function to output the image in a new file called "out.jpeg."
Result...
Final Thoughts
Although the end result wasn't anything visually stunning, you kind of get the idea of how pillow can be a useful tool in everything from web development to tweaking a personal image.
Thanks for reading!
Comments