51 clip image
Uncomment the following line to install leafmap if needed.
In [1]:
Copied!
# !pip install leafmap
# !pip install leafmap
In [2]:
Copied!
# !pip install rasterio fiona
# !pip install rasterio fiona
In [3]:
Copied!
import leafmap
import leafmap
Download a sample raster dataset.
In [4]:
Copied!
url = "https://open.gishub.org/data/raster/srtm90.tif"
dem = "dem.tif"
url = "https://open.gishub.org/data/raster/srtm90.tif"
dem = "dem.tif"
In [5]:
Copied!
leafmap.download_file(url, dem, overwrite=True)
leafmap.download_file(url, dem, overwrite=True)
Downloading... From: https://open.gishub.org/data/raster/srtm90.tif To: /home/runner/work/leafmap/leafmap/docs/notebooks/dem.tif
0%| | 0.00/16.6M [00:00<?, ?B/s]
100%|██████████| 16.6M/16.6M [00:00<00:00, 231MB/s]
Out[5]:
'/home/runner/work/leafmap/leafmap/docs/notebooks/dem.tif'
Create an interactive map.
In [6]:
Copied!
m = leafmap.Map()
m.add_raster(dem, palette="terrain", layer_name="DEM")
m
m = leafmap.Map()
m.add_raster(dem, palette="terrain", layer_name="DEM")
m
Out[6]:
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.
In [7]:
Copied!
# mask = 'https://raw.githubusercontent.com/opengeos/leafmap/master/examples/data/mask.geojson'
# 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.
In [8]:
Copied!
# mask = m.user_roi
# mask = m.user_roi
Or specify a list of coordinates [lon, lat]
as the mask.
In [9]:
Copied!
mask = [
[-119.679565, 37.256566],
[-119.679565, 38.061067],
[-118.24585, 38.061067],
[-118.24585, 37.256566],
[-119.679565, 37.256566],
]
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.
In [10]:
Copied!
output = "clip.tif"
output = "clip.tif"
Clip image by mask.
In [11]:
Copied!
try:
leafmap.clip_image(dem, mask, output)
except Exception as e:
print(e)
try:
leafmap.clip_image(dem, mask, output)
except Exception as e:
print(e)
module 'leafmap' has no attribute 'clip_image'
Add the clipped image to the map.
In [12]:
Copied!
try:
m.add_raster(output, palette="gist_earth", layer_name="Clip Image")
except Exception as e:
print(e)
try:
m.add_raster(output, palette="gist_earth", layer_name="Clip Image")
except Exception as e:
print(e)
Path does not exist: /home/runner/work/leafmap/leafmap/docs/notebooks/clip.tif