Image Manipulation in Python

We will use the Thonny code editor. To start, open Thonny and save the image below to your computer.

Discovering PIL

Loading an image

photo-pil.py
from PIL import Image

image = "feudartifice.jpg"

im = Image.open(image)

print("Here are the image properties:", im.format, im.size, im.mode)
Copy this code and paste it into the Thonny window. Save the file in the same folder as the image, then run the code.
What do the three values that are displayed mean?

Image pixels

reading a pixel

You can display the (R,G,B) components of a pixel using the getpixel((x,y)) function. Watch out for the double parentheses!
x and y represent the horizontal and vertical positions of the pixel in the image, knowing that the origin (0,0) corresponds to the upper left corner.
For example:

from PIL import Image

image = "feudartifice.jpg"

im = Image.open(image)

print("Here are the image properties:", im.format, im.size, im.mode)

print(im.getpixel((92,15)))
print(im.getpixel((600,600)))

modifying a pixel

You can also modify a pixel using the putpixel((x,y), (r, g, b)) function. For example, the command im.putpixel((84, 42), (0,0,0)) will modify the color of the pixel at coordinates (84,42). Its new color will be (0,0,0), which is black.

Modifying an image

We will transform the fireworks image into grayscale (black and white). We saw previously that black is coded in RGB as (0,0,0) and white is coded as (255, 255, 255). We can add important information for what follows: all shades of gray are composed of the same value for R, G and B.

Copy the following code in place of the previous one.

from PIL import Image

image = "feudartifice.jpg"
im = Image.open(image)

(l,h) = im.size #we have the width in l and the height in h

#now, we create a new image with the same dimensions
image_nb = Image.new('RGB', (l,h))


for i in range(500):
    for j in range(300):
        (r,g,b) = im.getpixel((i,j))
        moy = round(255)
        image_nb.putpixel((i,j), (moy,moy,moy))
        
image_nb.save("image_nb.jpg")
What does the image look like? Why do we get this result?
Let's modify this code together to get what we want!