Skip to content

47 numpy to cog

image image image

Create a fresh conda env to run this example if needed.

1
2
3
conda create -n cog python=3.9
conda install mamba -c conda-forge
mamba install leafmap rio-cogeo -c conda-forge
1
# !pip install leafmap
1
# !pip install rio-cogeo
1
import leafmap
1
2
3
url = "https://github.com/opengeos/leafmap/raw/master/examples/data/cog.tif"
in_cog = "cog.tif"
out_cog = "ndvi.tif"

Download a sample dataset.

1
leafmap.download_from_url(url, in_cog)

Convert image to numpy array.

1
arr = leafmap.image_to_numpy(in_cog)
1
arr.shape

Computer NDVI.

1
ndvi = (arr[3] - arr[0]) / (arr[3] + arr[0])
1
ndvi.shape

Convert numpy array to COG.

1
leafmap.numpy_to_cog(ndvi, out_cog, profile=in_cog)
1
2
3
4
m = leafmap.Map()
m.add_raster(in_cog, band=[4, 1, 2], layer_name="Color infrared")
m.add_raster(out_cog, palette="Greens", layer_name="NDVI")
m