match.py 3.7 KB

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