Topics

Iterate over elements in Rasterio window and obtain coordinates using transform.xy


Sean Gillies
 

Hi,

On Wed, Aug 19, 2020 at 6:24 PM <whytefish1@...> wrote:

[Edited Message Follows]

Worked it out using a previous thread, doing it using an affine transform on the window.

Excellent!
 
I would however like to know if the rasterio.transform.xy method can be used when passing col, row from a dataset window, as I would like to get the coordinate for the center of the cell rather than the ul which results from the affine window transform.

Yes. The important detail is that the transform matrix passed to xy() must apply to the window. You can't use the matrix from the dataset's .transform attribute unless your window has its origin at the upper left corner of the dataset. Dataset objects have a window_transform() method that can help compute the new transforms: https://rasterio.readthedocs.io/en/latest/api/rasterio.io.html?highlight=window_transform#rasterio.io.DatasetReader.window_transform.

--
Sean Gillies


whytefish1@...
 
Edited

Worked it out using a previous thread, doing it using an affine transform on the window. 
I would however like to know if the rasterio.transform.xy method can be used when passing col, row from a dataset window, as I would like to get the coordinate for the center of the cell rather than the ul which results from the affine window transform.


whytefish1@...
 

Does a window generated by rasterio maintain the dataset origin and absolute col/row indices?

I'd like to be able to iterate over a window of a dem dataset, find the highest value in the window and return it's lat long coordinates using rasterio.transform.xy or similar.

Obviously the below isn't suitable (the arr is invalid), it illustrates what I'm trying to achieve. Window is generated using slices and row/col high and lows which are provided by a valid function called extract_block.

with rasterio.open(inputraster) as dataset:
        for (x,y) in zip(*nonzero):
            row_low, row_high, col_low, col_high = extract_block(arr,[x,y],windowsize)
            rasteriowindowarr = dataset.read(1,window=Window.from_slices(slice(row_low, row_high), slice(col_low, col_high)))
            with rasterio.open(rasteriowindowarr) as windowarr:
                for i,j in np.ndindex(rasteriowindowarr.shape):
                    coordinatex,coordinatey = rasterio.transform.xy(windowarr.transform, i,j,offset='center')
                    print ("long of result is " + str(coordinatex))
                    print ("lat of result is " + str(coordinatey))