Categories
DATA SCIENCE EDITORS PROGRAMMING PYTHON TUTORIALS VISUAL STUDIO CODE

Python Add Text To An Image Using Matplotlib Library

We can use Python programming language to add text to an image using its Matplotlib library. In this tutorial, we will take a look at the Matplotlib library and learn how to accomplish this. The process of adding text to an image is often also called as annotating text to an image.

What Is Python Matplotlib library?

Matplotlib is a Python data visualization library that is often used to plot graphs and charts to represent a dataset in a meaningful way. However, we can also use Matlplotlib to do some basic editing on an image file. We can use it to overlay graphical data over an image or plot graphs.

But in this tutorial let us make use of Matlplotlib to add basic text annotation to our image. In other words, we will use Python Matplotlib to add text to our image file.

Adding Text To An Image Using Python Matplotlib Library

In order to get started, we first need to use an image file over which we would like to add text. In this example, I will make use of this picture of a butterfly that I shot in my garden. This is a simple JPG file that I got by capturing the butterfly image using my Android smartphone’s camera.

Picture Of A Butterfly. Shot On Motorola One Action Android smartphone

This is a 278KB JPG file over which I would like to add an annotated text stating “What A Wondeful World!”. I woud like the text to be Orange in color with a font size of 30 and stylized to be bold. I would also like to place this text at the bottom of the image, somewhere over here:

Butterfly image highlighting the area where we would like our text to appear at.
Butterfly image highlighting the area where we would like our text to appear at.

So enough of theory, let us start writing our Python program to add the text to our image. Fire up your favorite text editor to start writing your code. In my case I use VS Code editor, but you can use any text editor you want.

Want to learn more about VS Code editor? Check this article.

Python Program To Add Text To An Image Using Matplotlib

The first line of code we would like to add in our program is:

import matplotlib.pyplot as plt

What this line does is that it would import our matlotlib library’s pyplot module into our program. So this is imported as plt so every time we want to make use of it, we would call it by using the plt name.

Next thing we would like to import is the Python Imaging Library (aka PIL)’s Image module. We need to use this module to import the image file (butterfly.jpg) into our program. So this is achieved by using the following piece of code:

from PIL import Image

We will then go ahead with importing the butterfly.jpg file into our program using the line:

img = Image.open("/home/amar/Pictures/butterfly.jpg")

The Image.open() method will open our file, read its content and store it into the variable img. Notice here again that we have imported the buttefly.jpg file into a new Python variable called img. Because of this from now on wards, we will be able to access the content of this image file by using the img Python variable.

With the image being available, its time to start editing it using Matplotlib library.

The first step in using Matplotlib library is to create a Matplotlib’s figure object, which forms the canvas of our image. All the operations we do from now on will be with respect to this canvas element. We can create Matplotlib’s figure object by using the lines:

plt.figure(figsize=(12,8))

Wait a second! What does this line even mean? What does figsize stand for and what values are we passing here? Let us answer these questions first.

Understanding Figsize Parameter Of Matplotlib’s Figure Object

figsize is a parameter we need to pass to the matplotlib plt module’s figure() method. It allows us to specify the exact width and height of our image.

Therefore when we pass the values (12,8) to this parameter, we are specifying these exact values. These values are expressed in the unit of inches. So when we say (12,8), we are asking the Matplotlib library to draw a figure with a width of 12 inches and a height of 8 inches.

Following this, we will ask Matplotlib library to draw our picture onto the figure‘s canvas by calling imshow fuction as follows:

plt.imshow(img)

As a result of the above code, Matplotlib will draw to image onto our figure object. However, it must be noted that it only draws the image to our figure object. But nothing will be displayed to the end user. If we want to display this image, we need to call another Matplotlib function plt.show(). But we do not want to display it yet. Therefore, we will discuss about this function later in the article when we actually make use of it.

So for now we will further move on with our code. As of now we have created a Matplotlib’s figure canvas object, we have opened our image file and drawn this image onto our figure object’s canvas. It is now time to write our intended “What a wonderful world!” text on top of it.

Adding Text Using Plot’s Text Function

In order for us to write text over an image, Matlplotlib provides us with yet another method, not surprisingly called the text function. So we can access it as part of the plt module. Also, we can find this function’s signature and the parameters it takes in link to its official documentation. With this information, we can finally call the text function to print our string onto the figure object’s canvas like this:

plt.text(200, 700, "What A Wonderful World!", color="orange", fontdict={"fontsize":30,"fontweight":'bold',"ha":"left", "va":"baseline"})

From the above code, we can interpret the parameters of plt.text function as follows:

X & Y Co-Ordinates Parameter

The first two parameters of this function are the x & y co-ordinates of the image. We set its values to be 200 and 700 so that the string starts from there.

Annotation Text Parameter

Following the two co-ordinate parameters is the annotation text paramter. This is the parameter which takes in the text string that we would like to print. We have set it to our string “What A Wonderful World!” that we wanted to add to our image.

Text Color Parameter

Following the the text parameter is the color parameter. We use this parameter to set the color of the string. In our case, we have set this to orange color.

Font Dict Parameters

Finally, we set the parameters for the type of font to use and its properties. In our case, we are asking Matplotlib library to set the following properties to our text fonts:

  • We want to use a font size of 30
  • We want the font to be bold
  • Next, we want the text’s horizontal alignment to be to its left
  • Finally, we also want it to be vertically aligned to its baseline

So with these properties set, we have finally defined the text that we wanted on our canvas. Hence, it is now time to display this image on our screen.

Displaying Image On Screen Using Matplotlib

This is the final stage of our code. At this point, we want our program to simply display the content of our modified image on our screen. So we will achieve this by using the plt.show() function that we had discussed earlier.

Using Matplotlib’s Show Function To Display The Image On Screen

The code to display our image on screen is pretty simple

plt.show()

We just call the plt.show() function as shown above. This should finally display the image in a new window on our screen.

Summary Of Python Program To Add Text To Image

So to summarize, our final program in full looks like this:

import matplotlib.pyplot as plt
from PIL import Image

img = Image.open("/home/amar/Pictures/butterfly.jpg")
plt.figure(figsize=(12,8))

#Finishes drawing a picture of it. Does not display it.
plt.imshow(img)
plt.text(200, 700, "What A Wonderful World!", color="orange", fontdict={"fontsize":30, "fontweight":'bold', "ha":"left", "va":"baseline"})
#Display the image
plt.show()

How To Save Matplotlib Image To A File

So far we edited the image file and added our own text on top of it. We were also able to display the final result to the end user screen in a separate window.

But what if we wanted to save this image? Can we write the program to save this edited image automatically to a new file? How to achieve this? If these are some of the questions you have running your mind then fret not. Because Matplotlib library comes to our rescue, once again!

To save the image onto a new file, Matplotlib provides us with yet another function called savefig().

Using Matplotlib’s Savefig Function To Save An Image

Matplotlib provides us with the function savefig() to save our image in a new file. It takes in many parameters which can be seen in this official documentation link. However, for our case, we simply want to save the image to a simple jpg file. So we need not have to use all the parameters defined in that link. We can simply use the following code to save it as a JPG file:

plt.savefig('/home/amar/Pictures/butterfly_captioned.jpg')

From the above code, we can see that we used plt.savefig() in its simplest form. We just added a path to the new file and saved it as a jpg file. Yes, the format of the file in which we want it to be saved is given by simply using the appropriate file extension. Matplotlib is intelligent enough to understand this and save it accordingly. Hence, if you wanted to save it as a PNG file, you just need to change the extension to .png. Its that really simple!

So with this, we can finally get our captioned image file as shown below:

Final Image file created by the Python code containing added text over the image
Final Image file created by the Python code containing added text over the image

So this was a brief tutorial on how to use Python to add text over an image programatically using Matplotlib library. Hope this was easy for you to follow up and understand. I will continue to write more articles on Python and image/video editing libraries in the future including Matplotlib. If you have any more questions or queries regarding this, do let me know in the comment section below. Until next time, ciao!

Categories
INSTAGRAM PHOTOGRAPHY SMARTPHONES TUTORIALS

What Does Aspect Ratio Mean In Photography?

Aspect Ratio is one of the important parameter in photography that determines the quality of a photograph. In this article, we will try to understand what an Aspect Ratio means in photography and how to chose the best Aspect Ratio while taking photographs.

You might be taking your photographs using a dedicated Photographic camera or by using a simple smartphone camera, but what makes a real difference in how these images evolve ultimately depends on the Aspect Ratio of these images. So let us dwell in detail into understanding the concept of aspect ratios in pictures and how you can determine which is the best aspect ratio to use in your pictures, depending on the type of pictures you want to take.

When you look into any photograph, you will notice that it is composed of a two dimensional capture of a moment in time and place. This two dimensional aspect of the subject of the image is then captured and stored in your photograph in two dimension as well. In other words, your photograph has two dimensions associated with it, its width and its height. It is the ratio of this width and height of a photograph that is called its Aspect Ratio.

An image representation describing the Aspect Ratio of a photograph to be the ratio of width to height.
Representation Of Aspect Ratio In Photography

There exists many different aspect ratios used in photography these days such as the 4:3 Aspect Ratio, 3:2 Aspect Ratio or 16:9 Aspect Ratios. In addition to these, photographers sometimes also use aspect ratios such as 5:3, 5:4 and 1:1 as well for medium or large photographs.

When to use 1:1 Aspect Ratio

With the emergence of various social media platforms such as instagram, facebook or twitter, the unusual aspect ratio of 1:1 has become popular these days. With this kind of aspect ratio, users can record video or capture images while holding the smartphone vertically while still be able to view the resulting video or images horizontally without losing any information in the image.

1:1 Aspect Ratio usually used my Instagram, Facebook, Twitter etc.

When to use 4:3 Aspect Ratio

4:3 Aspect ratios are the most commonly used aspect ratio in TVs and films. However, even devices such as iPad and other tablets use 4:3 aspect ratio displays so images taken with aspect ratio 4:3 will view better on ipads and other tablets when compared to other ratios.

4:3 Aspect Ratio usually used by iPad, TVs

When to use 16:9 Aspect Ratio

The 16:9 Aspect Ratio has become a recent standard usually found in high definition pictures and videos that can be best viewed on a HD screen, TVs and monitors. In a HD image with higher resolution, we can get detailed information in an image even when we zoom into the picture.

16:9 Aspect Ratio usually used in HD TV, HD Monitors & HD Displays

When to use 9:16 Aspect Ratio

Just like 16:9 aspect ratio used in HD images and videos, there emerged its inverted 9:16 Aspect Ratio that was popularized by Snapchat in its “stories” feature. This is an aspect ratio where in user is expected to record videos in portrait mode (using their smartphone vertically instead of horizontally) and viewed in portrait mode (vertically) as well. With the “stories” feature of Snapchat becoming popular, this ratio has been adopted by other social networks such as Facebook and Instagram as well.

9:16 Aspect Ratio used in Snapchat, Instagram stories

With so many new media applications becoming popular on smartphones, the aspect ratios of photography and videos keep on evolving, so this is not an all inclusive list but something that keeps on emerging as the time progresses.