def shade(located_elevations): """ Given an array of elevations in a LocatedImage, add a relief (shadows) to give a realistic 3d appearance. """ new_img = srtm.add_shading(located_elevations.image, azimuth=135, altitude=15) return LocatedImage(new_img, located_elevations.extent)
def fill_and_shade(located_elevations): """ Given an array of elevations in a LocatedImage, fill any holes in the data and add a relief (shadows) to give a realistic 3d appearance. """ new_elevations = srtm.fill_gaps(located_elevations.image, max_distance=15) new_img = srtm.add_shading(new_elevations, azimuth=135, altitude=15) return LocatedImage(new_img, located_elevations.extent)
def get_elevation_srtm(lon1, lat1, dx=1, dy=1, max_distance=10, shading=True, azimuth=315, altitude=45): # https://github.com/SciTools/cartopy/issues/789 from http.cookiejar import CookieJar import urllib.request password_manager = urllib.request.HTTPPasswordMgrWithDefaultRealm() password_manager.add_password(None, "https://urs.earthdata.nasa.gov", 'your_user_name', 'your_password') cookie_jar = CookieJar() opener = urllib.request.build_opener( urllib.request.HTTPBasicAuthHandler(password_manager), urllib.request.HTTPCookieProcessor(cookie_jar)) urllib.request.install_opener(opener) # end patch from cartopy.io.srtm import SRTM1Source, add_shading elev, crs, extent = SRTM1Source().combined(lon1, lat1, dx, dy) shades = None if shading: shades = add_shading(elev, azimuth, altitude) return elev, shades, crs, extent
def main(): ax = plt.axes(projection=ccrs.PlateCarree()) # Get the 1x1 degree SRTM tile for 12E, 47N elev, crs, extent = srtm.srtm_composite(12, 47, 1, 1) # Fill the gaps present in the elevation data elev_filled = srtm.fill_gaps(elev, 15) # Add shading simulating the Sun at 10am (South-East) # and with a low angle (15 degrees above horizon) shaded = srtm.add_shading(elev_filled, 135.0, 15.0) # The plot the result : plt.imshow(shaded, extent=extent, transform=crs, cmap='Greys', origin='lower') plt.title("SRTM Shaded Relief Map") gl = ax.gridlines(draw_labels=True) gl.xlabels_top = False gl.ylabels_left = False plt.show()
def main(): ax = plt.axes(projection=ccrs.PlateCarree()) # Get the 1x1 degree SRTM tile for 12E, 47N elev, crs, extent = srtm.srtm_composite(12, 47, 1, 1) # Fill the gaps present in the elevation data elev_filled = srtm.fill_gaps(elev, 15) # Add shading simulating the Sun at 10am (South-East) # and with a low angle (15 degrees above horizon) shaded = srtm.add_shading(elev_filled, 135.0, 15.0) # The plot the result : plt.imshow(shaded, extent=extent, transform=crs, cmap='Greys', origin='lower') plt.title("SRTM Shaded Relief Map") gl = ax.gridlines(draw_labels=True,) gl.xlabels_top = False gl.ylabels_left = False plt.show()
def produce_dem(grid, external_file=None, plot_output=True, output_file=False): """ Produce a digital elevation model (DEM) with the same extent, spacing, and UTM projection as an input projected RTM grid. The data source can be either a user-supplied file or global SRTM 1 arc-second (~30 m) data taken from the GMT server. A DataArray and (optionally) a GeoTIFF file are created. Optionally plot the output DEM. Output GeoTIFF files are placed in ``./rtm_dem`` (relative to where this function is called). **NOTE 1** The filename convention for output files is ``rtm_dem_<lat_0>_<lon_0>_<x_radius>x_<y_radius>y_<spacing>m.tif`` See the docstring for :func:`define_grid` for details/units. **NOTE 2** GMT caches downloaded SRTM tiles in the directory ``~/.gmt/server/srtm1``. If you're concerned about space, you can delete this directory. It will be created again the next time an SRTM tile is requested. Args: grid (:class:`~xarray.DataArray`): Projected :math:`(x, y)` grid; i.e., output of :func:`define_grid` with `projected=True` external_file (str): Filename of external DEM file to use. If `None`, then SRTM data is used (default: `None`) plot_output (bool): Toggle plotting a hillshade of the output DEM - useful for identifying voids or artifacts (default: `True`) output_file (bool): Toggle creation of output GeoTIFF file (default: `False`) Returns: 2-D :class:`~xarray.DataArray` of elevation values with identical shape to input grid. """ print('--------------') print('PROCESSING DEM') print('--------------') # If an external DEM file was not supplied, use SRTM data if not external_file: print('No external DEM file provided. Will use 1 arc-second SRTM data ' 'from GMT server. Checking for GMT 6...') # Check for GMT 6 if shutil.which('gmt') is not None: # GMT exists! Now check version gmt_version = subprocess.check_output(['gmt', '--version'], text=True).strip() if gmt_version[0] < '6': raise ValueError('GMT 6 is required, but you\'re using GMT ' f'{gmt_version}.') else: raise OSError('GMT not found on your system. Install GMT 6 and ' 'try again.') print(f'GMT version {gmt_version} found.') # Find corners going clockwise from SW (in UTM coordinates) corners_utm = [(grid.x.values.min(), grid.y.values.min()), (grid.x.values.min(), grid.y.values.max()), (grid.x.values.max(), grid.y.values.max()), (grid.x.values.max(), grid.y.values.min())] # Convert to lat/lon lats = [] lons = [] for corner in corners_utm: lat, lon = utm.to_latlon( *corner, zone_number=grid.UTM['zone'], northern=not grid.UTM['southern_hemisphere']) lats.append(lat) lons.append(lon) # [deg] (lonmin, lonmax, latmin, latmax) # np.floor and np.ceil here ensure we download more data than we need region = [ np.floor(min(lons)), np.ceil(max(lons)), np.floor(min(lats)), np.ceil(max(lats)) ] # This command requires GMT 6 args = [ 'gmt', 'grdcut', '@srtm_relief_01s', '-V', '-R{}/{}/{}/{}'.format(*region), '-G{}=gd:GTiff'.format(TMP_TIFF) ] subprocess.run(args) # Remove extra nodata metadata file try: os.remove(TMP_TIFF + '.aux.xml') except OSError: pass # Remove gmt.history if one was created (depends on global GMT setting) try: os.remove('gmt.history') except OSError: pass input_raster = TMP_TIFF # If an external DEM file was supplied, use it else: abs_path = os.path.abspath(external_file) # Check if file actually exists if not os.path.exists(abs_path): raise FileNotFoundError(abs_path) print(f'Using external DEM file:\n\t{abs_path}') input_raster = external_file # Define target spatial reference system using grid metadata dest_srs = osr.SpatialReference() proj_string = '+proj=utm +zone={} +datum=WGS84'.format(grid.UTM['zone']) if grid.UTM['southern_hemisphere']: proj_string += ' +south' dest_srs.ImportFromProj4(proj_string) # Control whether or not an output GeoTIFF is produced if output_file: # Create output raster filename/path if not os.path.exists(OUTPUT_DIR): os.makedirs(OUTPUT_DIR) output_name = TEMPLATE.format(*grid.grid_center[::-1], grid.x_radius, grid.y_radius, grid.spacing) # Write to file output = os.path.join(OUTPUT_DIR, output_name) format = 'GTiff' else: # Write to memory (see https://stackoverflow.com/a/48706963) output = '' format = 'VRT' # Resample input raster, whether it be from an external file or SRTM ds = gdal.Warp( output, input_raster, dstSRS=dest_srs, format=format, dstNodata=NODATA, outputBounds=(grid.x.min() - grid.spacing / 2, grid.y.min() - grid.spacing / 2, grid.x.max() + grid.spacing / 2, grid.y.max() + grid.spacing / 2), xRes=grid.spacing, yRes=grid.spacing, resampleAlg=RESAMPLE_ALG, copyMetadata=False, ) # Read resampled DEM into DataArray, set nodata values to np.nan dem = grid.copy() dem.data = np.flipud(ds.GetRasterBand(1).ReadAsArray()) dem.data[dem.data == NODATA] = np.nan # Set NODATA values to np.nan dem.data[dem.data < 0] = 0 # Set negative values (underwater?) to 0 ds = None # Removes dataset from memory # Remove temporary tiff file if it was created try: os.remove(TMP_TIFF) except OSError: pass # Warn user about possible units ambiguity - we can't check this directly! warnings.warn('Elevation units are assumed to be in meters!', RTMWarning) if output_file: print(f'Created output DEM file:\n\t{os.path.abspath(output)}') print('Done') if plot_output: print('Generating DEM hillshade plot...') proj = ccrs.UTM(**dem.UTM) fig, ax = plt.subplots(figsize=(10, 10), subplot_kw=dict(projection=proj)) # Create hillshade shaded_dem = add_shading(dem, azimuth=135, altitude=45) # Plot hillshade grid_shaded = grid.copy() grid_shaded.data = shaded_dem grid_shaded.plot.imshow(ax=ax, cmap='Greys_r', center=False, add_colorbar=False, transform=proj) # Add translucent DEM im = dem.plot.imshow(ax=ax, cmap='magma', alpha=0.5, vmin=0, add_colorbar=False, transform=proj) cbar = fig.colorbar(im, label='Elevation (m)') cbar.solids.set_alpha(1) # Plot the center of the grid ax.scatter(*dem.grid_center, s=50, color='limegreen', edgecolor='black', label='Grid center', transform=ccrs.PlateCarree()) # Add a legend ax.legend(loc='best') if external_file: source_label = os.path.abspath(external_file) else: source_label = '1 arc-second SRTM data' ax.set_title('{}\nResampled to {} m spacing'.format( source_label, dem.spacing)) fig.show() print('Done') return dem
catchlist = ['saale','weser'] label_cat = ['Saale','Weser'] lon_cat = [ 10.90, 9.20] lat_cat = [ 51.85, 52.40] # MAPPLOT ######################################### ifig += 1 print 'Plot - Fig ', ifig fig = plt.figure(ifig) iplot = 1 # data PROCESSING ############################################################# data = ufz.readnetcdf(demfile, var='mask')[0,:,:] lons = ufz.readnetcdf(demfile, var='lon') lats = ufz.readnetcdf(demfile, var='lat') dem = np.ma.array(data, mask=~(data>-9999.)) shaded = np.ma.array(srtm.add_shading(data*10,315.,45.), mask=~(data>-9999.)) test = dem / 5. + shaded smooth = np.ma.array(ufz.savitzky_golay2d(shaded,7,2), mask=~(data>-9999.)) # ec stations data = ufz.sread(txt_ecstat, skip=1, strarr=True) data_header = ufz.sread(txt_ecstat, skip=1, header=True, strarr=True) lat_ec = data[:,np.where(data_header=='Latitude')[0][0]].astype('float') lon_ec = data[:,np.where(data_header=='Longitude')[0][0]].astype('float') label_ec = data[:,np.where(data_header=='Stat_ID')[0][0]] id_ec = data[:,np.where(data_header=='Id')[0][0]] # plotting ############################################################# mp = fig.add_axes(ufz.position(nrow,ncol,1, wspace=0.01, hspace=0.01, left=figleft, right=figright, top=figtop, bottom=figbottom),