Tag Archives: cv2

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.

Intensity Transformation

Intensity transformation as the name suggests, we transform the pixel intensity value using some transformation function or mathematical expression.

Intensity transformation operation is usually represented in the form

s = T(r)

where, r and s denotes the pixel value before and after processing and T is the transformation that maps pixel value r into s.

Basic types of transformation functions used for image enhancement are

  • Linear (Negative and Identity Transformation)
  • Logarithmic (log and inverse-log transformation)
  • Power law transformation

The below figure summarize these functions. Here, L denotes the intensity value (for 8-bit, L = [0,255])


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

This is a spatial domain technique which means that all the operations are done directly on the pixels. Also known as a point processing technique (output depend only on the single pixel) as opposed to neighborhood processing techniques(like filtering) which we will discuss later.

Applications:

  • To increase the contrast between certain intensity values or image regions.
  • For image thresholding or segmentation

In the next blog, we will discuss these different transformation functions in detail. 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.

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.

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.