Post

3 followers Follow
0
Avatar

NDVI in Python

Hi,

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?

Thanks,
Kathryn

Kathryn Jenkins Answered

Please sign in to leave a comment.

1 comment

1
Avatar

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 = raster.data[:, :, 0]
nir_chan = raster.data[:, :, 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
    writer.create(ndviRaster)

    # write ndviRaster to the new file
    writer.write_raster(ndviRaster)

Please take a look at our Python API documentation for more information: http://www.pcigeomatics.com/python-api-doc/pci_nspio.html

Hope this helps,
Sarah

Sarah Thompson 1 vote