Step-by-Step Guide to Using RANSAC in OpenCV using Python
Last Updated :
28 Jun, 2024
RANSAC (Random Sample Consensus) is an iterative method to estimate the parameters of a mathematical model from a set of observed data that contains outliers. In computer vision, it's often used for tasks like estimating the fundamental matrix, homography, or any fitting problem with noisy data.
In Python, OpenCV provides built-in support for RANSAC. Below, I'll show you how to use RANSAC with OpenCV to estimate a homography matrix from point correspondences between two images.
Step-by-Step Guide to Using RANSAC in OpenCV
Here's a detailed step-by-step guide on how to apply RANSAC in Python using OpenCV, specifically for estimating a homography matrix between two images.
Step 1 - Install OpenCV.
Python
pip install opencv-python
Step 2 - Import the required necessary libraries.
Python
import cv2
import numpy as np
Step 3 - Load Data - a set of points, an image pair, or data relevant to the problem.
Python
# Example: Load two images
img1 = cv2.imread('image1.jpg', 0)
img2 = cv2.imread('image2.jpg', 0)
Step 4 - Detect Key points and Descriptors.
Detecting key points involves identifying distinctive points in an image and descriptors are numerical representations of these keypoints' local neighbourhoods.
Python
# Using ORB detector
orb = cv2.ORB_create()
keypoints1, descriptors1 = orb.detectAndCompute(img1, None)
keypoints2, descriptors2 = orb.detectAndCompute(img2, None)
Step 5 - Match Descriptors.
It helps in identifying similar regions or objects across multiple images, which is crucial for tasks like image alignment and recognition.
Python
# Using BFMatcher
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
matches = bf.match(descriptors1, descriptors2)
matches = sorted(matches, key=lambda x: x.distance)
Step 6 - Apply RANSAC to Find Homography.
Technically, Projective – mapping between any two projection planes with the same centre of projection is called Homography.
Python
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)
H, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
Implementation of RANSAC in OpenCV
Combining all these steps, let us have a look at one basic example of this implementation by showing the homography matrix.
For this example, we used to GFG logos on grayscale called as image1 and image2.
image1.jpg
image2.jpg
Python
import cv2
import numpy as np
img1 = cv2.imread('image1.jpg', 0)
img2 = cv2.imread('image2.jpg', 0)
orb = cv2.ORB_create()
keypoints1, descriptors1 = orb.detectAndCompute(img1, None)
keypoints2, descriptors2 = orb.detectAndCompute(img2, None)
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
matches = bf.match(descriptors1, descriptors2)
matches = sorted(matches, key=lambda x: x.distance)
print("Number of keypoints in image 1:", len(keypoints1))
print("Number of keypoints in image 2:", len(keypoints2))
print("Number of matches found:", len(matches))
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)
H, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
print("Homography Matrix (H):")
print(H)
Output:
Number of keypoints in image 1: 137
Number of keypoints in image 2: 500
Number of matches found: 17
Homography Matrix (H):
[[-2.36968104e-01 -1.02475500e-01 1.47166550e+02]
[-6.91043155e-01 -2.22894760e-01 4.06596070e+02]
[-1.67955133e-03 -5.71908258e-04 1.00000000e+00]]
Explanation
- Feature Detection and Description:
- We use ORB (Oriented FAST and Rotated BRIEF) to detect keypoints and compute their descriptors.
- Feature Matching:
- We use BFMatcher (Brute Force Matcher) with the Hamming distance (appropriate for ORB descriptors) to find matches between the descriptors from the two images.
- RANSAC for Homography Estimation:
cv2.findHomography
is called with the method cv2.RANSAC
. The function returns the homography matrix H
and a mask indicating which matches were considered inliers by the RANSAC algorithm.
- Image Warping:
- We use the homography matrix
H
to warp the first image to align it with the second image.
Notes
- Parameter Tuning:
- The
cv2.RANSAC
method in cv2.findHomography
takes a reprojection error threshold as an argument (5.0 in this case). This parameter can be tuned based on your data.
- Alternative Methods:
- You can use other feature detectors and matchers like SIFT, SURF, or FLANN-based matcher depending on your requirements and data.
Using RANSAC with OpenCV is a powerful way to handle noisy data and outliers in computer vision tasks
Conclusion
The RANSAC algorithm is a highly effective tool in the field of computer vision that is used to work with noisy data and outliers. Due to it's iterative approach, even the presence significant noise allows for highly robust model fitting. The OpenCV implementation of RANSAC is simple but very powerful— thus finding use from different applications such as line fitting down to homography estimation.
Similar Reads
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read