index attributes not created by raster
astreix95 opened this issue · comments
Dear all, I have tried this function with the following monthly Viirs images
https://ngdc.noaa.gov/eog/viirs/download_dnb_composites.html
Although, importing the tif image, the attribute "affine" is not generated in the raster . Thanks, in advance for your support.
``from affine import Affine
import rasterio as rio
import shapely.geometry
import numpy as np
import os
raster =rio.open("d.tif")
geojson={"type":"GeometryCollection","geometries":[{"type":"Polygon","coordinates":[[[36.451170003671905,13.770399943139031],[36.49818000080741,13.832959942751973],[36.496150000713975,13.851029940207065],[36.46004000184132,13.97618994160023],[36.47336999951867,14.002619937531584],[36.53359000273085,14.183159940666277]]]}]}
def load_raster_with_mask(raster_file, geojson_geometry):
"""
Given a rasterio file and a geojson geometry, return a
numpy masked array of pixel values for coordinates within
that geometry.
Typically the geojson geometry is under the 'geometry' key of
a geojson feature.
You can recover the pixel values for the entire bounding box by
accessing the data
field of the masked array, or the mask
itself by accessing the mask
field.
"""
# get the bounding box, as latitude and longitude
geo_shape = shapely.geometry.shape(geojson_geometry)
lon_min, lat_min, lon_max, lat_max = geo_shape.bounds
# get the bounding box as indices of the raster file
# (note that the order of coordinates gets flipped here,
# the first index is for latitude, the second for longitude)
bottom, left = raster_file.index(lon_min, lat_min)
top, right = raster_file.index(lon_max, lat_max)
raster_window = ((top, bottom+1), (left, right+1))
bounding_box_array = raster_file.read(indexes=1, window=raster_window)
****rfa = raster_file.affine****
bounding_box_affine = Affine(
rfa.a, rfa.b, lon_min,
rfa.d, rfa.e, lat_max
)
inclusion_mask = rasterio.features.rasterize(
shapes=[(geo_shape, 0)],
out_shape=bounding_box_array.shape,
transform=bounding_box_affine,
fill=1,
dtype=np.uint8, # this is the smallest available dtype
)
# create the masked array
masked_data = np.ma.array(
data=bounding_box_array,
mask=inclusion_mask,
)
return masked_data``