Last active
April 5, 2020 14:40
-
-
Save emnak/8929ddd5248c2ce499540dfc1edeb085 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#%% Read and resize images | |
import numpy as np | |
import cv2 as cv | |
# Read images | |
train_img = cv.imread('train.png') | |
query_img = cv.imread('query.png') | |
# Resize images | |
train_img = cv.resize(train_img, dsize=(600, 950)) | |
query_img = cv.resize(query_img, dsize=(600, 950)) | |
#%% Detect keypoints | |
train_img_g = cv.cvtColor(train_img, cv.COLOR_BGR2GRAY) | |
query_img_g = cv.cvtColor(query_img, cv.COLOR_BGR2GRAY) | |
# Initiate AKAZE detector | |
akaze = cv.AKAZE_create() | |
# find the keypoints and descriptors with AKAZE | |
train_kp, train_des = akaze.detectAndCompute(train_img_g, None) | |
train_img_with_kp = cv.drawKeypoints(train_img, train_kp, None) | |
cv.imwrite('train_kp.jpg', train_img_with_kp) | |
query_kp, query_des = akaze.detectAndCompute(query_img_g, None) | |
query_img_with_kp = cv.drawKeypoints(query_img, query_kp, None) | |
cv.imwrite('query_kp.jpg', query_img_with_kp) | |
#%% Match keypoints | |
# BFMatcher with default params | |
bf = cv.BFMatcher(cv.NORM_HAMMING) | |
matches = bf.knnMatch(query_des, train_des, k=2) | |
# Apply ratio test | |
good_matches = [] | |
for m, n in matches: | |
if m.distance < 0.75 * n.distance: | |
good_matches.append([m]) | |
img_with_matches = cv.drawMatchesKnn(query_img, query_kp, train_img, train_kp, good_matches, None, | |
flags=cv.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS) | |
cv.imwrite('matches.jpg', img_with_matches) | |
#%% Warping | |
# Select good matched keypoints | |
train_matched_pts = np.float32([train_kp[m[0].trainIdx].pt for m in good_matches]) | |
query_matched_pts = np.float32([query_kp[m[0].queryIdx].pt for m in good_matches]) | |
# Compute homography | |
H, status = cv.findHomography(query_matched_pts, train_matched_pts, cv.RANSAC, 5.0) | |
# Warp image | |
warped_image = cv.warpPerspective(query_img, H, (query_img.shape[1], query_img.shape[0])) | |
cv.imwrite('warped_img.jpg', warped_image) | |
#%% Superposition | |
gray_warped_img = cv.cvtColor(warped_image, cv.COLOR_BGR2GRAY) | |
images_superposition = np.dstack((train_img_g, gray_warped_img, train_img_g)) | |
cv.imwrite("superposition.jpg", images_superposition) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment