match.py 3.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. #!/usr/bin/env python
  2. # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import argparse
  16. import paddlers
  17. import numpy as np
  18. import cv2
  19. from utils import Raster, raster2uint8, save_geotiff, time_it
  20. class MatchError(Exception):
  21. def __str__(self):
  22. return "Cannot match the two images."
  23. def _calcu_tf(image1, image2):
  24. orb = cv2.AKAZE_create()
  25. kp1, des1 = orb.detectAndCompute(image1, None)
  26. kp2, des2 = orb.detectAndCompute(image2, None)
  27. bf = cv2.BFMatcher()
  28. mathces = bf.knnMatch(des2, des1, k=2)
  29. good_matches = []
  30. for m, n in mathces:
  31. if m.distance < 0.75 * n.distance:
  32. good_matches.append([m])
  33. if len(good_matches) < 4:
  34. raise MatchError()
  35. src_automatic_points = np.float32([kp2[m[0].queryIdx].pt \
  36. for m in good_matches]).reshape(-1, 1, 2)
  37. den_automatic_points = np.float32([kp1[m[0].trainIdx].pt \
  38. for m in good_matches]).reshape(-1, 1, 2)
  39. H, _ = cv2.findHomography(src_automatic_points, den_automatic_points,
  40. cv2.RANSAC, 5.0)
  41. return H
  42. def _get_match_img(raster, bands):
  43. if len(bands) not in [1, 3]:
  44. raise ValueError("The lenght of bands must be 1 or 3.")
  45. band_array = []
  46. for b in bands:
  47. band_i = raster.GetRasterBand(b).ReadAsArray()
  48. band_array.append(band_i)
  49. if len(band_array) == 1:
  50. ima = raster2uint8(band_array[0])
  51. else:
  52. ima = raster2uint8(np.stack(band_array, axis=-1))
  53. ima = cv2.cvtColor(ima, cv2.COLOR_RGB2GRAY)
  54. return ima
  55. @time_it
  56. def match(image1_path,
  57. image2_path,
  58. save_path,
  59. image1_bands=[1, 2, 3],
  60. image2_bands=[1, 2, 3]):
  61. im1_ras = Raster(image1_path)
  62. im2_ras = Raster(image2_path)
  63. im1 = _get_match_img(im1_ras._src_data, image1_bands)
  64. im2 = _get_match_img(im2_ras._src_data, image2_bands)
  65. H = _calcu_tf(im1, im2)
  66. im2_arr_t = cv2.warpPerspective(im2_ras.getArray(), H,
  67. (im1_ras.width, im1_ras.height))
  68. save_geotiff(im2_arr_t, save_path, im1_ras.proj, im1_ras.geot,
  69. im1_ras.datatype)
  70. if __name__ == "__main__":
  71. parser = argparse.ArgumentParser()
  72. parser.add_argument('--image1_path', type=str, required=True, \
  73. help="Path of time1 image (with geoinfo).")
  74. parser.add_argument('--image2_path', type=str, required=True, \
  75. help="Path of time2 image.")
  76. parser.add_argument('--save_path', type=str, required=True, \
  77. help="Path to save matching result.")
  78. parser.add_argument('--image1_bands', type=int, nargs="+", default=[1, 2, 3], \
  79. help="Bands of image1 to be used for matching, RGB or monochrome. The default value is [1, 2, 3].")
  80. parser.add_argument('--image2_bands', type=int, nargs="+", default=[1, 2, 3], \
  81. help="Bands of image2 to be used for matching, RGB or monochrome. The default value is [1, 2, 3].")
  82. args = parser.parse_args()
  83. match(args.image1_path, args.image2_path, args.save_path, args.image1_bands,
  84. args.image2_bands)