We import Image
from the PIL
package:
from PIL import Image
We can open an image from disk by using open
:
if "google.colab" in str(get_ipython()):
!wget https://ssciwr.github.io/lunch-time-python/lunchtime5/thingstaette.png -q
img = Image.open("thingstaette.png")
The image is represented using the Image
class from PIL (or one of its specialized subclasses). Images can be created by loading from file, from other images or programmatically.
The img
object can be queried for a number of metadata fields of the image:
img.format
'PNG'
img.size
(856, 652)
img.width, img.height
(856, 652)
img.mode
'RGBA'
img.getbands()
('R', 'G', 'B', 'A')
To display the image directly in Jupyter notebooks, we can use the IPython
's rich display system. Alternatively, img.show()
can open the image in an external viewer.
img
Image modifications operate on one image and return a new image which is a copy of the original with the applied modifications. This is common (good) practice in object-oriented programming.
cropped = img.crop([330, 100, 650, 550])
cropped
resized = cropped.reduce(2)
# resized = cropped.resize((150, 100))
resized
rotated = resized.rotate(180)
rotated
from PIL import ImageFilter
blurred = rotated.filter(ImageFilter.BLUR)
blurred
Merging is done as an in-place operation on the Image
object:
img.paste(rotated, (100, 100))
img
After successful transformation, we can save the result.
PIL
converted = img.convert("RGB")
converted.getbands()
('R', 'G', 'B')
converted.save("final.jpg")
Pillow has much more functionality than shown here today, check the examples and references in its documentation:
Thanks for joining!