source: trunk/zoo-project/zoo-services/gdal/ndvi/cgi-env/ndvi.py @ 334

Last change on this file since 334 was 334, checked in by root, 13 years ago

Add the Normalized Difference Vegetation Index service.

File size: 4.1 KB
Line 
1#! /usr/bin/env python
2
3import sys, os, struct
4
5import osgeo.gdal as gdal
6
7# Calculate and output NDVI from raster bands
8def ExtractNDVI(conf, inputs, outputs):
9   
10    # Open the input dataset
11    gdal.FileFromMemBuffer('/vsimem//temp.tif', inputs["raster"]["value"])
12    dataset = gdal.Open( '/vsimem//temp.tif')
13    if dataset is None:
14        conf["lenv"]["message"]="The dataset could not be openned properly"
15        return 4
16
17    # Create the output dataset
18    driver = gdal.GetDriverByName( "GTiff" )
19    # Get the spatial information from the input file
20    geoTransform=None
21    geoProjection=None
22    print >> sys.stderr,dir(dataset) 
23    try:
24        geoTransform = dataset.GetGeoTransform()
25    except:
26        print >> sys.stderr, "Unable to load geotransform"
27    try:
28        geoProjection = dataset.GetProjection()
29    except:
30        print >> sys.stderr, "Unable to load projection"
31
32    # Create an output file of the same size as the inputted
33    # image but with only 1 output image band.
34    newDataset = driver.Create("/vsimem//output"+conf["lenv"]["sid"], \
35                               dataset.RasterXSize, dataset.RasterYSize,1, \
36                               gdal.GDT_Float32)
37    # Set spatial informations of the new image.
38    if geoTransform:
39        newDataset.SetGeoTransform(geoTransform)
40    if geoProjection:
41        newDataset.SetProjection(geoProjection)
42    if newDataset is None:
43        conf["lenv"]["message"]='Could not create output image'
44        return 4
45   
46    # Get the RED and NIR image bands of the image
47    red_id=int(inputs["red"]["value"])
48    nir_id=int(inputs["nir"]["value"])
49    red_band = dataset.GetRasterBand(red_id) # RED BAND
50    nir_band = dataset.GetRasterBand(nir_id) # NIR BAND
51
52    # Loop through each line in turn.
53    numLines = red_band.YSize
54    for line in range(numLines):
55        # Define variable for output line.
56        outputLine = ''
57        # Read in data for the current line from the
58        # image band representing the red wavelength
59        red_scanline = red_band.ReadRaster( 0, line, red_band.XSize, 1, \
60                                          red_band.XSize, 1, gdal.GDT_Float32 )
61        # Unpack the line of data to be read as floating point data
62        red_tuple = struct.unpack('f' * red_band.XSize, red_scanline)
63           
64        # Read in data for the current line from the
65        # image band representing the NIR wavelength
66        nir_scanline = nir_band.ReadRaster( 0, line, nir_band.XSize, 1, \
67                                          nir_band.XSize, 1, gdal.GDT_Float32 )
68        # Unpack the line of data to be read as floating point data
69        nir_tuple = struct.unpack('f' * nir_band.XSize, nir_scanline)
70
71        # Loop through the columns within the image
72        for i in range(len(red_tuple)):
73            # Calculate the NDVI for the current pixel.
74            ndvi_lower = (nir_tuple[i] + red_tuple[i])
75            ndvi_upper = (nir_tuple[i] - red_tuple[i])
76            ndvi = 0
77            # Becareful of zero divide
78            if ndvi_lower == 0:
79                ndvi = 0
80            else:
81                ndvi = ndvi_upper/ndvi_lower
82            # Add the current pixel to the output line
83            outputLine = outputLine + struct.pack('f', ndvi)
84        # Write the completed line to the output image
85        newDataset.GetRasterBand(1).WriteRaster(0, line, red_band.XSize, 1, \
86                                         outputLine, buf_xsize=red_band.XSize, 
87                                         buf_ysize=1, buf_type=gdal.GDT_Float32)
88   
89        # Delete the output line following write
90        del outputLine
91    print >> sys.stderr,'NDVI Calculated and Outputted to File'
92    print >> sys.stderr,dir(newDataset)
93    newDataset.FlushCache()
94    vsiFile=gdal.VSIFOpenL("/vsimem//output"+conf["lenv"]["sid"],"r")
95    i=0
96    while gdal.VSIFSeekL(vsiFile,0,os.SEEK_END)>0:
97        i+=1
98    fileSize=gdal.VSIFTellL(vsiFile)
99    gdal.VSIFSeekL(vsiFile,0,os.SEEK_SET)
100    outputs["raster"]["value"]=gdal.VSIFReadL(fileSize,1,vsiFile)
101    gdal.Unlink("/vsimem//output"+conf["lenv"]["sid"])
102    return 3
Note: See TracBrowser for help on using the repository browser.

Search

Context Navigation

ZOO Sponsors

http://www.zoo-project.org/trac/chrome/site/img/geolabs-logo.pnghttp://www.zoo-project.org/trac/chrome/site/img/neogeo-logo.png http://www.zoo-project.org/trac/chrome/site/img/apptech-logo.png http://www.zoo-project.org/trac/chrome/site/img/3liz-logo.png http://www.zoo-project.org/trac/chrome/site/img/gateway-logo.png

Become a sponsor !

Knowledge partners

http://www.zoo-project.org/trac/chrome/site/img/ocu-logo.png http://www.zoo-project.org/trac/chrome/site/img/gucas-logo.png http://www.zoo-project.org/trac/chrome/site/img/polimi-logo.png http://www.zoo-project.org/trac/chrome/site/img/fem-logo.png http://www.zoo-project.org/trac/chrome/site/img/supsi-logo.png http://www.zoo-project.org/trac/chrome/site/img/cumtb-logo.png

Become a knowledge partner

Related links

http://zoo-project.org/img/ogclogo.png http://zoo-project.org/img/osgeologo.png