Last active
October 12, 2021 17:35
-
-
Save jdbcode/54a387020d32e40b60b025e4aa694e64 to your computer and use it in GitHub Desktop.
ee_cartopy_polar_coordinate_ndvi.ipynb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"nbformat": 4, | |
"nbformat_minor": 0, | |
"metadata": { | |
"colab": { | |
"name": "ee_cartopy_polar_coordinate_ndvi.ipynb", | |
"provenance": [], | |
"collapsed_sections": [], | |
"include_colab_link": true | |
}, | |
"kernelspec": { | |
"name": "python3", | |
"display_name": "Python 3" | |
}, | |
"language_info": { | |
"name": "python" | |
} | |
}, | |
"cells": [ | |
{ | |
"cell_type": "markdown", | |
"metadata": { | |
"id": "view-in-github", | |
"colab_type": "text" | |
}, | |
"source": [ | |
"<a href=\"https://colab.research.google.com/gist/jdbcode/54a387020d32e40b60b025e4aa694e64/ee_cartopy_polar_coordinate_ndvi.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": { | |
"id": "EKTYuJjs2TId" | |
}, | |
"source": [ | |
"Install conda" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"metadata": { | |
"id": "J3GQOPsby4fy" | |
}, | |
"source": [ | |
"!pip install -q condacolab\n", | |
"import condacolab\n", | |
"condacolab.install()" | |
], | |
"execution_count": null, | |
"outputs": [] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": { | |
"id": "pYEeMVFa2YB3" | |
}, | |
"source": [ | |
"Reload the Colab browser tab (Ctrl + R), then continue with the following code cell to install cartopy via mamba" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"metadata": { | |
"id": "dO5I1vtyy61M" | |
}, | |
"source": [ | |
"!mamba install -c conda-forge -y cartopy=0.19.0" | |
], | |
"execution_count": null, | |
"outputs": [] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": { | |
"id": "OClEB5dx2bpd" | |
}, | |
"source": [ | |
"Earth Engine setup" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"metadata": { | |
"id": "xzwb7F_Ty9MM" | |
}, | |
"source": [ | |
"import ee\n", | |
"ee.Authenticate()\n", | |
"ee.Initialize()" | |
], | |
"execution_count": null, | |
"outputs": [] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": { | |
"id": "I9uU0G6D2g4_" | |
}, | |
"source": [ | |
"Import packages" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"metadata": { | |
"id": "A0Rqc8oky-p0" | |
}, | |
"source": [ | |
"import cartopy.crs as ccrs\n", | |
"import cartopy.feature as cfeature\n", | |
"import matplotlib as mpl\n", | |
"import matplotlib.pyplot as plt\n", | |
"import matplotlib.path as mpath\n", | |
"import numpy as np\n", | |
"import os\n", | |
"import requests" | |
], | |
"execution_count": null, | |
"outputs": [] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": { | |
"id": "mBvmJxJy2jFF" | |
}, | |
"source": [ | |
"Make visualization collection in Earth Engine" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"metadata": { | |
"id": "EhSdyqmLzFv8" | |
}, | |
"source": [ | |
"col = (ee.ImageCollection('MODIS/006/MOD13Q1')\n", | |
" .filterDate('2018-01-01', '2019-01-01'))\n", | |
"\n", | |
"vis_params = {\n", | |
" 'bands': 'NDVI',\n", | |
" 'min': -2000,\n", | |
" 'max': 8000,\n", | |
" 'palette': ['black', 'blanchedalmond', '8FBC8F', '006400'],\n", | |
" 'forceRgbOutput': True\n", | |
"}\n", | |
"\n", | |
"aoi = {\n", | |
" 'xmin': -180,\n", | |
" 'ymin': 60,\n", | |
" 'xmax': 180,\n", | |
" 'ymax': 90\n", | |
"}\n", | |
"\n", | |
"def vis_rgb(img):\n", | |
" return (img.visualize(**vis_params)\n", | |
" .unmask(0)\n", | |
" .set({'date': img.date().format('YYYY-MM-dd')}))\n", | |
"\n", | |
"col_vis = (col.map(vis_rgb))" | |
], | |
"execution_count": null, | |
"outputs": [] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": { | |
"id": "yJPbHrBE2oHF" | |
}, | |
"source": [ | |
"Get thumbnails of the visualization collection downloaded locally" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"metadata": { | |
"id": "8-kzRms2zZJG" | |
}, | |
"source": [ | |
"thumb_params = {\n", | |
" 'dimensions': 5000,\n", | |
" 'region': ee.Geometry.BBox(aoi['xmin'], aoi['ymin'], aoi['xmax'], aoi['ymax']),\n", | |
" 'crs': 'EPSG:4326',\n", | |
" 'format': 'PNG'\n", | |
"}\n", | |
"\n", | |
"dates = col_vis.aggregate_array('date').getInfo()\n", | |
"\n", | |
"frames = []\n", | |
"for count, date in enumerate(dates):\n", | |
" img_vis = col_vis.filter(ee.Filter.eq('date', date)).first()\n", | |
" img_url = img_vis.getThumbURL(thumb_params)\n", | |
" img_name = str(count).zfill(3) + '.png'\n", | |
" frames.append(img_name)\n", | |
" print(img_name)\n", | |
" response = requests.get(img_url)\n", | |
" with open(img_name, 'wb') as fd:\n", | |
" fd.write(response.content)" | |
], | |
"execution_count": null, | |
"outputs": [] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": { | |
"id": "j8tCsOuo201f" | |
}, | |
"source": [ | |
"Make a directory to hold altered images" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"metadata": { | |
"id": "q5t7GaKazp6k" | |
}, | |
"source": [ | |
"alt_dir = 'alt'\n", | |
"if not os.path.exists(alt_dir):\n", | |
" os.mkdir(alt_dir)" | |
], | |
"execution_count": null, | |
"outputs": [] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": { | |
"id": "_ehI4XRH23w9" | |
}, | |
"source": [ | |
"Use cartopy to change the projection of the downloaded images to North Polar Stereo, set the extent of the output plot, and clip by a circle." | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"metadata": { | |
"id": "CAVq5wBizzRd" | |
}, | |
"source": [ | |
"def make_plot(frame):\n", | |
" fig = plt.figure(figsize=[8, 8])\n", | |
" ax = plt.axes(projection=ccrs.NorthPolarStereo())\n", | |
" ax.spines['geo'].set_edgecolor('none')\n", | |
" ax.set_extent([aoi['xmin'], aoi['xmax'], aoi['ymin'], aoi['ymax']], ccrs.PlateCarree())\n", | |
" ax.add_feature(cfeature.COASTLINE, edgecolor='grey')\n", | |
" ax.gridlines()\n", | |
"\n", | |
" theta = np.linspace(0, 2*np.pi, 100)\n", | |
" center, radius = [0.5, 0.5], 0.5\n", | |
" verts = np.vstack([np.sin(theta), np.cos(theta)]).T\n", | |
" circle = mpath.Path(verts * radius + center)\n", | |
"\n", | |
" ax.set_boundary(circle, transform=ax.transAxes)\n", | |
" img = plt.imread(frame)\n", | |
" ax.imshow(img, extent=(aoi['xmin'], aoi['xmax'], aoi['ymin'], aoi['ymax']), origin='upper', transform=ccrs.PlateCarree())\n", | |
" fig.savefig(os.path.join(alt_dir, frame), bbox_inches='tight', pad_inches=0.5, facecolor='grey', edgecolor='none')\n", | |
" plt.close()\n", | |
"\n", | |
"for frame in frames:\n", | |
" print(frame)\n", | |
" make_plot(frame)" | |
], | |
"execution_count": null, | |
"outputs": [] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": { | |
"id": "I0hm72pz3P5g" | |
}, | |
"source": [ | |
"Make an animation from the frames" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"metadata": { | |
"id": "y3Qwwesa0mMk" | |
}, | |
"source": [ | |
"outfile = 'animation'\n", | |
"cmd = 'ffmpeg -framerate 10 -i alt/%03d.png -movflags faststart -pix_fmt yuv420p -vf \"scale=trunc(iw/2)*2:trunc(ih/2)*2\"'\n", | |
"\n", | |
"cmd_mp4 = f'{cmd} {outfile}.mp4' \n", | |
"os.system(cmd_mp4)\n", | |
"\n", | |
"cmd_gif = f'{cmd} {outfile}.gif' \n", | |
"os.system(cmd_gif)" | |
], | |
"execution_count": null, | |
"outputs": [] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": { | |
"id": "Y23_EjqZ497C" | |
}, | |
"source": [ | |
"Download the MP4 and GIF animations" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"metadata": { | |
"id": "pnbo395D8ToS" | |
}, | |
"source": [ | |
"from google.colab import files\n", | |
"files.download(f'{outfile}.mp4')\n", | |
"files.download(f'{outfile}.gif') " | |
], | |
"execution_count": null, | |
"outputs": [] | |
} | |
] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment