|
| 1 | +import cv2 |
| 2 | +import numpy as np |
| 3 | + |
| 4 | + |
| 5 | +MAX_MATCHES = 500 |
| 6 | +GOOD_MATCH_PERCENT = 0.15 |
| 7 | + |
| 8 | + |
| 9 | +def alignImages(im1, im2): |
| 10 | + |
| 11 | + # Convert images to grayscale |
| 12 | + im1Gray = cv2.cvtColor(im1, cv2.COLOR_BGR2GRAY) |
| 13 | + im2Gray = cv2.cvtColor(im2, cv2.COLOR_BGR2GRAY) |
| 14 | + |
| 15 | + # Detect ORB features and compute descriptors. |
| 16 | + orb = cv2.ORB_create(MAX_MATCHES) |
| 17 | + keypoints1, descriptors1 = orb.detectAndCompute(im1Gray, None) |
| 18 | + keypoints2, descriptors2 = orb.detectAndCompute(im2Gray, None) |
| 19 | + |
| 20 | + # Match features. |
| 21 | + matcher = cv2.DescriptorMatcher_create(cv2.DESCRIPTOR_MATCHER_BRUTEFORCE_HAMMING) |
| 22 | + matches = matcher.match(descriptors1, descriptors2, None) |
| 23 | + |
| 24 | + # Sort matches by score |
| 25 | + matches.sort(key=lambda x: x.distance, reverse=False) |
| 26 | + |
| 27 | + # Remove not so good matches |
| 28 | + numGoodMatches = int(len(matches) * GOOD_MATCH_PERCENT) |
| 29 | + matches = matches[:numGoodMatches] |
| 30 | + |
| 31 | + # Draw top matches |
| 32 | + imMatches = cv2.drawMatches(im1, keypoints1, im2, keypoints2, matches, None) |
| 33 | + cv2.imwrite("matches.jpg", imMatches) |
| 34 | + |
| 35 | + # Extract location of good matches |
| 36 | + points1 = np.zeros((len(matches), 2), dtype=np.float32) |
| 37 | + points2 = np.zeros((len(matches), 2), dtype=np.float32) |
| 38 | + |
| 39 | + for i, match in enumerate(matches): |
| 40 | + points1[i, :] = keypoints1[match.queryIdx].pt |
| 41 | + points2[i, :] = keypoints2[match.trainIdx].pt |
| 42 | + |
| 43 | + # Find homography |
| 44 | + h, mask = cv2.findHomography(points1, points2, cv2.RANSAC) |
| 45 | + |
| 46 | + # Use homography |
| 47 | + height, width, channels = im2.shape |
| 48 | + im1Reg = cv2.warpPerspective(im1, h, (width, height)) |
| 49 | + |
| 50 | + return im1Reg, h |
| 51 | + |
| 52 | + |
| 53 | +if __name__ == '__main__': |
| 54 | + im = cv2.imread("scanned-form.jpg", cv2.IMREAD_COLOR) |
| 55 | + imReference = cv2.imread("form.jpg", cv2.IMREAD_COLOR) |
| 56 | + |
| 57 | + imReg, h = alignImages(im, imReference) |
| 58 | + cv2.imwrite("aligned.jpg", imReg) |
| 59 | + |
0 commit comments