示例#1
0
def ChangeDetection(bands_1993, bands_2000, band_name='SWIR', ndi_of_ndvi=False):
    """ Calculates And Plot Change Detections.

    Band 1 : Blue
			 - Bathymetric mapping, distinguishing soil from vegetation and deciduous from coniferous vegetation

	Band 2 : Green
			 - Emphasizes peak vegetation, which is useful for assessing plant vigor

	Band 3 : Red
			 -  Discriminates vegetation slopes

	Band 4 : Near Infrared (NIR)
			 -  Emphasizes biomass content and shorelines

	Band 5 : Short-wave Infrared (SWIR)
		     - Discriminates moisture content of soil and vegetation (penetrates thin clouds)
	"""

    if band_name == 'SWIR':

        before, after = bands_1993[4], bands_2000[4]
        cmap_diff     = 'seismic_r'
        cmap_rat 	  = 'seismic'

    elif band_name == 'NIR':

        before, after = bands_1993[3], bands_2000[3]
        cmap_diff     = 'Greens'

    elif band_name == 'Red':

        before, after = bands_1993[2], bands_2000[2]
        cmap_diff     = 'RdGy_r'
        cmap_rat 	  = 'seismic'

    elif band_name == 'Green':

        before, after = bands_1993[1], bands_2000[1]
        cmap_diff     = 'YlGn'

    elif band_name == 'Blue':

        before, after = bands_1993[0], bands_2000[0]
        cmap_diff     = 'PuOr'

    else:
        print("Invalid band_number, use one from ['Blue', 'Green', 'Red', 'NIR', 'SWIR']")

    Difference(after, before, title='%s difference [1993 - 2000]' %band_name, cmap=cmap_diff)
    Ratio(after, before,      title='%s ratio [1993 - 2000]' %band_name, cmap=cmap_rat) #only defined cmap_rat for red
    NDI(after, before,        title='%s NDI [1993 - 2000]' %band_name, cmap=cmap_diff)

    if ndi_of_ndvi:
        # suppress RuntimeWarning (probably because of NaN)
        np.seterr(divide='ignore', invalid='ignore')
        ndvi_before = es.normalized_diff(bands_1993[3], bands_1993[2])
        ndvi_after  = es.normalized_diff(bands_2000[3], bands_2000[2])
        NDI_of_NDVI(ndvi_after, ndvi_before, title='NDI of NDVI', cmap='RdYlGn_r')
示例#2
0
def test_normalized_diff_shapes(b1_b2_arrs):
    """Test that two arrays with different shapes returns a ValueError."""

    # Test data
    b1, b2 = b1_b2_arrs
    b2 = b2[0]

    # Check ValueError
    with pytest.raises(ValueError,
                       match="Both arrays should have the same dimensions"):
        es.normalized_diff(b1=b1, b2=b2)
def calcola_ndvi(nir, red, metadatas):
    bands, rows, cols = red.shape
    ndvi = es.normalized_diff(b1=nir[0, :, :], b2=red[0, :, :])
    # ndvi2=np.zeros((rows,cols),dtype="float64")
    #
    for i in range(0, rows):
        for j in range(0, cols):
            appo = ndvi[i, j]
            if math.isnan(appo):
                ndvi[i, j] = 0
                #print(ndvi[i,j])
        #sopra=int(b4[0,i,j]-b8[0,i,j])
        #sotto=int(b4[0,i,j]+b8[0,i,j])
        # if sotto > 0 :
        #     diff=sopra/sotto
        #     ndvi2[i,j]=diff
        #  if math.isnan(diff) is True:
        #     diff=0
        #else:
        #    ndvi2[i,j]=0
    metadatas['dtype'] = "float64"
    metadatas['driver'] = "GTiff"
    metadatas['count'] = 1
    metadatas['nodata'] = 0
    print(metadatas)
    #    with rasterio.open('/Users/glicciardi/Desktop/ndvi.tif','w',**metadatas) as dst:
    #        dst.write(ndvi,1)
    #
    #    dst.close()
    #
    ##    with rasterio.open('/Users/glicciardi/Desktop/ndvi2.tif','w',**metadatas) as dst:
    ##        dst.write(ndvi2,1)
    #
    #    dst.close()
    return ndvi, metadatas
示例#4
0
def NDVI(bands, year):
	"""Normalized Difference Vegetation Index (NDVI)"""

	#ndvi = es.normalized_diff(band4, band3)      # (band4-band3)/(band4+band3)
	ndvi = es.normalized_diff(bands[3], bands[2]) # (band4-band3)/(band4+band3)

	titles = ['Normalized Difference Vegetation Index (NDVI) Year: %s' %year]

	# Turn off bytescale scaling due to float values for NDVI
	ep.plot_bands(ndvi, cmap="RdYlGn", cols=1, title=titles, vmin=-1, vmax=1)

	# Create classes and apply to NDVI results
	ndvi_class_bins    = [-np.inf, 0, 0.25, 0.5, 0.75, np.inf]
	ndvi_landsat_class = np.digitize(ndvi, ndvi_class_bins)

	# Define color map and class names
	ndvi_colors = ListedColormap(['gray', 'y', 'yellowgreen', 'g', 'darkgreen'])
	ndvi_names = ['0.00 No Vegetation','0.25 Bare Area','0.50 Low Vegetation','0.75 Moderate Vegetation','1.00 High Vegetation']

	# Get list of classes
	classes = np.unique(ndvi_landsat_class).tolist()

	fig, ax = plt.subplots(figsize=(8, 8))
	im      = ax.imshow(ndvi_landsat_class, cmap=ndvi_colors)

	ep.draw_legend(im_ax=im, classes=classes, titles=ndvi_names)
	ax.set_title('Normalized Difference Vegetation Index (NDVI) Classes. \nYear: %s' %yr,fontsize=14)
	ax.set_axis_off(); plt.tight_layout()
	plt.show()
示例#5
0
def computeNDVI(nirBand, redBand):
    """
    This function computes the ndvi and plot the results in a scale of -1 to 1
    """
    
    ndvi = es.normalized_diff(nirBand, redBand)
    plt.imshow(ndvi, vmin = -1, vmax = 1, cmap="RdYlGn")
    plt.colorbar()
    plt.show()
示例#6
0
def test_normalized_diff_no_mask(b1_b2_arrs):
    """Test that if result does not include nan values,
    the array is returned as unmasked."""

    # Test data
    b1, b2 = b1_b2_arrs

    n_diff = es.normalized_diff(b1=b1, b2=b2)

    # Output array unmasked
    assert not ma.is_masked(n_diff)
示例#7
0
def test_normalized_diff_mask(b1_b2_arrs):
    """Test that if result does include nan values,
    the array is returned as masked."""

    # Test data
    b1, b2 = b1_b2_arrs
    b2 = b2.astype(float)
    b2[1:, 4:] = np.nan

    n_diff = es.normalized_diff(b1=b1, b2=b2)

    # Output array masked
    assert ma.is_masked(n_diff)
示例#8
0
def test_normalized_diff_inf(b1_b2_arrs):
    """Test that inf values in result are set to nan and
    that array is returned as masked."""

    # Test data
    b1, b2 = b1_b2_arrs
    b2[1:, 4:] = -20

    # Check warning
    with pytest.warns(Warning,
                      match="Divide by zero produced infinity values"):
        n_diff = es.normalized_diff(b1=b1, b2=b2)

    # Inf values set to nan
    assert not np.isinf(n_diff).any()

    # Output array masked
    assert ma.is_masked(n_diff)
示例#9
0
def main():
    all_landsat_post_bands = glob('AOI/cana_band*.tif')
    #'AOI/arroz_band*.tif')
    all_landsat_post_bands.sort()
    landsat_img = []
    landsat_data = []
    band_vectors = []
    cana_bottom_limits = [181, 243, 531, 339, 2281, 1339, 558]
    cana_top_limits = [567, 658, 960, 1081, 3812, 2644, 1982]
    arroz_bottom_limits = [27, 158, 354, 168, 696, 175, 115]
    arroz_top_limits = [720, 830, 1123, 1430, 4060, 3363, 2236]
    for i in range(len(all_landsat_post_bands)):
        landsat_img.append(Image.open(all_landsat_post_bands[i]))
        landsat_data.append(np.array(landsat_img[i]))
        #band_vectors.append(matrix2vector(landsat_data[i], cana_bottom_limits[i], cana_top_limits[i]))
        #band_vectors.append(matrix2vector(landsat_data[i], arroz_bottom_limits[i], arroz_top_limits[i]))

    NIR = matrix3D2matrix2D(landsat_data[3], cana_bottom_limits[3],
                            cana_top_limits[3])
    VIS = matrix3D2matrix2D(landsat_data[0], cana_bottom_limits[0],
                            cana_bottom_limits[0])
    naip_ndvi = es.normalized_diff(NIR, VIS)
    ep.plot_bands(naip_ndvi, cmap="PiYG", scale=False, vmin=-1, vmax=1)
    plt.show()
示例#10
0
import rasterio as rio
import geopandas as gpd
import earthpy as et
import earthpy.spatial as es
import earthpy.plot as ep

# Download data and set working directory
data = et.data.get_data('cold-springs-fire')
os.chdir(os.path.join(et.io.HOME, 'earth-analytics'))

naip_data_path = os.path.join("data", "cold-springs-fire", "naip",
                              "m_3910505_nw_13_1_20150919", "crop",
                              "m_3910505_nw_13_1_20150919_crop.tif")

with rio.open(naip_data_path) as src:
    naip_data = src.read()

# View shape of the data
naip_data.shape

naip_ndvi = es.normalized_diff(naip_data[3], naip_data[0])

ep.plot_bands(
    naip_ndvi,
    cmap='PiYG',
    scale=False,
    vmin=-1,
    vmax=1,
    title="NAIP Derived NDVI\n 19 September 2015 - Cold Springs Fire, Colorado"
)
plt.show()
示例#11
0
    #sub_candidates = fs.ls(link)
    #print(sub_candidates)
    #dev_s3_client.list_objects(link) 
    s3 = boto3.resource('s3')
    s3_client = boto3.client('s3')

    bucket=link.partition('/')[0] 
    my_bucket = s3.Bucket(bucket)
    for my_bucket_object in my_bucket.objects.filter(Prefix=link.partition('/')[2]):
        #print(my_bucket_object)
        print('{0}:{1}'.format(my_bucket.name, my_bucket_object.key))
        with rio.open('s3://{0}/{1}'.format(my_bucket.name, my_bucket_object.key)) as src:
            print("key",my_bucket_object.key)
            print(src.meta)
            # # Load red and NIR bands - note all PlanetScope 4-band images have band order BGRN
            planet_ndvi = es.normalized_diff(src.read(3), src.read(4))
            aug_pla_meta = src.profile
            # Change the count or number of bands from 4 to 5
            aug_pla_meta['count'] = 5
            # Change the data type to float rather than integer
            aug_pla_meta['dtype'] = "float64"
            aug_pla_meta
            
            #convert to float64
            #ndvi_64 = np.array(planet_ndvi, dtype=numpy.float64)
            t = src.transform
            # rescale the metadata
            transform = Affine(t.a * scale, t.b, t.c, t.d, t.e * scale, t.f)
            height = int(src.height / scale)
            width = int(src.width / scale)
            
示例#12
0
from matplotlib.colors import ListedColormap
import earthpy as et
import earthpy.spatial as es
import earthpy.plot as ep
"""Call Landsat 5 input image (a tiff file) with rasterio """

image = rasterio.open(
    '/test_images/subset_0_of_LT05_L1TP_180032_20060727_20180311_01_T1_reprojected.tif'
)
"""Assign names of bands from test image"""

green = image.read(2)
nir = image.read(4)
"""Normalized difference water index"""

ndwi = es.normalized_diff(green, nir)
"""Display output"""

titles = ["Landsat 5 Normalized Difference Water Index"]

ep.plot_bands(ndwi, cmap="gray", cols=1, title=titles)
plt.show()
"""Create output ass a tiff file (one band)"""

meta = image.profile
meta.update(driver='GTiff')
meta.update(count=1)

with rasterio.open('NDWI.tif', 'w', **meta) as file:
    file.write(ndwi, 1)
    file.close()
示例#13
0
)
landsat_path.sort()
arr_st, meta = es.stack(landsat_path, nodata=-9999)


###############################################################################
# Calculate Normalized Difference Vegetation Index (NDVI)
# -------------------------------------------------------
#
# You can calculate NDVI for your dataset using the
# ``normalized_diff`` function from the ``earthpy.spatial`` module.
# Math will be calculated (b1-b2) / (b1 + b2).

# Landsat 8 red band is band 4 at [3]
# Landsat 8 near-infrared band is band 5 at [4]
ndvi = es.normalized_diff(arr_st[4], arr_st[3])


###############################################################################
# Plot NDVI With Colorbar Legend of Continuous Values
# ----------------------------------------------------
#
# You can plot NDVI with a colorbar legend of continuous values using the
# ``plot_bands`` function from the ``earthpy.plot`` module.

titles = ["Landsat 8 - Normalized Difference Vegetation Index (NDVI)"]

# Turn off bytescale scaling due to float values for NDVI
ep.plot_bands(ndvi, cmap="RdYlGn", cols=1, title=titles, vmin=-1, vmax=1)

###############################################################################
# it will only plot that single band. You can turn off the
# colorbar using the ``cbar`` parameter (``cbar=False``).

ep.plot_bands(array_stack[4], cbar=False)
plt.show()

##################################################################################
# Turn Off Scaling
# -----------------
#
# ``ep.plot_bands()`` scales the imagery to a 0-255 scale by default. This range
# of values makes it easier for matplotlib to plot the data. To turn off
# scaling, set the scale parameter to ``False``. Below you
# plot NDVI with scaling turned off in order for the proper range of values
# (-1 to 1) to be displayed. You can use the ``cmap=`` parameter to adjust
# the colormap for the plot

NDVI = es.normalized_diff(array_stack[4], array_stack[3])
ep.plot_bands(NDVI, scale=False, cmap="RdYlGn")
plt.show()

##################################################################################
# Adjust the Number of Columns for a Multi Band Plot
# ---------------------------------------------------
#
# The number of columns used while plotting multiple bands can be changed in order
# to change the arrangement of the images overall.

ep.plot_bands(array_stack, cols=2)
plt.show()