def get_footprint_mask(shpfile, geoimg, filelist, fprint_out=False): imlist = [im.split('OIS-Reech_')[-1].split('.tif')[0] for im in filelist] footprints_shp = gpd.read_file(shpfile) fp = footprints_shp[footprints_shp.ID.isin(imlist)] fprint = cascaded_union(fp.to_crs( epsg=geoimg.epsg).geometry.values[1:-1]).minimum_rotated_rectangle tmp_gdf = gpd.GeoDataFrame(columns=['geometry']) tmp_gdf.loc[0, 'geometry'] = fprint tmp_gdf.crs = {'init': 'epsg:{}'.format(geoimg.epsg)} tmp_gdf.to_file('tmp_fprint.shp') maskout = create_mask_from_shapefile(geoimg, 'tmp_fprint.shp') for f in glob('tmp_fprint.*'): os.remove(f) if fprint_out: return maskout, fprint else: return maskout
def get_initial_transformation(img1, img2, landmask=None, footmask=None): im2_lowres = reshape_geoimg(img2, 800, 800) im2_eq = match_hist(im2_lowres.img, np.array(img1)) im1_mask = 255 * np.ones(img1.shape, dtype=np.uint8) im1_mask[img1 == 0] = 0 # nodata from ortho im2_mask = 255 * np.ones(im2_eq.shape, dtype=np.uint8) im2_mask[im2_eq == 0] = 0 if landmask is not None: mask_ = create_mask_from_shapefile(im2_lowres, landmask) im2_mask[~mask_] = 0 if footmask is not None: mask_ = get_footprint_mask(footmask, im2_lowres, glob('OIS*.tif')) im2_mask[~mask_] = 0 kp, des, matches = get_matches(img1, im2_eq, mask1=im1_mask, mask2=im2_mask) src_pts = np.float32([kp[0][m.queryIdx].pt for m in matches]).reshape(-1, 1, 2) dst_pts = np.float32([kp[1][m.trainIdx].pt for m in matches]).reshape(-1, 1, 2) aff_matrix, good_mask = cv2.estimateAffine2D(src_pts, dst_pts, ransacReprojThreshold=25) # check that the transformation was successful by correlating the two images. im1_tfm = cv2.warpAffine( img1, aff_matrix, (im2_lowres.img.shape[1], im2_lowres.img.shape[0])) im1_pad = np.zeros(np.array(im1_tfm.shape) + 2, dtype=np.uint8) im1_pad[1:-1, 1:-1] = im1_tfm res = cv2.matchTemplate(im2_eq, im1_pad, cv2.TM_CCORR_NORMED) print(res[1, 1]) success = res[1, 1] > 0.6 return aff_matrix, success, im2_eq.shape
[rect_u[0] + rect_u[2], rect_u[1] + rect_u[3]], [rect_u[0], rect_u[1] + rect_u[3]], [rect_u[0], rect_u[1]]]) def cerc_units_to_verts(cerc_u): xy, rad = cerc_u theta = np.linspace(0, 2 * np.pi, 100) verts = np.vstack([np.sin(theta), np.cos(theta)]).T return verts * rad + xy img = GeoImg(fn_hs) land_mask = create_mask_from_shapefile(img, fn_land) ds = gdal.Open(fn_hs) hs = ds.ReadAsArray() hs = hs.astype(float) def stretch_hs(hs, stretch_factor=1.): max_hs = 255 min_hs = 0 hs_s = (hs - (max_hs - min_hs) / 2) * stretch_factor + (max_hs - min_hs) / 2 return hs_s
def create_stable_mask(img, mask1, mask2): """ Create mask representing stable terrain, given exclusion (i.e., glacier) and inclusion (i.e., land) masks. :param img: GeoImg to pull extents from :param mask1: filename for shapefile representing pixels to exclude from stable terrain (i.e., glaciers) :param mask2: filename for shapefile representing pixels to include in stable terrain (i.e., land) :type img: pybob.GeoImg :type mask1: str :type mask2: str :returns stable_mask: boolean array representing stable terrain """ # if we have no masks, just return an array of true values if mask1 is None and mask2 is None: return np.ones( img.img.shape) == 0 # all false, so nothing will get masked. elif mask1 is not None and mask2 is None: # we have a glacier mask, not land if mask1.split('.')[-1] == 'tif': mask_rast = myRaster = gdal.Open(mask1) transform = myRaster.GetGeoTransform() dx = transform[1] dy = transform[5] Xsize = myRaster.RasterXSize Ysize = myRaster.RasterYSize mask = myRaster.ReadAsArray(0, 0, Xsize, Ysize) else: mask = create_mask_from_shapefile(img, mask1) return mask # returns true where there's glacier, false everywhere else elif mask1 is None and mask2 is not None: if mask2.split('.')[-1] == 'tif': mask_rast = myRaster = gdal.Open(mask2) transform = myRaster.GetGeoTransform() dx = transform[1] dy = transform[5] Xsize = myRaster.RasterXSize Ysize = myRaster.RasterYSize mask = myRaster.ReadAsArray(0, 0, Xsize, Ysize) else: mask = create_mask_from_shapefile(img, mask2) return np.logical_not( mask) # false where there's land, true where there isn't else: # if none of the above, we have two masks. # implement option if either or, or both mask are given as rasters. if (mask1.split('.')[-1] == 'tif') & (mask2.split('.')[-1] == 'shp'): mask_rast = myRaster = gdal.Open(mask1) transform = myRaster.GetGeoTransform() dx = transform[1] dy = transform[5] Xsize = myRaster.RasterXSize Ysize = myRaster.RasterYSize gmask = myRaster.ReadAsArray(0, 0, Xsize, Ysize) lmask = create_mask_from_shapefile(img, mask2) elif (mask2.split('.')[-1] == 'tif') & (mask1.split('.')[-1] == 'shp'): mask_rast = myRaster = gdal.Open(mask2) transform = myRaster.GetGeoTransform() dx = transform[1] dy = transform[5] Xsize = myRaster.RasterXSize Ysize = myRaster.RasterYSize lmask = myRaster.ReadAsArray(0, 0, Xsize, Ysize) gmask = create_mask_from_shapefile(img, mask1) elif (mask1.split('.')[-1] == 'tif') & (mask2.split('.')[-1] == 'tif'): mask_rast = myRaster = gdal.Open(mask1) transform = myRaster.GetGeoTransform() dx = transform[1] dy = transform[5] Xsize = myRaster.RasterXSize Ysize = myRaster.RasterYSize gmask = myRaster.ReadAsArray(0, 0, Xsize, Ysize) mask_rast = myRaster = gdal.Open(mask2) transform = myRaster.GetGeoTransform() dx = transform[1] dy = transform[5] Xsize = myRaster.RasterXSize Ysize = myRaster.RasterYSize lmask = myRaster.ReadAsArray(0, 0, Xsize, Ysize) else: gmask = create_mask_from_shapefile(img, mask1) lmask = create_mask_from_shapefile(img, mask2) return np.logical_or( gmask, np.logical_not(lmask)) # true where there's glacier or water
# load the full mask, which we'll re-project later mask_full = GeoImg('../southeast_average_corr.tif') for yr in [2012, 2013]: print("Loading {} data files.".format(yr)) ifsar = GeoImg('{}/seak.ifsar.{}.dem.30m_adj.tif'.format(yr, yr)) ifsar_srtm = GeoImg('{}/ifsar_srtm_{}_dh.tif'.format(yr, yr)) srtm = GeoImg('{}/SRTM_SE_Alaska_30m_{}IfSAR_adj.tif'.format(yr, yr)) valid_area = np.isfinite(ifsar.img) glac_shp = '../outlines/01_rgi60_Alaska_GlacierBay_02km_UTM_{}.shp'.format(yr) glacier_mask = it.create_mask_from_shapefile(ifsar, glac_shp) mask_geo = mask_full.reproject(ifsar_srtm) corrs = [35, 50, 70, 80, 90, 95] for i, corr in enumerate(corrs): corr_mask = mask_geo.img < corr masked_ifsar = ifsar.copy() masked_ifsar.img[corr_mask] = np.nan masked_ifsar_srtm = ifsar_srtm.copy() masked_ifsar_srtm.img[corr_mask] = np.nan print("Linear interpolation of dH") ifsar_srtm_lin_interp = dt.fill_holes(masked_ifsar_srtm, dt.linear, valid_area=valid_area) ifsar_srtm_lin_interp.write('ifsar_srtm_{}_dHinterp.tif'.format(yr), out_folder='filled_ddems/{}/void{}'.format(yr, corr))
# dh_dem dem2_reproj = dem2.reproject(dem1) # reproject master DEM to slave DEM extent, cell size dh_dem = dem2.copy(new_raster=dem2_reproj.img - dem1.img) dh_bedrx = dem2.copy(new_raster=dem2_reproj.img - dem1.img) # remove outliers dem_rem = np.absolute(np.nanmean(dh_dem.img))+(np.nanstd(dh_dem.img)*5) np.seterr(all='ignore') dh_dem.img[dh_dem.img > dem_rem] = np.nan dh_dem.img[dh_dem.img < (dem_rem*-1)] = np.nan dh_bedrx.img[dh_bedrx.img > dem_rem] = np.nan dh_bedrx.img[dh_bedrx.img < (dem_rem*-1)] = np.nan # test coregistered bedrx error bedrx_ma = imtool.create_mask_from_shapefile(dem1,bedrx_poly_mask,buffer=None) bedrx_mask = np.invert(bedrx_ma) # inverting for mask dh_bedrx.img = np.ma.masked_where(bedrx_mask, dh_bedrx.img) # masking fig0 = dh_bedrx.display(fig=plt.figure(figsize=(8,8)), cmap='bwr_r', vmin=-10, vmax=10) fig0.gca().set_xlabel('utm easting (m)') fig0.gca().set_ylabel('utm northing (m)') cb = plt.colorbar(); cb.set_label('elevation difference (m)') #ts = np.ma.compressed(dh_bedrx.img) #plt.hist(ts,bins=40,range=[-7.5,7.5]) #plt.show() # to plot histogram # mask DEMs s1 = gpd.read_file(odir+'2016_outline1.shp') s2 = gpd.read_file(odir+'2021_outline.shp') s1arr_a = imtool.create_mask_from_shapefile(dem1,odir+'2016_outline1.shp',buffer=None) s1arr = np.invert(s1arr_a)