I have this very simple code:
import numpy as np
from rasterio.transform import Affine
nx = 5
maxx = 4.0
minx = -4.0
res = (maxx - minx) / nx
maxy = 3.0
miny = -3.0
ny = int((maxy - miny) / res)
x = np.linspace(minx, maxx, nx)
y = np.linspace(miny, maxy, ny)
z = numpy.array([
[-1, 10, 15.1, 6.3, 50.4],
[26.7, -1, 15.7, 40.7, 5],
[5, -1, 9.0, 38, 40.3],
])
cmap = plt.get_cmap("nipy_spectral")
with rasterio.open(
os.path.join(os.path.dirname(__file__), "test.tiff"),
"w",
driver='GTiff',
height=z.shape[0],
width=z.shape[1],
count=1,
dtype=z.dtype,
crs='+proj=latlong',
transform=Affine.translation(x[0]-res/2, y[0]-res/2) * Affine.scale(res, res),
nodata=-1,
) as df:
df.colorinterp = [ColorInterp.palette]
# df.write_colormap(1, cmap)
df.write(z, 1)
It create a basic image when drag and drop in QGIS:
I would like to drag and drop this file in Qgis and it have the cmap working from matplotlib named nipy_spectral
:
The line # df.write_colormap(1, cmap)
is working only for uint8
data (when cmap
is a dictionary using int values as keys) according to the documentation, but there is no documentation about float data...
My question and need is simple but there is nothing in documentation: how to apply this cmap to my df
rasterio object in the python code?
For the moment it is working when I force data to be uint8 but i can have only 256 values, which is not enough...
An other solution is to add manually in qgis a predefined cmap like this:
Then it is possible to export the style as a folder. Maybe it is possible to automatically apply this style to tiff file using qgis.core python module?