matcher.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  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. from utils import Raster, raster2uint8, Timer
  18. try:
  19. from osgeo import gdal
  20. except ImportError:
  21. import gdal
  22. class MatchError(Exception):
  23. def __str__(self):
  24. return "Cannot match two images."
  25. def _calcu_tf(im1, im2):
  26. orb = cv2.AKAZE_create()
  27. kp1, des1 = orb.detectAndCompute(im1, None)
  28. kp2, des2 = orb.detectAndCompute(im2, None)
  29. bf = cv2.BFMatcher()
  30. mathces = bf.knnMatch(des2, des1, k=2)
  31. good_matches = []
  32. for m, n in mathces:
  33. if m.distance < 0.75 * n.distance:
  34. good_matches.append([m])
  35. if len(good_matches) < 4:
  36. raise MatchError()
  37. src_automatic_points = np.float32([kp2[m[0].queryIdx].pt \
  38. for m in good_matches]).reshape(-1, 1, 2)
  39. den_automatic_points = np.float32([kp1[m[0].trainIdx].pt \
  40. for m in good_matches]).reshape(-1, 1, 2)
  41. H, _ = cv2.findHomography(src_automatic_points, den_automatic_points,
  42. 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[0])
  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, dtype):
  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, dtype)
  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. @Timer
  75. def matching(im1_path, im2_path, im1_bands=[1, 2, 3], im2_bands=[1, 2, 3]):
  76. im1_ras = Raster(im1_path)
  77. im2_ras = Raster(im2_path)
  78. im1 = _get_match_img(im1_ras._src_data, im1_bands)
  79. im2 = _get_match_img(im2_ras._src_data, im2_bands)
  80. H = _calcu_tf(im1, im2)
  81. # test
  82. # im2_t = cv2.warpPerspective(im2, H, (im1.shape[1], im1.shape[0]))
  83. # cv2.imwrite("B_M.png", cv2.cvtColor(im2_t, cv2.COLOR_RGB2BGR))
  84. im2_arr_t = cv2.warpPerspective(im2_ras.getArray(), H,
  85. (im1_ras.width, im1_ras.height))
  86. save_path = im2_ras.path.replace(("." + im2_ras.ext_type), "_M.tif")
  87. _img2tif(im2_arr_t, save_path, im1_ras.proj, im1_ras.geot, im1_ras.datatype)
  88. parser = argparse.ArgumentParser(description="input parameters")
  89. parser.add_argument("--im1_path", type=str, required=True, \
  90. help="The path of time1 image (with geoinfo).")
  91. parser.add_argument("--im2_path", type=str, required=True, \
  92. help="The path of time2 image.")
  93. parser.add_argument("--im1_bands", type=int, nargs="+", default=[1, 2, 3], \
  94. help="The time1 image's band used for matching, RGB or monochrome, `[1, 2, 3]` is the default.")
  95. parser.add_argument("--im2_bands", type=int, nargs="+", default=[1, 2, 3], \
  96. help="The time2 image's band used for matching, RGB or monochrome, `[1, 2, 3]` is the default.")
  97. if __name__ == "__main__":
  98. args = parser.parse_args()
  99. matching(args.im1_path, args.im2_path, args.im1_bands, args.im2_bands)