Skip to content

Instantly share code, notes, and snippets.

@OlafenwaMoses
Created August 31, 2019 01:05
Show Gist options
  • Save OlafenwaMoses/6736bf80beb285206209d27a9852f1b4 to your computer and use it in GitHub Desktop.
Save OlafenwaMoses/6736bf80beb285206209d27a9852f1b4 to your computer and use it in GitHub Desktop.
Feature Mapping using OpenCV's ORB detector and Brute-force Matching
import cv2
image1 = cv2.imread("1.jpg")
# Loaded first image in full color
image2 = cv2.imread("2.jpg")
# Loaded second image in full color
image1_gray = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
# Created gray version of first image
image2_gray = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)
# Created gray version of second image
orb_detector = cv2.ORB_create()
#created our ORB(Oriented FAST and Rotated BRIEF) detector
key_points1, descriptors1 = orb_detector.detectAndCompute(image1_gray, None)
# obtained key points and descriptions for first gray image
key_points2, descriptors2 = orb_detector.detectAndCompute(image2_gray, None)
# obtained key points and descriptions for second gray image
brute_force_matcher = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck= True)
# Created OpenCV brute force matcher instance with a average hamming distance value of 6 (cv2.NORM_HAMMING = 6)
matches = brute_force_matcher.match(descriptors1, descriptors2)
# Computed the matches across the descriptors of the two gay images
matches = sorted(matches, key = lambda x:x.distance)
# Sorted the matches in order of their hamming distance
new_image = cv2.drawMatches(image1, key_points1, image2, key_points2, matches[:10], outImg=None, flags=2)
"""
Created a new image by
- combining the two original colored images with the corresponding key_points of their gray versions
i.e image1, key_points1, image2, key_points2 . Note that you can combine with the gray images instead too
- display only the top 10 connect points, can be greater or lesser values
i.e matches[:10]
- set a None value for 'outImg'
"""
# The code below displays the new image
# Image can be displayed using Matplotlib's PyPlot as well.
cv2.imshow("Window1", new_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
@OlafenwaMoses
Copy link
Author

See the example images for the code

2
1

@OlafenwaMoses
Copy link
Author

You should see result like the one below.

result

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment