# Separate
landsat = rio.open("./data/landsat8_philly.tif")
c_limit = gpd.read_file("./data/City_Limits.geojson")
c_limit = c_limit.to_crs(landsat.crs.data['init'])
env = c_limit.envelope
envgdf = gpd.GeoDataFrame(gpd.GeoSeries(env))
envgdf = envgdf.rename(columns={0:'geometry'}).set_geometry('geometry')
envgdf = envgdf.to_crs(landsat.crs.data['init'])
sub_limit = gpd.overlay(envgdf,c_limit, how='difference')
city, mask_transform = mask(
dataset=landsat,
shapes=c_limit.geometry,
crop=True,
all_touched=True,
filled=False,
)
suburb, mask_transform = mask(
dataset=landsat,
shapes=sub_limit.geometry,
crop=True,
all_touched=True,
filled=False,
)
c_red = city[3]
c_nir = city[4]
sub_red = suburb[3]
sub_nir = suburb[4]
# Calculate
def calculate_NDVI(nir, red):
"""
Calculate the NDVI from the NIR and red landsat bands
"""
nir = nir.astype(float)
red = red.astype(float)
check = np.logical_and( red.mask == False, nir.mask == False )
ndvi = np.where(check, (nir - red ) / ( nir + red ), np.nan )
return ndvi
city_NDVI = calculate_NDVI(c_nir, c_red)
sub_NDVI = calculate_NDVI(sub_nir, sub_red)
fig, ax = plt.subplots(figsize=(10,10))
landsat_extent = [
landsat.bounds.left,
landsat.bounds.right,
landsat.bounds.bottom,
landsat.bounds.top,
]
img = ax.imshow(city_NDVI,extent=landsat_extent)
c_limit.boundary.plot(ax=ax, edgecolor='gray', facecolor='none', linewidth=4)
plt.colorbar(img)
ax.set_axis_off()
ax.set_title("NDVI in City of Philadelphia", fontsize=18);