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
100DaysOfCode PROGRAMMING TUTORIALS

How To Write Code Like A Professional?

Everyday, we programmers write hundreds of lines of programming code. But, have you ever stopped to notice if your program is good enough? How do you make sure your programming skill set is up to the mark? How to make sure you are Programming Like A Pro? In this article, we consider these questions and try to answer them each in greater details.

How To Code Like A Pro?

There are many characteristics of a program written by an experienced professional that sets his code apart from a code newbie. A professional programmer would make use of his past learning experience and implement his code that follows a certain set of guidelines and best practices he has learnt over the time since he began programming.

While each of these set of guidelines and best practices may differ from one Professional Programmer to another Pro, there are many common guidelines which more or less all Professional Programmers follow that can make their code set apart from the rest. Here is a list of some of such common guidelines used by almost all Professional Programmers. If you can practice and incorporate these practices and techniques into your daily programming routine, even your program code will start to look more professional.

Best Practices & Guidelines To Write Code Like A Professional

  • Write code that makes use of the processor efficiently – In other words, write code that runs fast on the processor using lower number of clock cycles. How to achieve this? While there are many things involved in learning to write a highly CPU efficient programs which will be explained in the future articles, some of the most common practices is to use loops sparingly, use efficient looping systems, write programs using instructions that require less clock cycles to accomplish the task at hand etc. You need to have good understanding of the underlying computer system architecture to get a better hold or control on these aspects, so learn more about the computer architecture.
  • Write code that makes use of memory efficiently – Use the memory of a computer system efficiently and sparingly. It usually takes certain amount of computer clock cycles to read and write data to or from the memory. So if you want your code to speed up, it is better to write code using instructions that uses lesser amount of memory. If your code allocates too many variables, it can start gobbling up a lot of RAM space in your user’s computer, there by slowing down the computer all together, thus giving a had user experience.
  • Write code that is more readable – This is one of the most important aspect of a professional code. You can write code in a convoluted way to do something extremely smart on its data, but if in the future you move on in your job role and your code is handed over to your junior developers, they will find it extremely hard to read and understand your code. So always write code that is easily readable by anyone familiar with programming. This can also include adding more comments in your source code, naming the variables appropriately etc. Sometimes, writing readable code could result in writing a slightly inefficient piece of code thus contradicting the above 2 points discussed earlier. But however, in such a situation, it is still advisable to give priority towards readable code than saving a few CPU clock cycles.
  • Write code that is highly modular – What does this mean? It means you need to break down your programming into individual modules such as functions and classes, that does one thing and only one thing but extremely well. Your code need to be split up into several functions, files and libraries that can be made use of in the future for other projects as well.
  • Write code that is well tested and documented – Each of your code modules need to be very well tested to ensure it fulfills and works under all boundary conditions. It should not break down for some unexpected values but gracefully reject the input under such situations. This is achieved by writing robust test cases that can test for all frequently possible conditions even if it occur only one in a million time (boundary conditions). Make sure that the code is well documented using comments and appropriate variable or function names as discussed earlier.
  • Write code that is easy to enhance – Before you sit down to write your code, you need to design to program to be highly modular and easy to enhance of its functionalities in the future. This would mean writing code that is modular, with will defined APIs and interfaces such that a function serving that API can be swapped for another function with a different implementation for the same set of input and output values.

There are still many more aspects of a professional’s code that usually depends on his style and taste of coding, but the above list should give you a good fundamental beginning on how to think and write code like a professional programmer.

In the future articles, we will continue to explore some of the fundamental aspects of computer science such as a computer’s architecture, its basic functionality etc that will help us getting a solid understanding the basics of computer science. Do let me know if you have any comments on this or any other topic you would want me to explore and I will be happy to accommodate your requests.

So until then, happy coding! 🙂

Categories
PYTHON TUTORIALS

Difference between expression and statement in Python

A Python expression can be defined as any element in our program that evaluates to some value. Well, what does this mean? To understand it better, let us fire up our Python interpreter and take a deep dive into this topic on Python expressions with these examples.

Once in our python interpreter, let us type the following command:

Python 3.5.2 (default, Nov 12 2018, 13:43:14) 
[GCC 5.4.0 20160609] on linux
Type "copyright", "credits" or "license()" for more information.
>>> 4
4
>>> 

We can see that by simply entering the number ‘4’ into our Python interpreter, it was accepted and evaluated to be of a value of integer 4. Hence, we can say that the input ‘4’ we entered is a type of expression.

Similarly, if we input the command ‘4 + 1’ to the Python interpreter:

Python 3.5.2 (default, Nov 12 2018, 13:43:14) 
[GCC 5.4.0 20160609] on linux
Type "copyright", "credits" or "license()" for more information.
>>> 4
4
>>> 4 + 1
5
>>>

Our interpreter goes ahead and computes a value of 4 from this and results in a value of 5. Here too, the input ‘4+1’ can be called an expression as it resulted in a value of 5.

Similarly, if we enter this code to the Python interpreter we get,

Python 3.5.2 (default, Nov 12 2018, 13:43:14) 
[GCC 5.4.0 20160609] on linux
Type "copyright", "credits" or "license()" for more information.
>>> 4
4
>>> 4 + 1
5
>>> "Hello" + "World"
'HelloWorld'
>>> 

This too shows that irrespective of the data type used (string in this case as opposed to integers in the earlier examples), a Python expression results in the evaluation of the data (“Hello” and “World”) to a final value (“HelloWorld”). Thus “Hello” + “World” is also a Python expression.

On the other hand, if we take a look at this example:

Python 3.5.2 (default, Nov 12 2018, 13:43:14) 
[GCC 5.4.0 20160609] on linux
Type "copyright", "credits" or "license()" for more information.
>>> 4
4
>>> 4 + 1
5
>>> "Hello" + "World"
'HelloWorld'
>>> result = "Hello" + "World"
>>> result
'HelloWorld'
>>> 

Here we are assigning the final evaluated expression value to another variable ‘result’. This type of command where a value is assigned to a variable is called a Python Statement.

So in other words, we can see that a Python statement is made up of one or more Python expressions.

Expression Vs Statement

  • Expression
    • Expressions always returns a value
    • Functions are also expressions. Even a non returning function will still return None value, so it is an expression.
    • Can print the result value
    • Examples Of Python Expressions: “Hello” + “World”, 4 + 5 etc.
  • Statement
    • A statement never returns a value
    • Cannot print any result
    • Examples Of Python Statements: Assignment statements, conditional branching, loops, classes, import, def, try, except, pass, del etc

Summary

In simpler terms, we can say that anything that evaluates to something is a Python expression, while on the other hand, anything that does something is a Python statement. Curious to learn further? Follow our other articles in this blog to know more!