OpenCV Python – Learn OpenCV with Python

In this OpenCV Python tutorial we are going to Learn OpenCV with Python,

we are going to start from the installation process and create different examples in

OpenCV with Python.

 

 

 

 

What is OpenCV ?

OpenCV (Open Source Computer Vision )is an open source library containing more

than 500 optimized algorithms for image and video analysis, OpenCV was developed

by intel, you can use OpenCV from displaying the feed of a webcam to teaching a robot

to recognize real life objects.

 

By OpenCV we can perform following actions

  • Read and write images
  • Face Detection using OpenCV
  • Text Recognition in Images using OpenCV
  • You can modify image quality and colors

 

 

Installation

You can install OpenCV for Python using pip.

 

 

 

 

Reading Image in Python OpenCV

Now we are going to create our first example and we want to read an image in OpenCV, this is the complete code for reading the image in opencv.

 

 

Using this code we can give a name for our window.

 

 

You can read image in OpenCV using imread() function.

 

 

For showing the image you can use imshow() function.

 

 

cv2.waitKey() is a keyboard binding function. Its argument is the time in milliseconds. The function waits specified milliseconds for any keyboard event. If you press any key in that time, the program continues. If 0 is passed, it waits indefinitely for a key stroke

 

 

Run the code and this is the result.

OpenCV Python - Learn OpenCV with Python
OpenCV Python – Learn OpenCV with Python

 

 

OpenCV Reading Image in Matplotlib 

Now we want to read our image using matplotlib, so Matplotlib is a plotting library for the Python programming language and its numerical mathematics extension NumPy. It provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits like Tkinter, wxPython, Qt, or GTK+. you can simply use pip for the installation.

 

 

 

OK now this is our code for reading image in matplotlib.

 

 

You can use imshow() method from matplotlib for showing the image.

 

 

If you want to hide tick values on X and Y axis than you can use this code.

 

 

 

Run the code and this is the result.

OpenCV Python - Learn OpenCV with Python
OpenCV Python – Learn OpenCV with Python

 

 

 

You can see a color difference in our image, it is because opencv renders the image in order of GBR, the reverse of  the usual RBG format.This is the reason the colors get messed up from OpenCV to matplotlib. The matplotlib module displays images according to the more conventional RGB method. Therefore, in order to correctly render images from OpenCV in matplotlib, what we need to do is convert the GBR image into a RGB image.

 

 

Using this code we have converted our GBR color to RGB.

 

 

 

Run the code and this is the result.

OpenCV Reading Image in Matplotlib
OpenCV Reading Image in Matplotlib

 

 

 

Writing Image in OpenCV

In this part we want to learn how to write image in OpenCV, this is the complete code for writing image in opencv.

 

 

So in here if user press escape key, we are going to close the window.

 

 

And if the user press s key we are going to save the image with a new name.

 

 

 

Python OpenCV Reading Videos 

In this part we are going to learn reading Mp4 video in OpenCV, so you can use an Mp4 video or you can use camera, the same code will be implemented with camera or Mp4 video, if you are using camera you need to give 0 in cap = cv2.VideoCapture(‘mp4vid.mp4’).

 

 

 

Python OpenCV Drawing Shapes

In this part we want to learn how you can draw different shapes in OpenCV, we will learn that how you can draw shapes like Line, Rectangle, Circle, Ellipse and Text. so this is the complete code for drawing different shapes.

 

 

 

In the above code first we have created a blank image using Numpy, so NumPy is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays.

 

 

Using this code you can create line in OpenCV, basically we are going to to create red line with thickness of 5 pixel.

 

 

You can use this code for creating of the rectangle in Python OpenCV, the first parameter is the image that we want to draw rectangle, after that you can give the x, y position and width, height, after that give the color and at the end give the thickness of line.

 

 

This is used for creating circle in OpenCV, you can give the image, center coordinates, radious, color and thickness for the circle.

 

 

If you want to draw ellipse than you can use this code, you need to give these parameters, center coordinates (x,y location), axes length (major and minor axes length), angle, start angle, end angle, color and thickness.

 

 

You can use this code for drawing text in OpenCV, you can give x, y position, font, color, thickness and type of the font.

 

 

 

Run the complete code and this is the result.

 Learn OpenCV with Python
Learn OpenCV with Python

 

 

 

Python OpenCV Mouse Clicks

In this part we want to learn how you can handle mouse clicks in OpenCV, basically we want when a user clicks on the window we are going to draw a circle, so this is the complete code for this part.

 

 

You can use this code for listing all available mouse events.

 

 

 

In this code we created a simple application which draws a circle on an image wherever we double click on it. first we create a mouse callback function which is executed when a mouse event take place. mouse event can be anything related to mouse like left-button down, left-button up, left-button double-click etc. It gives us the coordinates (x,y) for every mouse event. with this event and location, we can do whatever we like. Creating mouse callback function has a specific format which is same everywhere. It differs only in what the function does. So our mouse callback function does one thing, it draws a circle where we double-click. 

 

 

 

Run the complete code, double click on the window, you will see the circles.

Python OpenCV Mouse Events Drawing Circle
Python OpenCV Mouse Events Drawing Circle

 

 

 

Python OpenCV Creating Color Trackbar

In this part we want to create a simple color trackbar in opencv, for creating of color trackbar you can use createTrackbar() function. this is the complete code for creating color track bar in opencv.

 

In this example basically we want to create a simple application which shows the color you specify. You have a window which shows the color and three trackbars to specify each of B,G,R colors. You slide the trackbar and correspondingly window color changes. cv2.getTrackbarPos() function, first argument is the trackbar name, second one is the  window name to which it is attached, third argument is the default value, fourth one is the maximum value and fifth one is the callback function which is executed every time trackbar value changes. The callback function always has a default argument which is the trackbar position. In our case, function does nothing, so we simply pass.

 

 

Run the complete code and this will be the result 

Python OpenCV Color Track Bar
Python OpenCV Color Track Bar

 

 

 

OpenCV Arithmetic Operation

Using Arithmetic Operations We can apply operations like addition, subtraction, Bitwise Operations, so there are two ways, the first way is manually and the second way is using the functions that are available for opencv.

 

 

OK now we want to add and subtract two images manually.

 

 

So you can see that we have manually added and subtracted the two images.

 

 

If you run the complete code you will see strange result, and it is not the result that you expect.

Python OpenCV Arithmetic Operation Manually
Python OpenCV Arithmetic Operation Manually

 

 

 

OK now let’s use built in functions of OpenCV for arithmetic operations, so we are using  add() and also subtract() methods from OpenCV.

So you can see that in the above code we have used add() and also subtract() methods  from opencv.

 

 

 

Run the code and you will see the expected result, and it is better than first result.

OpenCV Arithmetic Operations
OpenCV Arithmetic Operations

 

 

 

OpenCV Image Blending 

Image blending is also a type of image addition, but we can add different weights to the images. You can use cv2.addWeighted() method of OpenCV for image blending. Here are two images to blend them together. First image is given a weight of 0.9 and second image is given 0.5, the last value is the gamma value and we use cv2.addWeighted() for blending the images.

 

 

 

Run the code and this is the result.

Python OpenCV Image Blending
Python OpenCV Image Blending

 

 

 

How to Change Color Space in OpenCV

There are more than 150 color-space conversion methods available in OpenCV. But we will look into some of them, BGR↔Gray and BGR↔HSV. in OpenCV you can use cv2.cvtColor() for converting color spaces.

You can see in the above code we have used three color spaces, and we have converted vice versa.

 

 

 

Run the code and this is the result.

OpenCV Python - Learn OpenCV with Python
OpenCV Python – Learn OpenCV with Python

 

 

 

Python OpenCV BitWise Operations

bitwise operations includes AND, OR, NOT and XOR operations, these operations are very useful when we want to extract any part of the image. these are the operations that we have  cv2.bitwise_and(img1, img2), cv2.bitwise_or(img1, img2), cv2.bitwise_xor.

 

 

 

First you need to create two images with rectangle and circle, you can use Numpy for creating blank image.

 

 

 

Run the code and this is the result.

OpenCV Python - Learn OpenCV with Python
OpenCV Python – Learn OpenCV with Python

 

 

 

How to Rotate Image in OpenCV

we can rotate an image in opencv using rotate() function there are three constants that you can use as parameter.

 

cv2.ROTATE_90_CLOCKWISE
cv2.ROTATE_90_COUNTERCLOCKWISE
cv2.ROTATE_180

 

 

 

This is the three rotations that we are going to use in opencv.

 

 

In here we are going to convert our BGR colors to RGB.

 

 

Also we show the images in Matplotlib, so Matplotlib is a plotting library for the Python programming language and its numerical mathematics extension NumPy. It provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits like Tkinter, wxPython, Qt, or GTK+.

 

 

 

Run the complete code and this is the result.

Python OpenCV Rotating Image
Python OpenCV Rotating Image

 

 

 

Image Filtering in OpenCV

In this part we are going to talk about 2D Convolution or image filtering, you can do image filtering using low pass filter (LPF) and high pass filters (HPF). for example if you want to remove the noises of the image you can use LPF filter or if you want to blur an image you can use LPF. and using HPF filter you can find the edges in the image. in OpenCV there is a function cv2.filter2D() that is used for filtering.

 

 

In this example we are going to use a 5 by 5 averaging filter kernel.

 

 

So in the above example first we have created a 5 x 5 kernel.

 

 

After that we have created our cv2.filter2D() method, you need to give the image, ddepth and kernel as parameter.

 

 

After that we need to convert our original and filtered image from BGR color to RGB. because by default OpenCV uses BGR color and we need RGB color, if we don’t convert the image, there will be messed up in the color.

 

 

After that we are going to show our images in Matplotlib and we are using two subplots.

 

 

 

Run the complete code and this is the result.

Python OpenCV Image Filtering
Python OpenCV Image Filtering

 

 

 

OpenCV Image Blurring

Image blurring or image smoothing is used for removing image noises and it is used for removing high frequency contents like noise and edges. according to documentation there are four types of blurring techniques in OpenCV. Averaging, Gaussian Blurring, Median  Blurring and Bilateral Filtering.

 

Average Blurring

In average blurring we takes the average of all pixels under the kernel area and replace them with central element with this average. and this is done in OpenCV by using cv2.blur() function.

 

You can see that we have used cv2.blur() method, and you need to give the image and the kernel size as parameter. also in the above code we have converted our image from BGR to RGB and at the end we have showed the image using Matplotlib library. 

 

 

Run the code and this is the result.

OpenCV Average Blurring
OpenCV Average Blurring

 

 

Gaussian Filtering 

The second technique for smoothing the image is Gaussian Filtering in this technique we need to specify width and height of the kernel which should be positive and odd. also we need to add standard deviation in the x and y directions. sigmax and sigmay. you can use cv2.GaussianBlur() for this in opencv.

 

In the above code we have used cv2.GaussianBlur() method, and you need to give the image and the kernel size as parameter. also in the above code we have converted our image from BGR  to RGB and at the end we have showed the image using Matplotlib library.

 

 

 

Run the code and this is the result.

OpenCV Gaussian Filtering
OpenCV Gaussian Filtering

 

 

Median Blurring 

Median Blurring computes the median of all pixels under the kernel and the central pixel is replaced with the median value, according to OpenCV documentation it is mostly used for removing salt and pepper noises.

 

In the above code we have used cv2.medianBlur() method, and you need to give the image and the median as parameter. also in the above code we have converted our image from BGR  to RGB and at the end we have showed the image using Matplotlib library.

 

 

 

Run the complete code and this is the result.

OpenCV Median Blurring
OpenCV Median Blurring

 

 

Bilateral Filtering 

A bilateral filter is non-linear, edge-preserving and noise-reducing smoothing filter. The intensity value at each pixel in an image is replaced by a weighted average of intensity values from nearby pixels. This weight can be based on a Gaussian distribution.

 

 

So this is the syntax.

 

Name Description 
SRC It is the source image
DST It is the destination or output image
D A variable of the type integer representing the diameter of the pixel neighborhood.
SIGMACOLOR A variable of the type integer representing the filter sigma in
the color space
SIGMASPACE A variable of the type integer representing the filter sigma in the coordinate space

 

 

So this is the complete code.

 

 

 

Run the code and this is the result.

OpenCV Bilateral Filtering
OpenCV Bilateral Filtering

 

 

 

Python OpenCV Image Pyramid

Image Pyramid is one the best concepts of the image processing, so when we are going to work with the images that is high resolution images. sometimes we need to work with images of different resolution of the same image like low resolution images. and we create the different resolution of the same image, now this is called pyramid in OpenCV, or we can say Image pyramid refers to the way of representing an image at multiple resolutions. so there are two functions that we can use pyrup() function increases the size to double of its original size, pyrdown() function decreases the size to half.

 

 

You can see that using cv2.pyrdown() method we have created different resolution images, as i have already said that pyrdown() function decreases the size to half.

 

 

Now run the code, along with the original image we have two new resolution images.

Python OpenCV Image Pyramid
Python OpenCV Image Pyramid

 

 

Leave a Comment