matcher.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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 numpy as np
  15. import cv2
  16. import argparse
  17. import time
  18. from utils import Raster, raster2uint8
  19. try:
  20. from osgeo import gdal
  21. except ImportError:
  22. import gdal
  23. class MatchError (Exception):
  24. def __str__(self):
  25. return "Cannot match two images."
  26. def _calcu_tf(im1, im2):
  27. orb = cv2.AKAZE_create()
  28. kp1, des1 = orb.detectAndCompute(im1, None)
  29. kp2, des2 = orb.detectAndCompute(im2, None)
  30. bf = cv2.BFMatcher()
  31. mathces = bf.knnMatch(des2, des1, k=2)
  32. good_matches = []
  33. for m, n in mathces:
  34. if m.distance < 0.75 * n.distance:
  35. good_matches.append([m])
  36. if len(good_matches) < 4:
  37. raise MatchError()
  38. src_automatic_points = np.float32([kp2[m[0].queryIdx].pt \
  39. for m in good_matches]).reshape(-1, 1, 2)
  40. den_automatic_points = np.float32([kp1[m[0].trainIdx].pt \
  41. for m in good_matches]).reshape(-1, 1, 2)
  42. H, _ = cv2.findHomography(src_automatic_points, den_automatic_points, cv2.RANSAC, 5.0)
  43. return H
  44. def _get_match_img(raster, bands):
  45. if len(bands) not in [1, 3]:
  46. raise ValueError("The lenght of bands must be 1 or 3.")
  47. band_array = []
  48. for b in bands:
  49. band_i = raster.GetRasterBand(b).ReadAsArray()
  50. band_array.append(band_i)
  51. if len(band_array) == 1:
  52. ima = raster2uint8(band_array)
  53. else:
  54. ima = raster2uint8(np.stack(band_array, axis=-1))
  55. ima = cv2.cvtColor(ima, cv2.COLOR_RGB2GRAY)
  56. return ima
  57. def _img2tif(ima, save_path, proj, geot):
  58. if len(ima.shape) == 3:
  59. row, columns, bands = ima.shape
  60. else:
  61. row, columns = ima.shape
  62. bands = 1
  63. driver = gdal.GetDriverByName("GTiff")
  64. dst_ds = driver.Create(save_path, columns, row, bands, gdal.GDT_UInt16)
  65. dst_ds.SetGeoTransform(geot)
  66. dst_ds.SetProjection(proj)
  67. if bands != 1:
  68. for b in range(bands):
  69. dst_ds.GetRasterBand(b + 1).WriteArray(ima[:, :, b])
  70. else:
  71. dst_ds.GetRasterBand(1).WriteArray(ima)
  72. dst_ds.FlushCache()
  73. return dst_ds
  74. def matching(im1_path, im2_path, im1_bands=[1, 2, 3], im2_bands=[1, 2, 3]):
  75. im1_ras = Raster(im1_path)
  76. im2_ras = Raster(im2_path)
  77. im1 = _get_match_img(im1_ras._src_data, im1_bands)
  78. im2 = _get_match_img(im2_ras._src_data, im2_bands)
  79. H = _calcu_tf(im1, im2)
  80. # test
  81. # im2_t = cv2.warpPerspective(im2, H, (im1.shape[1], im1.shape[0]))
  82. # cv2.imwrite("B_M.png", cv2.cvtColor(im2_t, cv2.COLOR_RGB2BGR))
  83. im2_arr_t = cv2.warpPerspective(im2_ras.getArray(), H, (im1_ras.width, im1_ras.height))
  84. save_path = im2_ras.path.replace(("." + im2_ras.ext_type), "_M.tif")
  85. _img2tif(im2_arr_t, save_path, im1_ras.proj, im1_ras.geot)
  86. parser = argparse.ArgumentParser(description="input parameters")
  87. parser.add_argument("--im1_path", type=str, required=True, \
  88. help="The path of time1 image (with geoinfo).")
  89. parser.add_argument("--im2_path", type=str, required=True, \
  90. help="The path of time1 image.")
  91. if __name__ == "__main__":
  92. args = parser.parse_args()
  93. start_time = time.time()
  94. matching(args.im1_path, args.im2_path)
  95. end_time = time.time()
  96. print("Total time:", (end_time - start_time))