playing with pillow… (part 1)

Here, we will discuss about image transformation: geometrical, color, point some image thresholding, image enhancement buy applying filters, editing GIF, drawing on an image, image conversion and modification in bulk and rolling image using PIL.
Pillow is a fork of PIL- Python Imaging Library that will support Python 3.x.

Installing pillow library:

pip install PIL

The important class of the library: Image

Opening the image and getting details about it.

from PIL import Image

im = Image.open('simpson.png')

print(im.size, im.mode, im.format)
#(1600, 1200) RGBA PNG

im.show()
#To open the image

As you can see from the comand:

print(im.size, im.mode, im.format)
#(1600, 1200) RGBA PNG

the image has a RGBA color profile. We can convert it to jpeg only after converting it to RGB:

rgb_im = im.convert('RGB')
rgb_im.save('simpson_new.jpg')

Rotate an image:

from PIL import Image
import os

im = Image.open('simpson.png')
im = im.rotate(45) # rotate the object im 45 degrees

rgb_im = im.convert('RGB')
rgb_im.save('simpson_45.jpg')

im.close()

You can resize the image through the resize command:

from PIL import Image
import os

im = Image.open('simpson.png')

rx = int(im.width/10)
ry = int(im.height/10)

im=im.resize((rx,ry)) #rx and ry are new pixel of image

rgb_im = im.convert('RGB')
rgb_im.save('simpson_resized.jpg')

im.close()

Add a text to immage:

from PIL import Image, ImageDraw, ImageFont
import os

im = Image.open('simpson.png')
d1 = ImageDraw.Draw(im)

myFont = ImageFont.truetype('Monofur/monofur bold Nerd Font Complete Mono Windows Compatible.ttf', 140)

d1.text((650,700), 'Hello World', font=myFont, fill=(255,255,0))

im.save('simpson_hello.png')
im.close()

Crop and paste the parts of the image:

from PIL import Image
import os

#path = # path of the image that you won't to open
#os.chdir(path)

im = Image.open('simpson.png')

print(im.size, im.mode, im.format)
#(1600, 1200) RGBA PNG



box = (531,38,957,434)  #Two points of a rectangle to be cropped
cropped_part = im.crop(box)
cropped_part = cropped_part.transpose(Image.ROTATE_180)
im.paste(cropped_part,box)


im.show()
#To open the image

Python animations with Matplotlib

In Python, plotting graphs is straightforward — you can use powerful libraries like Matplotlib. It happens, however, that you need to visualize the trend over time of some variables – that is, you need to animate the graphs.

Luckily, it’s just as easy to create animations as it is to create plots with Matplotlib.

Matplotlib

Matplotlib – as you can read on the official site – is a comprehensive library for creating static, animated, and interactive visualizations in Python. You can plot interactive graphs, histograms, bar charts, and so on.

How to Install Matplotlib

Installing Matplotlib is simple. Just open up your terminal and run:

pip install matplotlib

Numpy

Also, if you don’t have numpy, please install it so you can follow the examples in this tutorial:

pip install numpy

How to Plot with Matplotlib

Even though this tutorial is about animations in Matplotlib, first let’s create a simple static graph of a sine wave:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 10, 0.1)
y = np.sin(x)

fig = plt.figure()
ax = plt.axes(xlim=(0, 10), ylim=(-1.1, 1.1))
diagram = plt.plot(x, y)
 
plt.show()
A basic sine wave

How to Animate with Matplotlib

To create an animation with Matplotlib you need to use Matplotlib’s animation framework’s FuncAnimation class.

For instance, let’s create an animation of a sine wave:

import numpy as np
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation

fig = plt.figure()
ax = plt.axes(xlim=(0, 5), ylim=(-1.5, 1.5))
line, = ax.plot([], [], lw=2)

def init():
    line.set_data([], [])
    return line,

def animate(i):
    x = np.linspace(0, 5, 500)
    y = np.sin(2 * np.pi * (x + 0.02 * i))
    line.set_data(x, y)
    return line,

sinewawe_animation = FuncAnimation(fig, animate, init_func=init, frames=200, interval=20, blit=True)
sinewawe_animation.save("Animation.gif")

plt.show()

We have:

Let’s then go through the code above in a bit more detail to better understand how animations work with Matplotlib.

Lines 1–3

Here you add the required libraries. In particular, we add the FuncAnimation class that can be used to create an animation for you.

Lines 5–7

fig = plt.figure()
ax = plt.axes(xlim=(0, 5), ylim=(-1.5, 1.5))
line, = ax.plot([], [], lw=2)

Here you first create an empty window for the animation figure. Then you create an empty line object. This line is later modified to form the animation.

Lines 9–11

def init():
    line.set_data([], [])
    return line,

Here you create an init() function that sets the initial state for the animation.

Lines 13–17

You then create an animate() function. This is the function that gives rise to the sine wave. It takes the frame number i as its argument, then it creates a sine wave that is shifted according to the frame number (the bigger it is, the more the wave is shifted). Finally, it returns the updated line object. Now the animation framework updates the graph based on how the line has changed.

def animate(i):
    x = np.linspace(0, 5, 500)
    y = np.sin(2 * np.pi * (x + 0.02 * i))
    line.set_data(x, y)
    return line,

Line 19

sinewawe_animation = FuncAnimation(fig, animate, init_func=init, frames=200, interval=20, blit=True)

This line of code puts it all together and creates the actual animation object. It simply:

  • Renders an animation to the figure fig by repeatedly calling the animate() function starting from the initial state defined by init()
  • The number of frames rendered to “one round of animation” is 200.
  • A delay between two frames is 20 milliseconds (1000ms / 20ms = 50 FPS).
  • (The blit=True makes sure only changed pieces of the plot are drawn, to improve the efficiency)

Line 21

sinewawe_animation.save("Animation.gif")

This piece of code is used to generate an animated gif (the same one I used in this tutorial to show you the animation)

Line 22

You guessed it — this line shows the animation.