Code takes a netCDF4 file and converts the data to GeoTiff:

import numpy as np, sys
from osgeo import gdal
from osgeo import osr
import netCDF4


time = f.variables["time"]
lon = f.variables["lon"]
lat = f.variables["lat"]
data = f.variables["data"]
dims = f.dimensions
xsize = len(dims['lon'])
ysize = len(dims['lat'])

lonarray = np.array(lon)
latarray = np.array(lat)
dataarray = np.array(data)

# get bounds
xmin,ymin,xmax,ymax = [lonarray.min(),latarray.min(),lonarray.max(),latarray.max()]

# no. rows and columns
nrows,ncols = np.shape(dataarray)

# resolution of x/y
xres = (xmax-xmin)/float(ncols)
yres = (ymax-ymin)/float(nrows)

geot=(xmin,xres,0,ymax,0, -yres)

output_raster = gdal.GetDriverByName('GTiff').Create('myraster.tif',ncols,
nrows, 1 ,gdal.GDT_CInt16, options = ['PHOTOMETRIC=MINISWHITE'])  # Open the file

output_raster.SetGeoTransform(geot)            # Specify its coordinates

srs = osr.SpatialReference()                           # Establish its coordinate encoding

srs.ImportFromEPSG(4326)                               # This one specifies WGS84 lat long.

output_raster.SetProjection(srs.ExportToWkt())         # Exports the coordinate system
                                                       # to the file
output_raster.GetRasterBand(1).WriteArray(dataarray)   # Writes my array to the raster


del output_raster

After I load the Geotif into Arc Globe, the min value is black, ie. the ['PHOTOMETRIC=MINISWHITE'] tag has not done what I expected.


I solved this by writing a function to invert my data.

def invert_dataset(min, max, data):

for i, row in enumerate(data):
    for j, value in enumerate(row):
        A = value - min
        inverted_value = max - A
        data[i][j] = inverted_value
return data

I didn't use PIL as it returned an error when trying to open my tiff image.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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