Amazing Applications of OpenCV in Python
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.
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
Best-suited Machine Learning courses for you
Learn Machine Learning with these high-rated online courses
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 cv2import numpy as npfrom google.colab.patches import cv2_imshow
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 imageimg = cv2.imread('image.jpg') # Enter the path of the image
# Convert the image to HSV color spacehsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# Define the lower and upper bounds for the color rangel_b = np.array([0, 0, 220])u_b = np.array([255, 255, 255])
# Create a mask using the color rangemask = cv2.inRange(hsv, l_b, u_b)
# Inpaint the image using the maskdst = 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 imagecv2_imshow(img)
# Display the inpainted imagecv2_imshow(dst)
# Press any key to close the windowscv2.waitKey(0)cv2.destroyAllWindows()
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.
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 imagesimage1 = cv2.imread('1.jpg')image2 = cv2.imread('2.jpg')# Convert the images to grayscalegray1 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)gray2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)
# Perform feature detection and descriptionsift = cv2.SIFT_create()keypoints1, descriptors1 = sift.detectAndCompute(gray1, None)keypoints2, descriptors2 = sift.detectAndCompute(gray2, None)
# Perform feature matchingmatcher = cv2.BFMatcher(cv2.NORM_L2, crossCheck=True)matches = matcher.match(descriptors1, descriptors2)
# Sort the matches by distancematches = sorted(matches, key=lambda x: x.distance)
# Select the top N matchesN = 100matches = matches[:N]
# Extract the matched keypointssrc_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 matrixM, _ = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
# Warp image 1 to image 2's perspectiveresult = cv2.warpPerspective(image1, M, (image1.shape[1] + image2.shape[1], image1.shape[0]))
# Combine the warped image with image 2result[0:image2.shape[0], 0:image2.shape[1]] = image2
# Display the resultcv2_imshow(result)cv2.waitKey(0)cv2.destroyAllWindows()
Output:
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 detectorhog = cv2.HOGDescriptor()hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())
# Load the input imageimage = cv2.imread('5.jpg')
# Resize the image for faster processingimage = cv2.resize(image, (640, 480))
# Detect people in the imageboxes, weights = hog.detectMultiScale(image, winStride=(8, 8), padding=(4, 4), scale=1.05)
# Draw bounding boxes around the detected peoplefor (x, y, w, h) in boxes: cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
# Display the output imagecv2_imshow(image)cv2.waitKey(0)cv2.destroyAllWindows()
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.
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