PK uNb " plot_calculate_classify_ndvi.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\nCalculate and Classify Normalized Difference Results with EarthPy\n==================================================================\n\nLearn how to calculate and classify normalized difference indices in Python using EarthPy.\nThis example shows how to calculate and classify the normalized difference vegetation\nindex (NDVI) using Landsat 8 data.\n\n\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Calculating Normalized Difference in Python Using EarthPy\n---------------------------------------------------------\n\n
Note
The examples below will show you how to use the ``normalized_diff()`` function\n to calculate the normalized difference vegetation index (NDVI), a commonly\n used remotely sensed index for quantifying vegetation health.
\n\nThe example below walks you through a typical workflow for calculating the normalized\ndifference vegetation index (NDVI) using Landsat 8 data with EarthPy. NDVI provides\na measure of healthy vegetation and ranges in value from -1 to 1. Values closer to\n1 represent healthy, green vegetation. NDVI can be calculated from Landsat 8 data\nusing band 4 (red) and band 5 (near-infrared).\n\nFirst, you will create a stack of bands using Landsat 8 data and then calculate\nNDVI using the ``normalized_diff()`` function. Then, you will plot the NDVI results\nusing a colorbar legend with continuous values. Last, you will classify the NDVI\nresults using threshold values and plot the classified data with a categorical legend.\n\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Import Packages\n---------------\n\nTo begin, import the needed packages. You will use a combination of several EarthPy\nmodules including spatial and plot.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import os\nfrom glob import glob\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import ListedColormap\nimport earthpy as et\nimport earthpy.spatial as es\nimport earthpy.plot as ep\n\n# Get data and set your home working directory\ndata = et.data.get_data(\"cold-springs-fire\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Import Example Data\n-------------------\n\nTo get started, make sure your directory is set. Then, create a stack from all of\nthe Landsat .tif files (one per band).\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"os.chdir(os.path.join(et.io.HOME, \"earth-analytics\"))\n\n# Stack the Landsat 8 bands\n# This creates a numpy array with each \"layer\" representing a single band\nlandsat_path = glob(\n \"data/cold-springs-fire/landsat_collect/LC080340322016072301T1-SC20180214145802/crop/*band*.tif\"\n)\nlandsat_path.sort()\narr_st, meta = es.stack(landsat_path)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Calculate Normalized Difference Vegetation Index (NDVI)\n-------------------------------------------------------\n\nYou can calculate NDVI for your dataset using the\n``normalized_diff`` function from the ``earthpy.spatial`` module.\nMath will be calculated (b1-b2) / (b1 + b2).\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Landsat 8 red band is band 4 at [3]\n# Landsat 8 near-infrared band is band 5 at [4]\nndvi = es.normalized_diff(arr_st[4], arr_st[3])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Plot NDVI With Colorbar Legend of Continuous Values\n----------------------------------------------------\n\nYou can plot NDVI with a colorbar legend of continuous values using the\n``plot_bands`` function from the ``earthpy.plot`` module.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"titles = [\"Landsat 8 - Normalized Difference Vegetation Index (NDVI)\"]\n\n# Turn off bytescale scaling due to float values for NDVI\nep.plot_bands(\n ndvi, cmap=\"RdYlGn\", cols=1, title=titles, scale=False, vmin=-1, vmax=1\n)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Classify NDVI\n-------------\n\nNext, you can categorize (or classify) the NDVI results into useful classes.\nValues under 0 will be classified together as no vegetation. Additional classes\nwill be created for bare area and low, moderate, and high vegetation areas.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Create classes and apply to NDVI results\nndvi_class_bins = [-np.inf, 0, 0.1, 0.25, 0.4, np.inf]\nndvi_landsat_class = np.digitize(ndvi, ndvi_class_bins)\n\n# Define class names\nndvi_cat_names = [\n \"No Vegetation\",\n \"Bare Area\",\n \"Low Vegetation\",\n \"Moderate Vegetation\",\n \"High Vegetation\",\n]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Plot Classified NDVI With Categorical Legend\n--------------------------------------------\n\nYou can plot the classified NDVI with a categorical legend using the\n``draw_legend`` function from the ``earthpy.plot`` module.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Define color map\nnbr_colors = [\"gray\", \"y\", \"yellowgreen\", \"g\", \"darkgreen\"]\nnbr_cmap = ListedColormap(nbr_colors)\n\nfig, ax = plt.subplots(figsize=(12, 12))\n\nim = ax.imshow(ndvi_landsat_class, cmap=nbr_cmap)\n\n# Get list of classes\nclasses = np.unique(ndvi_landsat_class)\nclasses = classes.tolist()\n\nep.draw_legend(im_ax=im, classes=classes, titles=ndvi_cat_names)\n\nax.set_title(\n \"Landsat 8 - Normalized Difference Vegetation Index (NDVI) Classes\",\n fontsize=14,\n)\nax.set_axis_off()\n\n# Auto adjust subplot to fit figure size\nplt.tight_layout()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK uN plot_draw_legend_docs.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\nCustom Legends with EarthPy\n===========================\n\nLearn how to create discrete legends for raster plots with classes that you define in Python using EarthPy.\n\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Plotting Data in Python Using EarthPy\n-------------------------------------\n\nNote
The examples below will show you how to use the ``draw_legend()`` function for creating plots
\n\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Plot Continuous Data\n---------------------\n\nLet's explore a simple plot using EarthPy. To begin, import the needed packages\nand create an array to be plotted. Below we plot the data as continuous with a colorbar\nusing the ``plot_bands()`` function.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\nimport earthpy.plot as ep\nimport numpy as np\n\n# Create a numpy array. Let's pretend this is what you want to plot.\narr = np.random.randint(4, size=(5, 5))\n\n# When plot_bands is updated a cbar will be here as well\nep.plot_bands(arr)\nplt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Create Custom Discrete Legends with Earthpy\n-------------------------------------------\nIf you want to create a custom categorical legend, you can use the ``ep.draw_legend()`` function.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"f, ax = plt.subplots(figsize=(8, 5))\nim = ax.imshow(arr)\nep.draw_legend(im)\nplt.tight_layout()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Customize Discrete Legends\n---------------------------\nBy default the draw_legend function creates a legend with default categories.\nYou can customize the legend by adding titles.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"f, ax = plt.subplots(figsize=(8, 5))\nim = ax.imshow(arr)\nep.draw_legend(im, titles=[\"Small\", \"Bigger\", \"Even Bigger\", \"Ginormous\"])\nplt.tight_layout()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Discrete Legends With Missing Values in the Array\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nNow let's pretend that you are creating a series of classified plots. You may have a range of\nvalues that are expected between 0-4. However not all of your data has all values\nIn this case, your legend won't be able to by default create 4 categories because one\ndoesn't exist in your data. In this instance, you can specify the values explicitly:\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"new_arr = arr.copy()\nnew_arr[new_arr == 0] = 1\n\nf, ax = plt.subplots(figsize=(8, 5))\nim = ax.imshow(new_arr)\nep.draw_legend(\n im,\n titles=[\"Small\", \"Bigger\", \"Even Bigger\", \"Ginormous\"],\n classes=[0, 1, 2, 3],\n)\nplt.tight_layout()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Custom Colormaps and Ensuring Cmaps Apply to All Valid Classes\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nYou can customize the color map used in your plot too. Notice that in this example,\n4 category colors are rendered. Yet, the image only contains three values and thus will be\nrendered using three colors. The three colors used to render the image are incorrect by default.\nThe colors begin at white and end at black even though the value of 0 which should be black\nis missing from the data.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"f, ax = plt.subplots(figsize=(8, 5))\nim = ax.imshow(new_arr, cmap=\"Greys_r\")\nep.draw_legend(\n im,\n titles=[\"Small\", \"Bigger\", \"Even Bigger\", \"Ginormous\"],\n classes=[0, 1, 2, 3],\n)\nplt.tight_layout()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Specify vmin and vmax to set the colormap range\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIn this case, you can use the ``vmin`` and ``vmax`` arguments to set the range of values to use for the colormap.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"f, ax = plt.subplots(figsize=(8, 5))\nim = ax.imshow(new_arr, cmap=\"Greys_r\", vmin=0, vmax=3)\nep.draw_legend(\n im,\n titles=[\"Small\", \"Bigger\", \"Even Bigger\", \"Ginormous\"],\n classes=[0, 1, 2, 3],\n)\nplt.tight_layout()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK uN^w徹 plot_stack_masks.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\nMask and Plot Remote Sensing Data with EarthPy\n==============================================\n\nLearn how to mask out pixels in a raster dataset. This example shows how to apply a cloud mask to\nLandsat 8 data.\n\n\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Plotting with EarthPy\n---------------------\n\nNote
Below we walk through a typical workflow using Landsat data with EarthPy.
\n\nThe example below uses Landsat 8 data. In the example below, the landsat_qa layer is the\nquality assurance data layer that comes with Landsat 8 to identify pixels that may represent\ncloud, shadow and water. The mask values used below are suggested values associated with the\nlandsat_qa layer that represent pixels with clouds and cloud shadows.\n\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Import Packages\n------------------------------\n\nTo begin, import the needed packages. You will use a combination of several EarthPy\nmodules including spatial, plot and mask.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from glob import glob\nimport os\nimport matplotlib.pyplot as plt\nimport rasterio as rio\nfrom rasterio.plot import plotting_extent\nimport earthpy as et\nimport earthpy.spatial as es\nimport earthpy.plot as ep\nimport earthpy.mask as em\n\n# Get data and set your home working directory\ndata = et.data.get_data(\"cold-springs-fire\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Import Example Data\n------------------------------\nTo get started, make sure your directory is set. Create a stack from all of the\nLandsat .tif files (one per band) and import the ``landsat_qa`` layer which provides\nthe locations of cloudy and shadowed pixels in the scene.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"os.chdir(os.path.join(et.io.HOME, \"earth-analytics\"))\n\n# Stack the landsat bands\n# This creates a numpy array with each \"layer\" representing a single band\nlandsat_paths_pre = glob(\n \"data/cold-springs-fire/landsat_collect/LC080340322016070701T1-SC20180214145604/crop/*band*.tif\"\n)\nlandsat_paths_pre.sort()\narr_st, meta = es.stack(landsat_paths_pre)\n\n# Import the landsat qa layer\nwith rio.open(\n \"data/cold-springs-fire/landsat_collect/LC080340322016070701T1-SC20180214145604/crop/LC08_L1TP_034032_20160707_20170221_01_T1_pixel_qa_crop.tif\"\n) as landsat_pre_cl:\n landsat_qa = landsat_pre_cl.read(1)\n landsat_ext = plotting_extent(landsat_pre_cl)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Plot Histogram of Each Band in Your Data\n----------------------------------------\nYou can view a histogram for each band in your dataset by using the\n``hist()`` function from the ``earthpy.plot`` module.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"ep.hist(arr_st)\nplt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Customize Histogram Plot with Titles and Colors\n-----------------------------------------------\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"ep.hist(\n arr_st,\n colors=[\"blue\"],\n title=[\n \"Band 1\",\n \"Band 2\",\n \"Band 3\",\n \"Band 4\",\n \"Band 5\",\n \"Band 6\",\n \"Band 7\",\n ],\n)\nplt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"View Single Band Plots\n-----------------------------------------------\nNext, have a look at the data, it looks like there is a large cloud that you\nmay want to mask out.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"ep.plot_bands(arr_st)\nplt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Mask the Data\n-----------------------------------------------\nYou can use the EarthPy ``mask()`` function to handle this cloud.\nTo begin you need to have a layer that defines the pixels that\nyou wish to mask. In this case, the ``landsat_qa`` layer will be used.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"ep.plot_bands(\n landsat_qa,\n title=\"The Landsat QA Layer Comes with Landsat Data\\n It can be used to remove clouds and shadows\",\n)\nplt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Plot The Masked Data\n~~~~~~~~~~~~~~~~~~~~~\nNow apply the mask and plot the masked data. The mask applies to every band in your data.\nThe mask values below are values documented in the Landsat 8 documentation that represent\nclouds and cloud shadows.\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Generate array of all possible cloud / shadow values\ncloud_shadow = [328, 392, 840, 904, 1350]\ncloud = [352, 368, 416, 432, 480, 864, 880, 928, 944, 992]\nhigh_confidence_cloud = [480, 992]\n\n# Mask the data\nall_masked_values = cloud_shadow + cloud + high_confidence_cloud\narr_ma = em.mask_pixels(arr_st, landsat_qa, vals=all_masked_values)\n\n# sphinx_gallery_thumbnail_number = 5\nep.plot_rgb(\n arr_ma, rgb=[4, 3, 2], title=\"Array with Clouds and Shadows Masked\"\n)\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK uNb " plot_calculate_classify_ndvi.ipynbPK uN 1 plot_draw_legend_docs.ipynbPK uN^w徹 n5 plot_stack_masks.ipynbPK [Q