Manipulating images

Let’s Do Digital Team

Python image library

  • Image

Introduction to Image Manipulation

  • Image manipulation involves altering or transforming images using various techniques and tools.
  • This can include resizing, cropping, rotating, adjusting colours, and applying filters.

Loading Images

  • To manipulate images, we first need to load them into our environment.
  • In Python, we can use the PIL (also called Pillow) module from Image.
  • Note we are using imshow() now and not just show().
images.py
from PIL import Image

import matplotlib.pyplot as plt

img_1 = Image.open('hand-x-ray.jpg')

plt.imshow(img_1)

plt.show()

Loading Images

  • You will also need to use the pyplot module.
images.py
from PIL import Image

import matplotlib.pyplot as plt

img_1 = Image.open('hand-x-ray.jpg')

plt.imshow(img_1)

plt.show()

Loading Images

  • And then open the image file.
images.py
from PIL import Image

import matplotlib.pyplot as plt

img_1 = Image.open('hand-x-ray.jpg')

plt.imshow(img_1)

plt.show()

Loading Images

  • And then prepare to show the image and then actually show it.
images.py
from PIL import Image

import matplotlib.pyplot as plt

img_1 = Image.open('hand-x-ray.jpg')

plt.imshow(img_1)

plt.show()

Resizing Images

  • To resize an image, you can use the resize method from the PIL library.
  • img_1.resize((width, height)) needs a tuple with the new width and height.
  • This stretches or compresses the image.
resize.py
resized_img_1 = img_1.resize((50, 300))

plt.imshow(resized_img_1)
plt.show()

Cropping Images

  • Define the top-left and bottom-right coordinates of the area you want to crop.
  • Then use the crop method from the PIL library.
  • This uses pixel coordinates.
  • The top-left corner is (0, 0).
  • Coordinates are (new_top_left_x, new_top_left_y, new_bottom_right_x, new_bottom_right_y).
crop.py
box = (3900, 2900, 6000, 5500)

cropped_img_1 = img_1.crop(box)

Rotate Images

  • Use the rotate method from the PIL library to rotate an image.
  • Just provide an angle in degrees.
rotate.py
rotated_img_2 = img_2.rotate(10)

Inverting Images

  • Here we can invert the colours of an image.
  • Use the invert method.
rotate.py
from PIL import ImageOps

inverted_img_3 = ImageOps.invert(img_3)

Change file type

  • Specify the new file type in the name and then,
  • Use the save method from the PIL library to save the image in a different format.
rotate.py
bmp_filename = 'converted_image_3.bmp'

img_4.save(bmp_filename)

Now try it yourself!

  • Go to the Lesson 4 folder.
  • Open lesson_4.ipynb.
  • Don’t forget to ask your tutor if you need help.
  • See you in 20 minutes.

If you finish lesson 4 (but no need to rush), you can try your hand at lesson 5.