asift.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. #!/usr/bin/env python
  2. '''
  3. Affine invariant feature-based image matching sample.
  4. This sample is similar to find_obj.py, but uses the affine transformation
  5. space sampling technique, called ASIFT [1]. While the original implementation
  6. is based on SIFT, you can try to use SURF or ORB detectors instead. Homography RANSAC
  7. is used to reject outliers. Threading is used for faster affine sampling.
  8. [1] http://www.ipol.im/pub/algo/my_affine_sift/
  9. USAGE
  10. asift.py [--feature=<sift|surf|orb|brisk>[-flann]] [ <image1> <image2> ]
  11. --feature - Feature to use. Can be sift, surf, orb or brisk. Append '-flann'
  12. to feature name to use Flann-based matcher instead bruteforce.
  13. Press left mouse button on a feature point to see its matching point.
  14. '''
  15. # Python 2/3 compatibility
  16. from __future__ import print_function
  17. import numpy as np
  18. import cv2 as cv
  19. # built-in modules
  20. import itertools as it
  21. from multiprocessing.pool import ThreadPool
  22. # local modules
  23. from common import Timer
  24. from find_obj import init_feature, filter_matches, explore_match
  25. def affine_skew(tilt, phi, img, mask=None):
  26. '''
  27. affine_skew(tilt, phi, img, mask=None) -> skew_img, skew_mask, Ai
  28. Ai - is an affine transform matrix from skew_img to img
  29. '''
  30. h, w = img.shape[:2]
  31. if mask is None:
  32. mask = np.zeros((h, w), np.uint8)
  33. mask[:] = 255
  34. A = np.float32([[1, 0, 0], [0, 1, 0]])
  35. if phi != 0.0:
  36. phi = np.deg2rad(phi)
  37. s, c = np.sin(phi), np.cos(phi)
  38. A = np.float32([[c,-s], [ s, c]])
  39. corners = [[0, 0], [w, 0], [w, h], [0, h]]
  40. tcorners = np.int32( np.dot(corners, A.T) )
  41. x, y, w, h = cv.boundingRect(tcorners.reshape(1,-1,2))
  42. A = np.hstack([A, [[-x], [-y]]])
  43. img = cv.warpAffine(img, A, (w, h), flags=cv.INTER_LINEAR, borderMode=cv.BORDER_REPLICATE)
  44. if tilt != 1.0:
  45. s = 0.8*np.sqrt(tilt*tilt-1)
  46. img = cv.GaussianBlur(img, (0, 0), sigmaX=s, sigmaY=0.01)
  47. img = cv.resize(img, (0, 0), fx=1.0/tilt, fy=1.0, interpolation=cv.INTER_NEAREST)
  48. A[0] /= tilt
  49. if phi != 0.0 or tilt != 1.0:
  50. h, w = img.shape[:2]
  51. mask = cv.warpAffine(mask, A, (w, h), flags=cv.INTER_NEAREST)
  52. Ai = cv.invertAffineTransform(A)
  53. return img, mask, Ai
  54. def affine_detect(detector, img, mask=None, pool=None):
  55. '''
  56. affine_detect(detector, img, mask=None, pool=None) -> keypoints, descrs
  57. Apply a set of affine transformations to the image, detect keypoints and
  58. reproject them into initial image coordinates.
  59. See http://www.ipol.im/pub/algo/my_affine_sift/ for the details.
  60. ThreadPool object may be passed to speedup the computation.
  61. '''
  62. params = [(1.0, 0.0)]
  63. for t in 2**(0.5*np.arange(1,6)):
  64. for phi in np.arange(0, 180, 72.0 / t):
  65. params.append((t, phi))
  66. def f(p):
  67. t, phi = p
  68. timg, tmask, Ai = affine_skew(t, phi, img)
  69. keypoints, descrs = detector.detectAndCompute(timg, tmask)
  70. for kp in keypoints:
  71. x, y = kp.pt
  72. kp.pt = tuple( np.dot(Ai, (x, y, 1)) )
  73. if descrs is None:
  74. descrs = []
  75. return keypoints, descrs
  76. keypoints, descrs = [], []
  77. if pool is None:
  78. ires = it.imap(f, params)
  79. else:
  80. ires = pool.imap(f, params)
  81. for i, (k, d) in enumerate(ires):
  82. print('affine sampling: %d / %d\r' % (i+1, len(params)), end='')
  83. keypoints.extend(k)
  84. descrs.extend(d)
  85. print()
  86. return keypoints, np.array(descrs)
  87. def main():
  88. import sys, getopt
  89. opts, args = getopt.getopt(sys.argv[1:], '', ['feature='])
  90. opts = dict(opts)
  91. feature_name = opts.get('--feature', 'brisk-flann')
  92. try:
  93. fn1, fn2 = args
  94. except:
  95. fn1 = 'aero1.jpg'
  96. fn2 = 'aero3.jpg'
  97. img1 = cv.imread(cv.samples.findFile(fn1), cv.IMREAD_GRAYSCALE)
  98. img2 = cv.imread(cv.samples.findFile(fn2), cv.IMREAD_GRAYSCALE)
  99. detector, matcher = init_feature(feature_name)
  100. if img1 is None:
  101. print('Failed to load fn1:', fn1)
  102. sys.exit(1)
  103. if img2 is None:
  104. print('Failed to load fn2:', fn2)
  105. sys.exit(1)
  106. if detector is None:
  107. print('unknown feature:', feature_name)
  108. sys.exit(1)
  109. print('using', feature_name)
  110. pool=ThreadPool(processes = cv.getNumberOfCPUs())
  111. kp1, desc1 = affine_detect(detector, img1, pool=pool)
  112. kp2, desc2 = affine_detect(detector, img2, pool=pool)
  113. print('img1 - %d features, img2 - %d features' % (len(kp1), len(kp2)))
  114. def match_and_draw(win):
  115. with Timer('matching'):
  116. raw_matches = matcher.knnMatch(desc1, trainDescriptors = desc2, k = 2) #2
  117. p1, p2, kp_pairs = filter_matches(kp1, kp2, raw_matches)
  118. if len(p1) >= 4:
  119. H, status = cv.findHomography(p1, p2, cv.RANSAC, 5.0)
  120. print('%d / %d inliers/matched' % (np.sum(status), len(status)))
  121. # do not draw outliers (there will be a lot of them)
  122. kp_pairs = [kpp for kpp, flag in zip(kp_pairs, status) if flag]
  123. else:
  124. H, status = None, None
  125. print('%d matches found, not enough for homography estimation' % len(p1))
  126. explore_match(win, img1, img2, kp_pairs, None, H)
  127. match_and_draw('affine find_obj')
  128. cv.waitKey()
  129. print('Done')
  130. if __name__ == '__main__':
  131. print(__doc__)
  132. main()
  133. cv.destroyAllWindows()