3 followers Follow

NDVI in Python


I am very new to Python and I'm currently in the process of creating a script to automate a few of the tasks that I run in Focus. However, I am not quite sure of how to run NDVI in python. Previously I was able to do this using the Focus EASI modeling window. Does anyone know how I can do this in python?


Kathryn Jenkins Answered

Please sign in to leave a comment.

1 comment


Hi Kathryn,

Thanks for your question. You are now able to complete raster calculations using our new Python API library. The following example outlines how you would run NDVI:

import numpy
from pci.api import gobs, cts, datasource as ds

# get the path to irvine.pix in the demo folder
inputImage = r'E:\demo\irvine.pix'

#open the dataset
with ds.open_dataset(inputImage) as dataset:
    # create a reader which will read bands 3 (red) and 4 (NIR)
    reader = ds.BasicReader(dataset, [3, 4])

    # read the raster. The first two values are offset and the second two are the size
    raster = reader.read_raster(0, 0, 512, 512)

# create a separate 'view' of the array for each channel
red_chan =[:, :, 0]
nir_chan =[:, :, 1]

# convert to 32bit so your NDVI values are floating point and not integers
red_chan_flt = red_chan.astype(numpy.float32)
nir_chan_flt = nir_chan.astype(numpy.float32)

# run the NDVI equation (NIR-R)/(NIR+R) which creates an array (ndvi)
ndvi = (nir_chan_flt - red_chan_flt) / (nir_chan_flt + red_chan_flt)

# create a Raster from your ndvi array
ndviRaster = gobs.array_to_raster(ndvi)

# open the write dataset that you want to write to
with ds.new_dataset(r'E:\PythonTesting\NDVI.pix', 'PCIDSK', '') as write_dataset:
    # create a writer to write the raster
    writer = ds.BasicWriter(write_dataset)

    # create the file on disk based on the size and datatype of ndviRaster

    # write ndviRaster to the new file

Please take a look at our Python API documentation for more information:

Hope this helps,

Sarah Thompson 1 vote