My problem is similar to "ValueError: negative dimensions are not allowed" when using raster created from NetCDF
I am working on a raster that I generated from the interpolation of some points, but the rasters are inverted (north down). When I try to do zonal statistics with Rasterstats this error is generated: "ValueError: negative dimensions are not allowed".
I don't know how to fix the transform.
This is the code I used for the interpolation (https://hatarilabs.com/ih-en/how-to-create-a-geospatial-raster-from-xy-data-with-python-pandas-and-rasterio-tutorial)
import numpy as np
import pandas as pd
from scipy.interpolate import griddata
import rasterio
chemData = pd.read_csv(r'path201012円.csv')
points = list(zip(chemData.longitude,chemData.latitude))
values = chemData.sm.values
#define raster resolution
rRes = 0.225
#create coord ranges over the desired raster extension
xRange = np.arange(chemData.longitude.min(),chemData.longitude.max()+rRes,rRes)
yRange = np.arange(chemData.latitude.min(),chemData.latitude.max()+rRes,rRes)
#create arrays of x,y over the raster extension
gridX,gridY = np.meshgrid(xRange, yRange)
gridPh = griddata(points, values, (gridX,gridY), method='cubic')
#definition of the raster transform array
from rasterio.transform import Affine
transform = Affine.translation(gridX[0][0]-rRes/2, gridY[0][0]-rRes/2)*Affine.scale(rRes,rRes)
print(transform)
#get crs as wkt
#from rasterio.crs import CRS
#rasterCrs=rasterio.crs.CRS.from_epsg(4326)
#definition, register and close of interpolated raster
interpRaster = rasterio.open('interpRaster_cubic.tif',
'w',
driver='GTiff',
height=gridPh.shape[0],
width=gridPh.shape[1],
count=1,
dtype=gridPh.dtype,
transform=transform,
)
interpRaster.write(gridPh,1)
interpRaster.close()
This is the resulting transform of the code:
| 0.23, 0.00, -79.87 |
| 0.00, 0.23, -3.94 |
| 0.00, 0.00, 1.00 |
The origin points have these coordinates:
- upper left: lat = 12.956, lon = -79.755
- lower right: lat = -3.828, lon = -66.009
1 Answer 1
Your Affine transform is incorrect, the transform.e
element should be negative (because raster map coordinates are bottom up, but pixel coordinates are top down).
Change:
transform = Affine.translation(gridX[0][0]-rRes/2, gridY[0][0]-rRes/2)*Affine.scale(rRes,rRes)
To:
transform = Affine.translation(gridX[0][0]-rRes/2, gridY[0][0]-rRes/2)*Affine.scale(rRes,-rRes)
Note the negative -rRes
as the 2nd argument in Affine.scale(rRes,-rRes)
Explore related questions
See similar questions with these tags.