1

I want to subset a 10m sentinel dataset using rasterio window modul. I have tried using the window = from_bounds(...) part in .read() however it requires for me to put in the left top right bottom coordinates.

I want to subset using only the top left coordinates and the height and width of subset in pixels.

Here is what I have tried so far

import rasterio 
from rasterio import plot # for plotting datasets, may not be of use
from rasterio.plot import show_hist # for showing histogram distribution of bands in a daatset, may not be of use
from rasterio.windows import Window , from_bounds, crop# for clipping out only a window from dataset use in part 2
import matplotlib.pyplot as plt #for plotting images
import numpy as np # for doing computations
import os  # to read file paths to the image data
from sklearn import cluster
%matplotlib inline

path_10 =  R'./GRANULE/L2A_T31UET_A025788_20200530T105134/IMG_DATA/R10m'
l_10 = os.listdir(path_10)
tostack_10 = l_10[1:5] #take bands B G R NIR for 10m data
stackpath_10 = [os.path.join(path_10,i) for i in tostack_10]
ds_10 = [rasterio.open( stackpath_10[i], driver='JP2OpenJPEG' ) for i in  range(len( stackpath_10 ))] # list of datasets    

bands_10= [] #array holding all bands as numpy arrays 

# window_= Window( 601200.0, 5773695.0, 700, 500)

for i in range( len(ds_10)):
    bands_10.append( np.array(ds_10[i].read(1 ) , dtype='int32' ) )
    ds_10[i].close()


bands_10 = np.array(bands_10 , dtype='int32') # typecasting from unsigned int to signed
bands_10.shape

This gives me a shape of (4, 10980,10980), which is teh shape of the total scene and not the subset

2

1 Answer 1

0

You can convert your coordinates to a row and col using the DatasetReader.index method, then build a window from that.

Below is a very simple example:

import rasterio 
from rasterio.windows import Window

# Check your coordinate ordering, 
# I wasn't sure which was X and which was Y
ulx, uly = 5773695.0, 601200.0  
width, height = 700, 500

with rasterio.open('/path/to/someraster') as ds:
    # Note - index takes coordinates in X,Y order 
    #        and returns row, col (Y,X order)
    row, col = ds.index(ulx, uly)
    window = Window(row, col, width, height)
    data = ds.read(window)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.