Skip to content

Instantly share code, notes, and snippets.

@iKrishneel
Created October 4, 2022 00:03
Show Gist options
  • Save iKrishneel/a0727452ccf3300b1bce180306a3b590 to your computer and use it in GitHub Desktop.
Save iKrishneel/a0727452ccf3300b1bce180306a3b590 to your computer and use it in GitHub Desktop.
Finds the transformations between two images given the control points
#!/usr/bin/env python
import argparse
import numpy as np
import cv2 as cv
key = None
img = None
coordinates = {
'src': [],
'dst': [],
}
def mark_keypoints(event, x, y, flag, param):
global coordinates, key
if event == cv.EVENT_LBUTTONDOWN:
cv.circle(img, (x, y), 10, (0, 255, 0), -1)
coordinates[key].append([x, y])
def get_keypoints(image, name):
global key, coordinates, img
key = name
cv.namedWindow(key, cv.WINDOW_NORMAL)
cv.setMouseCallback(key, mark_keypoints)
img = image.copy()
while True:
cv.imshow(name, img)
k = cv.waitKey(20) & 0xFF
if k == 27:
break
img = None
return coordinates[key]
def main(args):
im_src = cv.imread(args.src)
im_dst = cv.imread(args.dst)
kp_src = get_keypoints(im_src, 'src')
kp_dst = get_keypoints(im_dst, 'dst')
kp_src, kp_dst = np.array(kp_src), np.array(kp_dst)
h, status = cv.findHomography(kp_src, kp_dst)
im_warp = cv.warpPerspective(im_src, h, im_dst.shape[:2][::-1])
im_out = cv.addWeighted(im_dst, 0.3, im_warp, 0.7, 0.0)
cv.destroyAllWindows()
cv.namedWindow('warp', cv.WINDOW_NORMAL)
cv.imshow('warp', im_out)
cv.waitKey(0)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--src', type=str, required=True)
parser.add_argument('--dst', type=str, required=True)
args = parser.parse_args()
main(args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment