Amazing Applications of OpenCV in Python

Amazing Applications of OpenCV in Python

4 mins read681 Views Comment
Updated on Feb 1, 2024 17:28 IST

This article provides a detailed overview of popular OpenCV applications, such as image inpainting, image stitching, and object detection. We also provide each application's Python code and a proper explanation to help you understand the process. By the end of this article, you will better understand these OpenCV applications and how they can be implemented with Python code.

2023_06_Feature-Image-Templates-1-1.jpg

OpenCV (Open Source Computer Vision) is an open-source library of computer vision and image processing algorithms. It provides a wide range of functions and tools that enable developers to build powerful applications for various domains, including image processing, object detection, image stitching, image inpainting and more. We have already covered basic applications of OpenCV with Python code in a previous blog- OpenCV Python: Beginner’s Guide.

In this article, we will explore some amazing applications of OpenCV and provide Python code snippets to demonstrate their implementation. Let’s dive into a few notable applications.

Table of Content

Recommended online courses

Best-suited Machine Learning courses for you

Learn Machine Learning with these high-rated online courses

2.5 L
2 years
2.5 L
2 years
1.53 L
11 months
34.65 K
11 months
– / –
8 hours
5.6 L
18 months
– / –
6 months

What is OpenCV?

OpenCV is an open-source computer vision library. This gives machines the ability to recognize faces and objects. In this tutorial, you will learn his OpenCV concepts using Python. OpenCV is a widely recognized open-source library that provides a rich suite of computer vision and image processing functions. It offers a wide range of tools and technologies that enable developers to create cutting-edge applications in areas such as robotics, augmented reality, facial recognition, object recognition, and more. OpenCV has become the top choice for developers worldwide due to its powerful features and user-friendly interface.

Explore: Opencv Online Courses & Certifications

Applications of OpenCV with Python Code

1. Image Inpainting


 
import cv2
import numpy as np
from google.colab.patches import cv2_imshow
Copy code

The code imports the OpenCV library as cv2, the NumPy library as np, and the cv2_imshow function from the google.colab.patches module. The cv2_imshow function is used to display images in a Colab notebook.


 
# Read the image
img = cv2.imread('image.jpg') # Enter the path of the image
# Convert the image to HSV color space
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# Define the lower and upper bounds for the color range
l_b = np.array([0, 0, 220])
u_b = np.array([255, 255, 255])
# Create a mask using the color range
mask = cv2.inRange(hsv, l_b, u_b)
# Inpaint the image using the mask
dst = cv2.inpaint(img, mask, 5, cv2.INPAINT_TELEA)
# dst = cv2.inpaint(img, mask, 5, cv2.INPAINT_NS) # Alternatively, you can use this line for inpainting
# Display the original image
cv2_imshow(img)
# Display the inpainted image
cv2_imshow(dst)
# Press any key to close the windows
cv2.waitKey(0)
cv2.destroyAllWindows()
Copy code

Output:

Explanation:

l_b = np.array([0, 0, 220]) 

u_b = np.array([255, 255, 255])

The code defines the lower bound (l_b) and upper bound (u_b) for the colour range. These values represent the minimum and maximum HSV values for the desired color.inRange(hsv, l_b, u_b)-Create the mask using color range. cv2.destroyAllWindows() destroys all OpenCV windows.

10 Computer Vision Projects Ideas For Beginners
OpenCV python: Beginner’s guide
Face detection using OpenCV

You can also read

Must Read: Top 10 Powerful Python Libraries for Data Science

Must Check: Top Python Online Courses and Certifications

Must Read: What is Python

2. Image Stitching

Image or photo stitching combines multiple photographic images with overlapping fields of view to create a segmented panorama or high-resolution image. Most image stitching techniques are typically performed using computer software and require nearly exact overlap and identical exposure between images to achieve seamless results.


 
# Load the input images
image1 = cv2.imread('1.jpg')
image2 = cv2.imread('2.jpg')
# Convert the images to grayscale
gray1 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
gray2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)
# Perform feature detection and description
sift = cv2.SIFT_create()
keypoints1, descriptors1 = sift.detectAndCompute(gray1, None)
keypoints2, descriptors2 = sift.detectAndCompute(gray2, None)
# Perform feature matching
matcher = cv2.BFMatcher(cv2.NORM_L2, crossCheck=True)
matches = matcher.match(descriptors1, descriptors2)
# Sort the matches by distance
matches = sorted(matches, key=lambda x: x.distance)
# Select the top N matches
N = 100
matches = matches[:N]
# Extract the matched keypoints
src_pts = np.float32([keypoints1[m.queryIdx].pt for m in matches]).reshape(-1, 1, 2)
dst_pts = np.float32([keypoints2[m.trainIdx].pt for m in matches]).reshape(-1, 1, 2)
# Compute the homography matrix
M, _ = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
# Warp image 1 to image 2's perspective
result = cv2.warpPerspective(image1, M, (image1.shape[1] + image2.shape[1], image1.shape[0]))
# Combine the warped image with image 2
result[0:image2.shape[0], 0:image2.shape[1]] = image2
# Display the result
cv2_imshow(result)
cv2.waitKey(0)
cv2.destroyAllWindows()
Copy code

Output:

2023_06_6.jpg

Explanation:

Function Purpose
cv2.cvtColor() Convert an image from one color space to another, such as BGR to grayscale.
cv2.SIFT_create() Create a SIFT (Scale-Invariant Feature Transform) object for feature detection and description.
sift.detectAndCompute() Detect key points and compute descriptors using the SIFT algorithm.
cv2.BFMatcher() Create a Brute-Force Matcher object for feature matching.
bf.match() Perform feature matching between two sets of descriptors.
sorted() Sort a list or iterable based on a given key or criteria.
np.float32() Convert an array to the float32 data type.
cv2.findHomography() Compute the homography matrix using RANSAC algorithm for robust estimation.
cv2.warpPerspective() Apply a perspective transformation to an image using a given homography matrix.
cv2.addWeighted() Combine two images with a specified weight to create a blended result.
cv2.waitKey() Wait for a key press in the OpenCV window.
 

3. Object Detection

Object recognition is a computer vision task to detect and locate interesting objects in images or videos. The task is to identify the location and boundaries of objects in the image and classify the objects into different categories.


 
import cv2
# Load the pre-trained HOG object detector
hog = cv2.HOGDescriptor()
hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())
# Load the input image
image = cv2.imread('5.jpg')
# Resize the image for faster processing
image = cv2.resize(image, (640, 480))
# Detect people in the image
boxes, weights = hog.detectMultiScale(image, winStride=(8, 8), padding=(4, 4), scale=1.05)
# Draw bounding boxes around the detected people
for (x, y, w, h) in boxes:
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
# Display the output image
cv2_imshow(image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Copy code

Output:

Explanation:

The image is loaded by cv2.imread(‘5.jpg’). The image file should be loaded in Google Colab before reading. The image is then resized to a fixed size of (640, 480) using cv2.resize() for faster processing.

The HOG object detector is instantiated using the cv2.HOGDescriptor() constructor. This detector is specifically trained to recognize human-like objects. It contains parameters like:

  • winStride: The sliding window step size during the detection process.
  • padding: The amount of padding added to the image during detection.
  • scale: The scale factor for multi-scale detection.

Draw bounding boxes around the detected objects using cv2.rectangle() where they have top-left corner coordinates (x, y), the bottom-right corner coordinates (x + w, y + h), and the colour (0, 255, 0).

FAQs

What are some common applications of OpenCV?

OpenCV finds applications in various fields, including image and video processing, object detection and tracking, facial recognition, augmented reality, robotics, medical imaging, surveillance, and autonomous vehicles.

How does OpenCV support deep learning?

OpenCV has integration with deep learning frameworks like TensorFlow and PyTorch. It allows users to load pre-trained deep learning models and perform tasks like image classification, object detection, semantic segmentation, and style transfer. OpenCV provides functions to preprocess images, feed them into the models, and interpret the output.

Is OpenCV suitable for real-time applications?

Yes, OpenCV is designed to handle real-time processing. It leverages hardware optimizations and parallel computing to achieve high performance. OpenCV supports accessing video streams from cameras, processing frames in real-time, and displaying results with minimal latency.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio