I am trying to transform a masked array, result of a NETCFD4 file, to a raster.
The array is saved as a masked array, with shape (500,805)
, and the mask is the value 32768.0.
The array looks like:
import os
import gdal, ogr, osr
import numpy as np
import fiona as fn
import pandas as pd
import geopandas as gpd
import rasterio as rt
import scipy as sp
import matplotlib.pyplot as plt
masked_array(
data=[[--, --, --, ..., 16.31, 16.39, 16.35],
[--, --, --, ..., 16.31, 16.42, 16.34],
[--, --, --, ..., 16.29, 16.330000000000002, 16.39],
...,
[--, --, --, ..., 27.650000000000002, 28.54, 28.57],
[--, --, --, ..., 26.64, 28.59, 27.92],
[--, --, --, ..., 27.84, 27.830000000000002, 27.54]],
mask=[[ True, True, True, ..., False, False, False],
[ True, True, True, ..., False, False, False],
[ True, True, True, ..., False, False, False],
...,
[ True, True, True, ..., False, False, False],
[ True, True, True, ..., False, False, False],
[ True, True, True, ..., False, False, False]],
fill_value=32768.0)
I have written the following method, based on many posts from around. However, it fails whenever I save the file as a raster. The maximum value I get, is the one for the fill = 32768.0
def array2raster(newRasterfn, rasterOrigin, pixelWidth, pixelHeight, array, path):
reversed_arr = array[::-1]
cols = reversed_arr.shape[1]
rows = reversed_arr.shape[0]
originX = rasterOrigin[0]
originY = rasterOrigin[1]
driver = gdal.GetDriverByName('GTiff')
outRaster = driver.Create(newRasterfn, cols, rows, 1, gdal.GDT_Float64)
outRaster.SetGeoTransform((originX, pixelWidth, 0, originY, 0, pixelHeight))
outband = outRaster.GetRasterBand(1)
outband.WriteArray(reversed_arr)
outband.SetNoDataValue(-999)
outRasterSRS = osr.SpatialReference()
outRasterSRS.ImportFromEPSG(4326) # http://spatialreference.org/ref/epsg/32614/
outRaster.SetProjection(outRasterSRS.ExportToWkt())
outband.FlushCache()
I call the function like this.
jan_1950raster = array2raster('jan1950' + '.tif', [lon,lat], cell_size, cell_size, jan_1950, gis)
How can I proceed from here?
I have changed outband.SetNoDataValue(-32768.0)
but the problem remains, I have a raster with these values.
outband.SetNoDataValue
doesn't change the masked values to -999, it just sets some metadata in the output raster that says treat -999 as nodata, but you haven't written any -999 values.