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

Last change on this file since 371 was 348, checked in by neteler, 13 years ago

set correctly svn propset

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

Search

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