In this article, we will learn how to import a class from another file in Python. But there can be two scenarios when we try to import a class from another file. The file can be in the same folder or in a different one. So, we will take a look at both the scenarios.
So are you ready to dig more? Great! Then let us start right away!
Import class from another file in the same folder
So we have written a Python class in a file and now want to import it into another file in the same directory. How do we do that? I think this is best explained with an example.
So let me create a file called bird.py that has a Bird class in it. Alright? So this is how that class looks like:
//birds.py
class Bird:
def init(self, name, can_talk):
self.name = name
self.can_talk = can_talk
def get_details(self):
details = self.name + ', Can it talk? = ' + self.can_talk
return details
So as you can see, the Bird class defined here will store the name of the bird and whether it can talk or not. Just a simple class, alright?
Now, say we want to import this class into my main Python file called main.py present in the same folder as shown below:
How do we go about doing that?
Well, since both our main.py and my bird.py files are in the same folder or directory, all we need to do is to import the bird.py’s Bird class in my main.py file. Hmm… confused? Well don’t be! Just take a look at the main.py file’s code below and you will get it!
See? It is quite simple when both of the files are in the same directory. Right?
But what to do if your bird.py is in a different folder? That is what we will see in the next section.
Import class from another file in a different directory
Now in this case, let us put our bird.py in a sub folder called pet. So our directory structure looks something like this:
So how can we now import our Bird class into our main.py in this case? Well, now we need to make use of what is called a Python package.
What I mean by this is that we will now create our pet folder as a separate package and then use that package in any of our Python file present in any directory.
How to create a Python package
So we now want to create a package from our pet directory, right? How do we do that? Once again, it is quite a simple process in Python.
All you have to do to create a package in a folder using Python is to introduce a file called __init__.py. What this file does is to create a Namespace for the package. This is required so that you can use any class names in your package and not get conflicted with other packages using the same class name.
But here is the thing. You need this __init__.py file only if you are using a Python version that is version 3.3 or lower. But if you are using Python version higher than that, you dont even need to use the __init__.py file.
So, by adding a __init__.py file, our directory structure will now look something like this:
Now with this file in place, we can import the Bird class into our main.py file as follows:
from pet.bird import Bird
mybird = Bird('Parrot', Yes)
print (mybird.get_details())
So as you can see, once we have packaged the pet folder, calling Bird class from this package is done in line 1. Here we have used the dot operator to access the bird file present inside pet folder and then imported the Bird class.
The remaining code after that line is exactly the same as in our previous case.
Conclusion
So as you can see, importing classes from other files in Python is quite easy. It varies just a bit based on where the file is located. If it is in the same folder we can simply import the file. But if it is in another folder, we will have to create a package of that folder and then import it.
I hope this tutorial helped you in some ways in learning Python imports. But if you have any queries, please do let me know in the comments below and I will be more than happy to help.
While working on Matplotlib, we can change the axes size of its output plots. Matplotlib provides us with specific functions to modify individual axes values. So we can write Python programs to modify these axes size.
In our previous tutorial, we created a simple Matplotlib plot of multiple lines along with gridlines. However, in that plot we can see tht the size of each of the two axis where auto-determined. Since we used x & y values ranging between 1-10 & 0-30 respectively, axis size was also so to the same range.
However, we can actually change this. We can use Matplotlib to change axes size by making use of its appropriate features.
Understanding How Matplotlib Changes Axes Size
So let us go back to our previous plot, which looked like this:
Output plot of our previous tutorial
The code we used to generate the above chart looked like this:
import matplotlib.pyplot as plt
x = range(1, 10)
plt.plot(x, [xi*1 for xi in x])
plt.plot(x, [xi*2 for xi in x])
plt.plot(x, [xi*3 for xi in x])
plt.grid()
plt.show()
As mentioned earlier, we can see from the above code that x-axis values ranges between 1 & 10. On the other hand, values of y-axis is determined by the 3 lines we plotted on the graph. Their values where calculated by multiplying the values of x by 3 different values – 1, 2 & 3.
So by analyzing this, we can see that the highest y value achieved is from line number three. But line is being drawn using the code:
plt.plot(x, [xi*3 for xi in x])
So, we can see that the highest value of y it can achieve is when we multiply the highest value of x with 3. But x ranges between 1 & 10. So the highest value that y can achieve is:
yi = xi*3 where xi=9 (because it is less than 10)
yi = 9 * 3
yi = 27
Hence, the highest value of y is 27. Our graph is also confirming this. We can see that the value of y axis of our 3rd line is not going beyond 27.
So with this knowledge, Matplotlib is drawing the x-axis of the plot to be up to 10. But on the other hand, it is stretching the y-axis to 30. It did this to accommodate the highest y-axis value of 27 of our 3rd plot.
Programming Matplotlib To Change Axes Size
So now that we understand how Matplotlib calculates the axes values automatically, we will now learn how we can change this. In order for us to achieve this, we will use yet another function of Matplotlib.
Matplotlib Axis Function
In order to control the size of our plot axes, Matplotlib provides us with another function called the axis function. The signature of this function looks like this:
matplotlib.pyplot.axis(*args, **kwargs)
where args = [xmin, xmax, ymin, ymax]
From the above signature, we can see that we can set the minimum and maximum values of x & y axis using xmin, xmax, ymin and ymax. You should also keep in mind that we need to pass these parameters as a Python list variable.
However this is not it. There is one another interesting feature of axis(). It is that if we simply call it without passing any parameters, it will return the current values of xmin, xmax, ymin ymax!
So axis() acts like both a GET function and a POST function.
One more thing to keep in mind while using axis() is that we need to call it before calling our plt.show().
Now enough of the theory behind this function. Let us understand it better by exploring it with our example plot.
Code For Matplotlib Change Axes Size
So we will now modify our code to include axis() function call as follows:
import matplotlib.pyplot as plt
x = range(1, 10)
plt.plot(x, [xi*1 for xi in x])
plt.plot(x, [xi*2 for xi in x])
plt.plot(x, [xi*3 for xi in x])
plt.grid()
plt.axis()
plt.show()
When we run this program, what we get is the current size of the axes of our plot:
So the above code returned us with the current size of our plot. Let us now modify this code further so that it can change the size of our plot axes values. To do this, let us modify our code like this:
import matplotlib.pyplot as plt
x = range(1, 10)
plt.plot(x, [xi*1 for xi in x])
plt.plot(x, [xi*2 for xi in x])
plt.plot(x, [xi*3 for xi in x])
plt.grid()
plt.axis([0, 20, 0 , 40])
plt.show()
By adding the parameters (0, 20, 0, 40) to our plot axis function, we have increased the size of both our axes. So the x-axis is extended to 20(xmax=20) while the y-axis is extended to 40 (ymax=40).
When we now run this program again, we will finally get this Matplotlib output plot:
Image of Output Plot After Changing Axes Size In Matplotlib
From the above plot, we can clearly see that the x-axis is increased upto 20 while the y-axis of the plot is increased to 40. So this is how we can use the axis() provided by Matplotlib to change xxes size of our output graph plot.
I hope this tutorial was helpful to you. If you still have any questions about it, do let me know in the comments below. So until next time, ciao! 🙂
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.
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.
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:
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:
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
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!
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.
Writing a very big sum function in Python programming language
A Python expression can be defined as any element in our program that evaluatestosomevalue. 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!