1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
| import cv2 import numpy as np def stitch_image(img1, img2, H): h1, w1 = img1.shape[:2] h2, w2 = img2.shape[:2] img1_dims = np.float32([[0,0], [0, h1], [w1, h1], [w1, 0]]).reshape(-1, 1, 2) img2_dims = np.float32([[0,0], [0, h2], [w2, h2], [w2, 0]]).reshape(-1, 1, 2) img1_transform = cv2.perspectiveTransform(img1_dims, H) result_dims = np.concatenate((img2_dims, img1_transform), axis=0) [x_min, y_min] = np.int32(result_dims.min(axis=0).ravel()-0.5) [x_max, y_max ] = np.int32(result_dims.max(axis=0).ravel()+0.5) transform_dist = [-x_min, -y_min] transform_array = np.array([[1, 0, transform_dist[0]], [0, 1, transform_dist[1]], [0, 0, 1]]) result_img = cv2.warpPerspective(img1, transform_array.dot(H), (x_max-x_min, y_max-y_min)) result_img[transform_dist[1]:transform_dist[1]+h2, transform_dist[0]:transform_dist[0]+w2] = img2 return result_img def get_homo(img1, img2): sift = cv2.xfeatures2d.SIFT_create() k1, d1 = sift.detectAndCompute(img1, None) k2, d2 = sift.detectAndCompute(img2, None) bf = cv2.BFMatcher() matches = bf.knnMatch(d1, d2, k=2) verify_ratio = 0.8 verify_matches = [] for m1, m2 in matches: if m1.distance < 0.8 * m2.distance: verify_matches.append(m1) min_matches = 8 if len(verify_matches) > min_matches: img1_pts = [] img2_pts = [] for m in verify_matches: img1_pts.append(k1[m.queryIdx].pt) img2_pts.append(k2[m.trainIdx].pt) img1_pts = np.float32(img1_pts).reshape(-1, 1, 2) img2_pts = np.float32(img2_pts).reshape(-1, 1, 2) H, mask = cv2.findHomography(img1_pts, img2_pts, cv2.RANSAC, 5.0) return H else: print('err: Not enough matches!') exit()
img1 = cv2.imread('map1.png') img2 = cv2.imread('map2.png')
img1 = cv2.resize(img1, (640, 480)) img2 = cv2.resize(img2, (640, 480)) inputs = np.hstack((img1, img2))
H = get_homo(img1, img2)
result_image = stitch_image(img1, img2, H) cv2.imshow('input img', result_image) cv2.waitKey()
|