This pillow tutorial explains how to convert images in Python.
The Python Pillow library provides with all kinds of different image editing and manipulation capabilities. One of the many features is image conversion between different types (extensions) and also things like RPG to grayscale conversion.
This is the original image that we’ll be working with in this pillow tutorial.
Converting to another Format
Here we briefly discuss how to change file extension formats. This doesn’t actually have anything to do with the
convert() function, but thought it would be a good addition.
Interestingly enough, all you have to do is re-save the image with a new extension (and a new name if you want) by changing the extension in the
from PIL import Image img = Image.open("C://Users/Shado/Desktop/kitten.jpg") img.save("C://Users/Shado/Desktop/new_kitten.png")
And that’s it. We’re done! Pillow will automatically convert and save the JPG as PNG.
Converting from RPG to Grayscale
Now, onto the actual
convert() function. It can take different symbols as input which symbolize different modes into which it’s supposed to convert the image to. The below use is the most simple and common one that we could find.
Passing ‘L’ into the pillow convert function converts the image from it’s regular RGB colors to simple black and white (gray-scale).
from PIL import Image img = Image.open("C://Users/Shado/Desktop/kitten.jpg") new_img = img.convert('L') new_img.show()
Here’s our grayscale kitten image:
Another mode setting that you can pass it the convert function is ‘1’.
from PIL import Image img = Image.open("C://Users/Shado/Desktop/kitten.jpg") new_img = img.convert('1') new_img.show()
Here’s the output. It adds some kind of “blur” effect onto the image, which adds a unique look to it, which kind of looks nice.
This marks the end of the Python Pillow – Image Convert Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the article content can be asked in the comments section below.