OpenCV Python Tutorial: A Guide to Learn OpenCV
By: Haider Imtiaz
Tags: Programming, Coding, Computer Vision, Bots, Python

Computer vision is the interdisciplinary field that deals with gaining high-level understanding from images and video. If we see it from an engineering perspective it is used to automate tasks that human vision can do. Like recognizing a specific part in images, making differences in images, and understanding things that a human brain can think about after visualizing an object. During these modern days, computer vision is useful in Artificial intelligence and robot programming in which we need a human vision technique to recognize the surroundings and take the action according to that. In programming languages, we had many modules to work with computer vision but the famous one is OpenCV. It is a library of programming functions mainly aimed at real-time computer vision. Originally developed by Intel, it was later supported by Willow Garage then Itseez. That language is made in use C++/C language and which makes it easy faster and easy to use. We will work through how we can use the OpenCV module in python and learn some crazy stuff that OpenCV can do.

Installation:

You need the latest version of python, you can download it from the python official website and later on copy the following code and paste it into the command prompt and it will automatically install the python-OpenCV module in your system.

pip install opencv-python

Basics of OpenCV:

loading image:

In Order to read an image from your disk in the OpenCV, you need to used the cv2.imread function which will read the image in RGB format.

We had loaded the module of python-OpenCV name cv2 then used cv2.imread function and passing the image name we want to read. The image could be in any image format png, jpeg, jpg, etc.

Displaying Image:

Displaying an image in the python-OpenCV is easy like reading the image for that we used cv2.imshow the method by passing the image that we read and after that we used cv2.waitKey method to make the program wait for showing us the image for that we pass the integer value representing seconds in the cv2.waitKey and next, we used cv2.destroyAllWindows method to destroy the open window that showing us the image.

Writing Image :

Writing image in python-OpenCV used a method cv2.imwrite() which take two parameters one is the image we read in OpenCV and the second is the name of the image with its extension we want to output.

Image Processing:

Image Resizing:

Image Resizing is referring to as scaling of the image, it is come in handy when you want to decrease the size of the image by lowering its pixels. As we know the pixels are spread like X and Y coordinates of the image so we can use that X and Y points to tell the OpenCV to reduce the pixels and resize the image.

We had import the cv2 module which is called python-OpenCV module and next we had read the image called python.png and setting the scale_precent to 60 % because we are going to downscale our image to 60% and next reduce the height and width of the images by multiplying it with scaling_percent and divide by 100, And next we had used the cv2.resize() function bypassing the image that we read and the new dimension.

Blurring an Image:

Now we will make our image blurry by using OpenCV blurring technique. OpenCV module had 3 blurring techniques Gaussian Blurring, Median Blurring, Bilateral Filtering.

If you had seen the Code we had used 4 different functions cv2.blur which is the simple averaging blur mode, cv2.GaussianBlur , cv2.MedianBlurr , cv2.bilateralFilter blur, one thing is common in all of these blur technique is the kernel size we are passing as an argument with the image on which we are applying the blur filter. A Kernel tells you how to change the value of any given pixel by combining it with different amounts of the neighboring pixels.

Grayscaling an Image:

Grayscalling an image is the process of converting an image of other color spaces like RGB, CYMK to shades of grey, as it varies between black and white colors. Grayscalling is useful when you want to train an artificial intelligence against an image or you want to lower the difficulty of recognizing an image because when we lowered the image to gray scaling it became one channel of color but in RGB mode it has 3 color channel considered an example you want to train a neural image with 10x10x3 size in RGB mode it will have 300 layer nodes and the same image with gray scaling will have 100 layer nodes. There are many benefits of image gray scalings like reducing noise for reading text, edge detection and etc.

We use cvtColor() , to convert the image to grayscale bypassing the image variable name and the cv2.COLOR_BGR2GRAY the method in it.

Create Border around Images:

In the OpenCV module, we used cv2.copyMakeBorder() a function to make a border around the image same as the Frame of an image. Check the below code

Edge Detection:

Processing of image detection involves the detection of sharp edges of the image. This edge detection is essential in the context of image recognition or object detection. There are several algorithms for detecting edges due to their wide applicability. We’ll be using one such algorithm known as Canny Edge Detection.

So if you had seen the code we had used imread() the function again to read the image and the next line we had used the cv2.Canny by passing the image we are using and the size of the pixels we to detect. The dimension we pass is in the width x height format.

Simple Thresholding:

Thresholding is the technique in OpenCV to the assignment of the pixel value to the threshold value. In thresholding, each pixel value is compared with the threshold value. If the pixel value is smaller than the threshold, it is set to 0, otherwise, it is set to a maximum value (generally 255). In Computer Vision, this technique of thresholding is done on grayscale images. So initially, the image has to be converted in grayscale color space. The basic Thresholding technique is Binary Thresholding. For every pixel, the same threshold value is applied. If the pixel value is smaller than the threshold it is set to 0 otherwise it is set to a maximum value.

In python OpenCV we used cv2.threshold function by passing the image we are working pixels value and setpoint and 4th argument will be the mode of the threshold. If you see the code line 14–16 we are setting the 3 types of threshold mode Binary, Trunc, and Tozero, and also we selecting if the pixels value of the image is 120 then set it to 255.

Image Inpainting using OpenCV:

Image impainting is a technique to repair the damaged photos, or noise, stroke text in the photos. It is particularly useful to recover the old photos that had scratches or some ink spots. Image inpainting usually works by replacing the dead pixels with their neighboring similar ones, therefore making it blend with the background. In python openCv, we used cv2.inpaint method using two modes of inpainting FMM (Fast Marching Method ) and Navier-Strokes. we can use cv2.INPAINT_TELEA it for FMM and cv2.INPAINT_NS for Navier-stroke.

If you had seen eh code I had also read an image of mask.png its a black cover image that will work as a mask on which any damaged pixel will appear in white color and then OpenCV can replace it with the matching surrounding pixels.

Image Translation:

Translation refers to the rectilinear shift of an object i.e. an image from one location to another. If we know the amount of shift in horizontal and the vertical direction, say (tx, ty) then we can make a transformation matrix.

where tx denotes the shift along the x-axis and ty denotes shift along the y-axis i.e. the number of pixels by which we need to shift about in that direction.

Now, we can use the cv2.wrapAffine() function to implement these translations.

Benefits of Translation:

Hiding a part of the image

Cropping an image

Shifting an image to any point

Animating an image using image translations in a loop.

I made two new variables name quarter height and quarter width because we will translate our image to that height and width and then on the next line I had used np.float which is a NumPy function to convert our image in 2x3 format and then used the warpAffine function by passing the 2x3 image dimension. Take a test on any image and see the difference.

We had learned the basics of OpenCV and see their image processing methods how we can use them but its not the end of OpenCV feature you can read the OpenCV official documentation which had a lot of function that you can use to make image edit bot, artificial intelligence, solving daily problems and etc. I hope you learn something from this article and this article will help you someday, Feel free to leave your feedback.