Author Archives: kang & atul

What’s inside Python ‘for’ loop?

Have you ever wondered how ‘for’ loop is automatically able to iterate over iterable like lists, strings etc? What if I tell you that Python for loop is actually an infinite while loop. Most of us might not believe but as is this beautiful Python.

There must be something inside ‘for’ loop that helps it to iterate over any iterable. In this blog, we will see how the for loop is actually implemented in python. Let’s understand this with an example.

Suppose we want to sum the elements of a list [1,2,3,4]. This can be done as

Actually what happens inside for loop is this

To understand this, we first need to know what iterable and iterators are

  • Iterable: It is anything that you are able to loop over like lists, tuples, strings etc.
  • Iterator: It is the object that does the actual iterating.

So, in order to iterate, you must first convert an iterable into an iterator. This is done by using built-in iter() function. To get the next item, use next() function on that iterator (not on iterable). If there are 100 elements in an iterable then we need to call next() 100 times. To avoid this, we use an infinite while loop. next() function raises a StopIteration exception when there are no more elements in that iterable. So, to avoid this exception, we have used try-except statement and in this way, we break out from the infinite loop.

This is how the for loop actually works in python.

Now, you might have got some feeling about the Python for loop, iterator and iterable. Hope you enjoy reading.

If you have any doubt/suggestion please feel free to ask and I will do my best to help or improve myself. Good-bye until next time.

Read, Write and Display Videos with OpenCV Python

In this blog, we will see how to Read, Write and Display Videos using OpenCV. Since a video is made up of images, most of the commands we learned in the previous blog also applies here.

Let’s see by an example how to capture video from the camera and display it.

cv2.VideoCapture(0) will open the default camera. You can select the second camera by passing 1, third by passing 2 and so on. This creates a VideoCapture object (“cap” here).

cap.read() capture frame by frame. This returns two values, frame and ret. If the frame is read correctly, ret will be True otherwise False.

cv2.waitKey(1) & 0xFF == ord(‘q’) will exit the video when ‘q’ is pressed.

cap.release() closes video file or capturing device.

If you want to play a video from a file, just change the cv2.VideoCapture(0) function in the above code by giving the file path as cv2.VideoCapture(‘F:/downloads/Python.mp4’). Also, use the appropriate time for cv2.waitKey() function (25 will be OK).

Saving a Video:

First, create a VideoWriter object with cv2.VideoWriter(output filename, fourcc, fps, frameSize). fourcc(4-character code of codec) is used to compress the frames. After creating this object, use object.write() to save the video. Let’s see an example

Now, you might have got some feeling about the basic video commands in OpenCV. Hope you enjoy reading.

If you have any doubt/suggestion please feel free to ask and I will do my best to help or improve myself. Good-bye until next time.

Creating a Snake Game with pygame

In this tutorial, we will create a snake game with python and pygame. You can find full code here.

What is pygame?

It is a free and open source Python programming language library used for making a multimedia application like games. It is great for beginners as it’s simple and easy to use.

Installing pygame in Python:

There are two ways to do this.

  1. You can directly use pip install pygame in the command window or
  2. Download whl file from this link python extension packages according to your python version. Then use pip install whl_file_name.

Let’s create a snake game using pygame library. To Start with this, we first need to initialize pygame modules as shown below.

pygame.init() will attempt to initialize all the pygame modules for you. Not all pygame modules need to be initialized, but this will automatically initialize the ones that do.

Displaying Game Objects:

After initializing pygame modules, it’s time to display the game window. For that, we need to initialize its dimensions(width and height). Here I have used 500 x 500, but you can choose yours.

display.fill(window_color) will fill white color into game window and pygame.display.update() allows only a portion of the screen to be updated, instead of the entire area. If no argument is passed, it updates the entire Surface area.

This will create a game window as shown below.

Now it’s time to display snake and apple. Here I have used red color for snake and an image for apple. At the start of each game, we want snake’s starting position to be fixed while apple can take any random locationStarting length of the snake is 3 units where each unit is a 10×10 block.

pygame.draw.rect() will draw a rectangle corresponding to given arguments which will represent our snake and display.blit() will show the image of an apple.

This will create a game window as shown below.

The next thing is to decide at what frame rate we want to play our game. This is done using pygame.time.Clock() that creates a “clock” object. Now whenever clock.tick() is called and passed with some number, then it will limit the run time speed of the game. As an example, if clock.tick(20) is called, then the program will never run at more than 20 frames per second.

Game Logic:

Now it’s time to define game rules. As you know, there must be some rules which makes a game playable.

Rule 1: If the snake collapses with itself or with boundaries, game over.

Rule 2:  Moving the snake to a new position

In our game, the snake will continue to move in one direction until a button is pressed. To move the snake, we need to add one unit to the head and remove one unit from the tail.

Another case is when a button is pressed to move in a direction(left, right, up or down). Also, the Snake cannot move backward.

After seeing which direction button is pressed, we need to change our snakes head position.

Rule 3. If the snake eats an apple, the apple moves to a new position and snake length increases.

When the snake eats an apple, we increase our snake’s length and improve the score. To increase snake size, we add one unit at snake’s head. Also, we need to create another apple at random location to proceed the game.

Displaying Final Score:

After the game is over, we want to display the final score. Here, I have defined a function ‘display_final_score’, which takes final score and text to be displayed as its arguments to display in the game window.

This will display our final score as shown below.

Finally, our snake game is created, now it’s time to play it.

Now, you might have got some feeling about creating games using pygame. Hope you enjoy reading.

If you have any doubt/suggestion please feel free to ask and I will do my best to help or improve myself. Good-bye until next time.

Read, Write and Display Images with OpenCV

In this blog, we will see how to Read, Write and Display Images using OpenCV. I hope you have installed OpenCV, numpy, and matplotlib libraries, if not, please refer to this blog.

Read an image:

To read an image, use the function cv2.imread(filename[, flags]) where filename is the full path of image and flags specifies the way image should be read (>0 for color, =0 for greyscale, and <0 for loading image as is (with alpha channel)).

If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format), the function returns an empty matrix, not an error.

Display an image:

To display an image in a window, use the function cv2.imshow(winname, image) where the first argument is the Name of the window and second is the Image to be shown. So, this will first create a window named as image and displays the image in that window.

Note: This function must be followed by cv2.waitkey(delay) function otherwise the image wouldn’t be displayed.

cv2.waitKey(delay) decides for how long the image will be displayed. Its argument delay is the time in milliseconds. If the delay is <=0, the image will be shown forever otherwise destroyed after delay milliseconds.

cv2.destroyAllWindows() simply destroys all the windows we created.

Special Case: We can create a window first and load the image to it later. Just write the below code line before the cv2.imshow() function.

Write an image:

To save an image, use the function cv2.imwrite(filename, image) where the first argument is the file name with which we want to save the image file, the second argument is the image you want to save.

This will save the image in JPEG format in the working directory.

Now, you might have got some feeling about the basic image commands in OpenCV. Hope you enjoy reading.

If you have any doubt/suggestion please feel free to ask and I will do my best to help or improve myself. Good-bye until next time.

What is a Digital Image?

In this blog, we will try to understand what is a digital image and how it is formed. We will also learn about image sensors and pixels in this blog.

What is a Digital Image?

A Digital Image is a numeric representation of a two-dimensional image and is made of picture elements called pixels, arranged in rows and columns. These numeric values are the intensity or brightness values that are associated with the pixels.

Digital Image

Now, let’s understand what is a pixel and how the intensity value is calculated?

The concept of pixel is closely related with image sensors. So, by understanding image sensors I hope you will get a feel of what a pixel is.

Image Sensor: It is a device that converts the light energy into an electric signal. The figure below shows a single image sensor.

source: R. C. GonzalezR. E. Woods, Digital Image Processing

In digital cameras, these sensors are arranged in the form of a 2D array on a chip. Mostly there is a 1-to-1 correspondence between a pixel and a sensor meaning each sensor produces 1 pixel. Thus, the total number of pixels in an image = total number of sensors on a chip. Sometimes, multiple sensors are used to produce a pixel of information.

8MP camera means there are 8×106 image sensors in the camera chip and if there is a 1-to-1 correspondence between a pixel and a sensor then the image contains 8×106 pixels.

Note: Larger the pixel, better will be the image quality.

How the Digital Image is formed?

There are basically two types of image sensors used in digital cameras: CCD or CMOS. The CCD sensor is a silicon chip that contains a 2D array of photosensitive sites or sensors. Each sensor has a PN diode and a storage cell. Each sensor outputs a pixel value through these steps

  1. Light energy or photons(>1.2eV) falls on the silicon layer of the sensor and electrons are released(stored in potential well until the shutter is open).
  2. After the camera shutter closes, these electrons are moved to the storage cell (by applying +ve voltage on vertical shift register).
  3. These electrons are then transferred to the serial shift register.
  4. These electrons are converted into the analog voltage that is amplified using an amplifier.
  5. The output voltage signal is immediately converted to a digital signal by means of an analog-to-digital converter (ADC) in digital cameras, either on or off-chip. This digital quantity obtained is the intensity value of a pixel.

These steps are for the CCD sensor. For CMOS sensor, step 3 is not performed and voltage conversion and amplification (Step 4) is done in the sensor itself. This voltage is sent to ADC with the help of switch from each sensor and outputs the intensity value of a pixel.

Repeat these steps for all the sensors on a chip to get the intensity values corresponding to each pixel and thus we get a digital image.

Now, you might have got some feeling about the image sensors, pixel, and digital image. Hope you enjoy reading.

If you have any doubt/suggestion please feel free to ask and I will do my best to help or improve myself. Good-bye until next time.

Installing Python OpenCV and other libraries

Here, we will be installing the libraries that are required to perform image processing operations. We will be using the following Python libraries

  1. OpenCV
  2. Numpy
  3. Matplotlib

Why we are using OpenCV, not Matlab or any other?

  1. Because it is open source, fast(written in C/C++), memory efficient and easy to install (can run on any device that can run C).
  2. if you really want to learn about how computer vision works from the initial steps to the last, I suggest you learn OpenCV first then use any deep learning library like Tensorflow, pytorch etc when you’re ready to train a deep learning algorithm for better performance/accuracy results.

Installing Numpy, OpenCV or any library      (For WINDOWS)

There are two ways to install any library in Python IDLE,

  1. using pip command: In the installed Python folder, go to Scripts folder and open command prompt(press and hold Shift + Right Click and select Open command window here).  Then write pip install library name to get it installed. For example
  2. using .whl file:  First download .whl file of any library (version corresponding to your Python) from here. Then open the command prompt where you have downloaded this file and write pip install filename.whl. For example

Installing Numpy, OpenCV or any library    (For UBUNTU)

First, install pip using apt-get, then you can install any library as shown below

Anaconda: open the Anaconda prompt and write pip install numpy or any other library name which you want to install.

Now, you might have got some feeling about how to install Python libraries. Hope you enjoy reading.

If you have any doubt/suggestion please feel free to ask and I will do my best to help or improve myself. Good-bye until next time.

Python If __name__ == “__main__”

There are two things which we can do with our script/program, either we run it directly or import it into another program. Suppose we have a my_module.py file, as shown below

To run the my_module.py file directly we write python my_module.py on the command line. But if we want to import this file, then we have to comment out the function() calling statement. Import file means we only want functions, classes etc. and no code execution statements like a function call from that file. Just let the user call these at his own will.

For example, import math only imports functions from the math.py file. It is up to us whether we call math.sin() or math.cos(). That’s why we should remove code execution statements before importing a file.

Problem: “Commenting out function call from the file which we want to import”. For large modules, this is seriously a headache.

Question: Can’t we do something to automate the above problem, meaning writing import should automatically comment out or remove the function call.

Solution: Python if __name__ == “__main__” statement.

Concept: Before executing the code, Python defines a few special variables. For example, if the Python interpreter is running that module (the source file) directly, it sets the special __name__ variable to have a value “__main__”. If this file is being imported from another module, __name__ will be set to the module’s or file’s name.

So, what we do is write all the code execution statements inside if __name__ == “__main__” statement. When we run the file directly this condition is satisfied and the code is executed. While importing __name__ == file_name and not __main__  so the code is not executed.  Let’s see an example

Running the above hello.py file directly (F5 in shell or by command line), we get this output

Now, import this hello.py into another file say hi.py like as shown below

Running the above code gives the output shown below

Clearly, the func() is not executed while importing and this is what we want.

Now, you might have got some feeling about the Python if __name__ == “__main__” statement. Always use this. Hope you enjoy reading.

If you have any doubt/suggestion please feel free to ask and I will do my best to help or improve myself. Good-bye until next time.

Python Variables and Scope

To understand what is happening in the code, you should know what the “scope” of variable means. The scope of a variable refers to the places from where we can see or access a variable. To understand this more clearly, we should first know what “variable” actually means.

A variable is a reference to a memory address that contains the value. Let’s see the figure below.

Suppose, we have x=5. There are two ways of reading this line.

  1. ‘x’ is a variable name that references to a memory location in which 5 is stored.
  2. variable x equals 5

Saying the humungous first line every time may be frustrating, so we usually use the second way. Here comes the confusion. Let’s see by an example

Question: How many variables are there in the above code?

If we use the definition x equals 5, we might think that it is the same variable x with different values. But if we use the actual definition of the variable, we can argue that there are 3 variables as they refer to different memory locations and thus are different. We can always check the identity of the location of the object in memory using the python id() function. Just write id(variable_name) which outputs a number that refers to some memory location(same number means the same variable). So, use the shortcut definition but always remember the actual meaning.

This means we can define a number of variables with the same name(say x) in a program without having a relation between them. This sometimes creates confusion. Let’s understand this by an example

Now, which value should this x prints? This is where the scope comes into the picture. Scope tells us which variable we can access and from where.

LEGB Rule: LEGB stands for Local, Enclosing, Global and Built-in. This tells us the order in which python accesses the variable in a program. First, python will check if the variable is present in the local scope, if not then checks in enclosing scope and so on till the builtin scope is checked.

Let’s understand the LEGB terms one by one:

  1. Local: Python first tries to search for an identifier(variable) in Local scope. The local variable exists only within the block/function that it is declared in. When that block/function ends, the local variable has no significance, it gets destroyed. We cannot use it outside the function where it is declared. For example in the code below, x=3 is local to the number() function means we cannot access that variable outside this function. So, the output of the last print(x) will be an error saying name ‘x’ is not defined.
  2. Enclosing: Enclosing refers to the nested functions where one encloses the other. If Python does not find an identifier(variable) within the local scope, it will examine the Enclosing scope to see if it can find the variable there. Let’s understand this by an example

    For the print x —1, inner() is Local and outer is Enclosing while for the print x—2, outer() is Local. So, print x—1 will first search for x in the inner(). Since there is no x in the inner() so we go to outer()/Enclosing and check if x is there or not. So, print x—1 outputs 4. For print x–2, we have x in the Local scope of outer() so this will output 4.
  3. Global: Global variable means that it is accessible from anywhere in your script, including from within a function. It is usually defined at the top of the script or outside of the function. If Python fails to find the variable in both above scopes, then it will check the global scope. Let’s see an example

    As we have no x in the local and enclosing scope, so Python checks the global scope and outputs 4 for both print x statements.
    Note: using too many global variables will generally lead to name conflicts and will likely lead to unwanted side effects.
  4. Built-in: Built-in means the function and variables that are already defined in python. If an identifier is not found in any of the above scopes within a module, then Python will examine the built-in identifiers to see if it is defined there. For example

    If len is not found in any of the scopes, then Python would consult the Built-In scope, where it will find the len function and outputs 6. But if we create our own len function then it will have precedence over Built-in len function. Let’s see by an example

    Since our len function precedes over built-in len and thus the output of print x statement equals 1.

Now, I hope that you might have understood the Python variable and scope, Let’s look at some of the keywords that are useful regarding this

  1. Global Keyword: With this, we tell the Python to use the globally defined variable instead of locally defining it. This is useful when we want to change the value of a variable through a function. To use it, simply type global followed by the variable name. Let’s see an example
  2.  NonLocal Keyword: This is useful in nested functions. It causes the variable to refer to the previously bound variable in the closest enclosing scope. Let’s see by an example

    By nonlocal, we tell Python that this x is same as defined in the enclosing outer() function.

Now, you might have got some feeling about the Python variable and scope. Hope you enjoy reading.

If you have any doubt/suggestion please feel free to ask and I will do my best to help or improve myself. Good-bye until next time.

Side Effects in programming

According to Wikipedia, a function or expression is said to have a side effect if it modifies some state outside its local environment. Let’s understand this in depth by examples.

To understand side effects, first, we should know what “state” is. In layman terms, the state refers to the value of the variable at any given point in the program like x=2.

Now, the above Wikipedia definition might have started to make some sense. If not, don’t worry, see the figure below.

In this figure, we have a variable x that is outside the scope of two functions. Clearly, after the Function_2 call, the value of x changes which means that Function_2, other than returning value(if any), is interacting with variables outside its local environment and thus has a side effect.

In general, any lasting effect that occurs in a function, not through its return value, is called a side effect. Not through its return value means if we assign x=Function_1(), this will clearly change the value of x but this is not a side effect. For side effect, the change should occur inside a function.

Common ways to have side effects:

  1. Modifying a non-local variable: Let’s understand by an example

    The x in the square() function is local to its scope so no change in outside x. Global in square_side_effect() makes x global so any change in x will change it in whole code (outside function scope) so the square_side_effect function() is not pure(has side effects).
  2. Changing the value of a mutable object: Let’s take Lists which is a mutable object.

    Clearly, after calling list_side_effect(), the value of lst changes so, list_side has side effects.
  3. Performing Input/Output operations: This doesn’t change any objects or variable value, but it does have a potential lasting effect outside the function call because a person might see the output and be influenced by it.
  4. Calling other side-effect functions

Now, you might have got some feeling about the side effects. Hope you enjoy reading.

If you have any doubt/suggestion please feel free to ask and I will do my best to help or improve myself. Good-bye until next time.

Expressions vs Statements

Statement and expression are two important terms which are commonly misunderstood. Let’s start the explanation from the expression term.

Expression: 

An expression is a combination of values, variables, and operators including function call operator (), subscription operator [ ] etc. I guess that it is not clear, so let’s see an example.

In simple terms, an expression produces a value (1+1 is an expression as it produces a value 2) and can be written wherever a value is expected, for example as an argument in a function call, for example, 2*3 is expression given as an argument to range function in the code above.

Note: If you type an expression on the command line, the interpreter evaluates it and displays the result. While in a script an expression all by itself is a statement. You have to write print(expression) in order to display the result.

A value or variable is considered an expression as the interpreter returns the result(See example below). Functions that do not return anything is not an expression.

Note: Expressions can be reduced to any kind of value, which can be any integer, string or even a Python object like

Note: Evaluating an expression is not quite the same thing as printing a value. Expressions are displayed by the interpreter in the same format we enter, but print statement only shows the content (See example below)

Statements: 

A statement is an instruction that the Python interpreter can execute. In short, every line of python code is a statement. Note that expressions are statements as well. Below is an example of print and assignment statements.

Expression Statements: In this, first the expression is evaluated then the statement is executed. In the example below, the 2*3 expression is evaluated first, then the print statement is executed.

Now, you might have got some feeling about the difference between expression and statement. Hope you enjoy reading.

If you have any doubt/suggestion please feel free to ask and I will do my best to help or improve myself. Good-bye until next time.