Uncomment the following line to install leafmap if needed.
# !pip install leafmap
# !pip install rasterio fiona
import leafmap
Download a sample raster dataset.
url = "https://open.gishub.org/data/raster/srtm90.tif"
dem = "dem.tif"
leafmap.download_file(url, dem, overwrite=True)
Create an interactive map.
m = leafmap.Map()
m.add_raster(dem, palette="terrain", layer_name="DEM")
m
Define a mask to extract the image. The mask can be a string representing a file path to a vector dataset (e.g., geojson, shp), or a list of coordinates (e.g., [[lon,lat], [lon,lat]]
), or a dictionary representing a feature (e.g., m.user_roi).
For example, the mask can be a filepath to a vector dataset.
# mask = 'https://raw.githubusercontent.com/opengeos/leafmap/master/examples/data/mask.geojson'
Or you can draw a polygon on the map, then use m.user_roi
as the mask.
# mask = m.user_roi
Or specify a list of coordinates [lon, lat]
as the mask.
mask = [
[-119.679565, 37.256566],
[-119.679565, 38.061067],
[-118.24585, 38.061067],
[-118.24585, 37.256566],
[-119.679565, 37.256566],
]
Specify the output filename.
output = "clip.tif"
Clip image by mask.
try:
leafmap.clip_image(dem, mask, output)
except Exception as e:
print(e)
Add the clipped image to the map.
try:
m.add_raster(output, palette="gist_earth", layer_name="Clip Image")
except Exception as e:
print(e)