Tag Archives: numpy

Creating a Snake Game using OpenCV-Python

Isn’t it interesting to create a snake game using OpenCV-Python? And what if I tell you that you only gonna need

  • cv2.imshow()
  • cv2.waitKey()
  • cv2.putText()
  • cv2.rectangle()

So, let’s get started.

Import Libraries

For this we only need four libraries

Displaying Game Objects

  • Game Window: Here, I have used a 500×500 image as my game window.
  • Snake and Apple: I have used green squares for displaying a snake and a red square for an apple. Each square has a size of 10 units.

Game Rules

Now, let’s define some game rules

  • Collision with boundaries: If the snake collides with the boundaries, it dies.
  • Collision with self: If the snake collides with itself, it should die. For this, we only need to check whether the snake’s head is in snake body or not.
  • Collision with apple: If the snake collides with the apple, the score is increased and the apple is moved to a new location.

Also, on eating apple snake length should increase. Otherwise, snake moves as it is.

  • Snake game has a fixed time for a keypress. If you press any button in that time, the snake should move in that direction otherwise continue moving in the previous direction. Sadly, with OpenCV cv2.waitKey() function, if you hold down the left direction button, the snake starts moving fast in that direction. So, to make the snake movement uniform, i did something like this.

Because cv2.waitKey() returns -1 when no key is pressed, so this ‘k’ stores the first key pressed in that time. Because the while loop is for a fixed time, so it doesn’t matter how fast you pressed a key. It will always wait a fixed time.

  • Snake cannot move backward: Here, I have used the w, a, s, d controls for moving the snake. If the snake was moving right and we pressed the left button, it will continue moving right or in short snake cannot directly move backwards.

After seeing which direction button is pressed, we change our head position

Displaying the final Score

For displaying the final score, i have used cv2.putText() function.

Finally, our snake game is ready and looks like this

The full code can be found here.

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.

Greyscale and Color Image

In the previous blog, we learned how the digital image is formed but we didn’t discuss whether the image formed was greyscale or colored. In this blog, let’s go through this.

A greyscale image is the one where pixels contains only the intensity information and not wavelength. For example, a pixel value of 165 represents the amount of light captured by the sensor(pixel). It doesn’t tell how much of this light belongs to red wavelength or any other.

For an 8 bit image, there will be 28=256 intensity levels where 0 means no light(black) and 255 means White light and in between levels represents shades of grey as shown below

The above image is created using numpy and OpenCV (See here for code).

A color image, on the other hand, contains intensity information corresponding to three wavelengths red, green, and blue (RGB)collectively called primary colors or channels. The reason for choosing these 3 colors lies in the fact that cone cells in the human eye, that is responsible for color vision, are sensitive to red, green, and blue light.

Note: Combining the primary colors(their wavelength may vary) in various intensity proportions, we can produce all visible colors.

So, in color image, corresponding to every pixel, we have 3 intensity values Red, Green, Blue (for example 160,30,45) that produces different colors in the image.

How a Color image is formed?

To form a color image, we want something that absorbs light in red, green, and blue wavelengths. The advancements in color image formation can be summarized by the figure below

Source: Foveon

The drastic advancement in color image formation came with the introduction of digital sensors like CCD and CMOS. Most of the digital cameras today only contain one imaging sensor so they cannot collect red, green, and blue information simultaneously at each pixel location. One possible solution is we use 3 imaging sensors with RGB filters but that is expensive in terms of money and time.

So, in 1976 Bryce Bayer of Eastman Kodak, invented the Bayer filter that revolutionized color image formation. Bayer filter is a color filter array(CFA) in which RGB color filters are arranged in a pattern on the sensor. Below figure shows a Bayer filter.

Source: Wikipedia

In the bayer filter, there are twice as many green elements as red or blue to mimic the human eye’s greater resolving power with the green light. In order to construct an RGB picture, we calculate Green and Blue values for each Red pixel, Blue and Red values for each Green pixel and Red and Green values for each Blue pixel through interpolation or color demosaicing algorithm (For more details See here).

Foveon X3 direct image sensor is the most advanced color image sensor. This combines the power of digital sensor with the essence of the film. Like the film, this has three layers of pixels embedded in silicon. The layers are positioned to take advantage of the fact that silicon absorbs red, green, and blue light to different depths. The bottom layer records red, the middle layer records green and the top layer records blue. Pros are superior quality and less processing power.

Now, you might have got some feeling about the Color image and how it is formed. 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.

Create own image using Numpy and OpenCV

In this tutorial, we will learn how we can create our own image using numpy and OpenCV. This will help you in understanding the image concepts more. Let’s see how the 256 intensity levels for an 8-bit image looks like.

Steps:

  1.  Create an array of any desired size using numpy. Always specify the ‘datatype’
  2.  Fill the values of the array using some logic
  3.  Show the image using cv2.imshow() or matplotlib.

Code:

The resulting image looks like this

To create a color image just specify the third dimension of the array (for example (100,256,3)) and rest is same.

Now, you are ready to create your own images. 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.

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.