match.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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 numpy as np
  16. import cv2
  17. from utils import Raster, raster2uint8, save_geotiff, time_it
  18. class MatchError(Exception):
  19. def __str__(self):
  20. return "Cannot match two images."
  21. def _calcu_tf(im1, im2):
  22. orb = cv2.AKAZE_create()
  23. kp1, des1 = orb.detectAndCompute(im1, None)
  24. kp2, des2 = orb.detectAndCompute(im2, None)
  25. bf = cv2.BFMatcher()
  26. mathces = bf.knnMatch(des2, des1, k=2)
  27. good_matches = []
  28. for m, n in mathces:
  29. if m.distance < 0.75 * n.distance:
  30. good_matches.append([m])
  31. if len(good_matches) < 4:
  32. raise MatchError()
  33. src_automatic_points = np.float32([kp2[m[0].queryIdx].pt \
  34. for m in good_matches]).reshape(-1, 1, 2)
  35. den_automatic_points = np.float32([kp1[m[0].trainIdx].pt \
  36. for m in good_matches]).reshape(-1, 1, 2)
  37. H, _ = cv2.findHomography(src_automatic_points, den_automatic_points,
  38. cv2.RANSAC, 5.0)
  39. return H
  40. def _get_match_img(raster, bands):
  41. if len(bands) not in [1, 3]:
  42. raise ValueError("The lenght of bands must be 1 or 3.")
  43. band_array = []
  44. for b in bands:
  45. band_i = raster.GetRasterBand(b).ReadAsArray()
  46. band_array.append(band_i)
  47. if len(band_array) == 1:
  48. ima = raster2uint8(band_array[0])
  49. else:
  50. ima = raster2uint8(np.stack(band_array, axis=-1))
  51. ima = cv2.cvtColor(ima, cv2.COLOR_RGB2GRAY)
  52. return ima
  53. @time_it
  54. def match(im1_path, im2_path, im1_bands=[1, 2, 3], im2_bands=[1, 2, 3]):
  55. im1_ras = Raster(im1_path)
  56. im2_ras = Raster(im2_path)
  57. im1 = _get_match_img(im1_ras._src_data, im1_bands)
  58. im2 = _get_match_img(im2_ras._src_data, im2_bands)
  59. H = _calcu_tf(im1, im2)
  60. # test
  61. # im2_t = cv2.warpPerspective(im2, H, (im1.shape[1], im1.shape[0]))
  62. # cv2.imwrite("B_M.png", cv2.cvtColor(im2_t, cv2.COLOR_RGB2BGR))
  63. im2_arr_t = cv2.warpPerspective(im2_ras.getArray(), H,
  64. (im1_ras.width, im1_ras.height))
  65. save_path = im2_ras.path.replace(("." + im2_ras.ext_type), "_M.tif")
  66. save_geotiff(im2_arr_t, save_path, im1_ras.proj, im1_ras.geot,
  67. im1_ras.datatype)
  68. parser = argparse.ArgumentParser(description="input parameters")
  69. parser.add_argument("--im1_path", type=str, required=True, \
  70. help="Path of time1 image (with geoinfo).")
  71. parser.add_argument("--im2_path", type=str, required=True, \
  72. help="Path of time2 image.")
  73. parser.add_argument("--im1_bands", type=int, nargs="+", default=[1, 2, 3], \
  74. help="Bands of im1 to be used for matching, RGB or monochrome. `[1, 2, 3]` is the default value.")
  75. parser.add_argument("--im2_bands", type=int, nargs="+", default=[1, 2, 3], \
  76. help="Bands of im2 to be used for matching, RGB or monochrome. `[1, 2, 3]` is the default value.")
  77. if __name__ == "__main__":
  78. args = parser.parse_args()
  79. match(args.im1_path, args.im2_path, args.im1_bands, args.im2_bands)