Image Processing Using OpenCV library in Python (Basics)
By: Panisetti Prudhviraj
Tags: Image Processing, Python, Canny Edge Detection, Opencv, Edge Detection

Today, we are going to discuss few basic operations which can be performed on images using OpenCv library in Python. Starting from the Installation of Python 3 in Windows and executing the basic operations in the python script.

Image Processing with python using OpenCv

Basically, Image processing is the technical analysis of an image, Like preforming some operations in-order to get an enhanced image/ or to extract some useful information.

As we move on, a lot of applications uses images/frames/videos as an inputs which needs pre-processing them and feeding them to the device or softwares or Scripts.

Applications

Image processing can be entertaining and can be used for many applications.

It can be used to resize the images to fit into our web pages as per the required sizes and can sharpen them to bring out certain features Older black and white images can be brought into colour photos or the latest colour photos can be made to look like old black and white phots using colorization techniques It can be used to enhance medical imaging to screening patients for cancer or other diseases.

Basic Image processing techniques

In this article, we are going to see the functions that read the images from directory, modifies them and stores them in another directory. Below are the main things we are going to discuss.

Read the Image using Python and OpenCV

Resize the Image using OpenCV

Blur/Smoothing the Image

Sharpen the Image

Edge detection algorithm (Canny)

Basic Requirements & Installation:

A Computer/PC/Laptop with Windows Python Software : Can be downloaded and installed as procedure mentioned here. (Mostly try to download and Install latest version from here) If you have not already done so, Download and install VS Code. Next, install the Python extension for VS Code from the Visual Studio Marketplace. The Python extension is named Python and it’s published by Microsoft. Install opencv-python (which is an unofficial pre-built OpenCV package for Python) by issuing the following command in CMD (Command Prompt):

pip install PACKAGE_NAME

where PACKAGE_NAME can be

opencv-python (only contains main modules)

(only contains main modules) opencv-contrib-python (contains both main and contrib modules)

(contains both main and contrib modules) opencv-python-headless (same as opencv-python but without GUI functionality)

(same as but without GUI functionality) opencv-contrib-python-headless (same as opencv-contrib-python but without GUI functionality)

Once the setup is done,

Open a directory and create a folder “Image_Processing”. Download few images (3–4 images) and save in this folder. Create a Python Script file “Test_img_processing.py”(.py is an extension of python scripts)

Implementation & Execution :

Now you are free to use python script. Always start the script with Importing the libraries required. Below are the functions to do the basic image processing.

To read an image, we have a function “imread()”, which takes the image file name as a string and a flag

cv2.imread(/complete/path/to/image,flag) First argument is complete path to the image along with the extension. Second argument is an optional flag which could be any one of the following : cv2.IMREAD_COLOR : Loads a color image. Any transparency of image will be neglected. It is the default flag. cv2.IMREAD_GRAYSCALE : Loads image in grayscale mode cv2.IMREAD_UNCHANGED : Loads image as such including alpha channel Returns numpy array, containing the pixel values. For colored images, each pixel is represented as an array containing Red, Green and Blue channels. Note that the default flag is cv2.IMREAD_COLOR. Hence even if read a png image with transparency, the transparency channel is neglected.

2. To Display the read image, we use “imshow()”

cv2.imshow(window_name, image) First argument is name of the window that is displayed when image is shown. Second argument is the image to be shown in the window.

3. To save the image which we read into another directory, we use “imwrite()”, which takes the destination and the image file.

cv2.imwrite(‘/path/to/destination/image.png’,image) First Argument is Path to the destination on file system, where image is ought to be saved. Second Argument is ndarray containing image Returns True is returned if the image is written to file system, else False.

4. To get the dimensions of an image, we have a property called shape

img = cv2.imread(‘/home/img/python.png’, cv2.IMREAD_UNCHANGED)

# get dimensions of image

dimensions = img.shape

# height, width, number of channels in image

height = img.shape[0]

width = img.shape[1]

channels = img.shape[2]

img.shape returns (Height, Width, Number of Channels) Height represents the number of pixel rows in the image or the number of pixels in each column of the image array. Width represents the number of pixel columns in the image or the number of pixels in each row of the image array. Number of Channels represents the number of components used to represent each pixel.

5. To Blur the image, we use “cv2.blur()”, which takes the image file and the kernel filter. This is called “Averaging”. There are other options as well:

— Gaussian Blurring

— Median Blurring

— Bilateral Filtering

Example Script with all the basic functionalities:

# importing opencv CV2 module

import cv2

# bat.jpg is the batman image.

img = cv2.imread(‘bat.jpg’)

# make sure that you have saved it in the same folder

# Averaging

# You can change the kernel size as you want

Averaging_blur= cv2.blur(img,(10,10))

cv2.imshow(‘Averaging’,Averaging_blur)

cv2.waitKey(0)#waits for the window to close

# Gaussian Blurring

# Again, you can change the kernel size

Gaussian_Blur= cv2.GaussianBlur(img, (5,5),0)

cv2.imshow(‘Gaussian Blurring’, Gaussian_Blur)

cv2.waitKey(0)#waits for the window to close

# Median blurring

Median_Blur= cv2.medianBlur(img,5)

cv2.imshow(‘Median Blurring’, Median_Blur)

cv2.waitKey(0)#waits for the window to close

# Bilateral Filtering

Bilateral_Filter= cv2.bilateralFilter(img,9,75,75)

cv2.imshow(‘Bilateral Filtering’, Bilateral_Filter)

cv2.waitKey(0) #waits for the window to close

cv2.destroyAllWindows()# closes all the open windows in this session

6. To detect the edges of the image, we use the popular canny edge detection algorithm . OpenCV has in-built function cv2.Canny() which takes our input image as first argument and its aperture size(min value and max value) as last two arguments.

edges = cv2.Canny(frame,100,200) # Display edges in a frame cv2.imshow('Edges',edges)

And there are many more operations and open algorithms to perform specific functionalities to images using opencv and python, which can be very easy and flexible to implement in real time videos/frames.