align.py 2.2 KB

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