Skip to content
Permalink
Browse files
did some work on the gdal bindings
git-svn-id: http://sextante.googlecode.com/svn/trunk/soft/bindings/qgis-plugin@68 881b9c09-3ef8-f3c2-ec3d-21d735c97f4d
  • Loading branch information
volayaf committed Apr 10, 2012
1 parent f499c85 commit 69bc4a084ff1fdbdba467bd77a8e6dda602724b5
@@ -10,6 +10,10 @@
from sextante.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException
import traceback
from sextante.core.SextanteLog import SextanteLog
from sextante.outputs.OutputVector import OutputVector
from sextante.outputs.OutputRaster import OutputRaster
from sextante.outputs.OutputTable import OutputTable
from sextante.outputs.OutputHTML import OutputHTML

class GeoAlgorithm:

@@ -72,6 +76,7 @@ def execute(self, progress):
Raises a GeoAlgorithmExecutionException in case anything goes wrong.'''
self.setOutputCRSFromInputLayers()
self.resolveTemporaryOutputs()
self.checkOutputFileExtensions()
try:
self.processAlgorithm(progress)
return not self.canceled
@@ -87,6 +92,29 @@ def execute(self, progress):
SextanteLog.addToLog(SextanteLog.LOG_ERROR, lines)
raise GeoAlgorithmExecutionException(str(e))

def checkOutputFileExtensions(self):
'''Checks if the values of outputs are correct and have one of the supported output extensions.
If not, it adds the first one of the supported extensions, which is assumed to be the default one'''
for out in self.outputs:
if (not out.hidden) and out.value != None:
if isinstance(out, OutputRaster):
exts = self.provider.getSupportedOutputRasterLayerExtensions()
elif isinstance(out, OutputVector):
exts = self.provider.getSupportedOutputVectorLayerExtensions()
elif isinstance(out, OutputTable):
exts = self.provider.getSupportedOutputTableExtensions()
elif isinstance(out, OutputHTML):
exts =["html", "htm"]
else:
continue
idx = out.value.rfind(".")
if idx == -1:
out.value = out.value + "." + exts[0]
else:
ext = out.value[idx + 1:]
if ext not in exts:
out.value = out.value + "." + exts[0]

def resolveTemporaryOutputs(self):
'''sets temporary outputs (output.value = None) with a temporary file instead'''
for out in self.outputs:
@@ -18,7 +18,7 @@ def initialize():
SextanteConfig.addSetting(Setting("General", SextanteConfig.USE_SELECTED, "Use only selected features in external application", True))
SextanteConfig.addSetting(Setting("General", SextanteConfig.SHOW_RECENT_ALGORITHMS, "Show recently executed algorithms", True))
SextanteConfig.addSetting(Setting("General", SextanteConfig.OUTPUT_FOLDER,
"Output folder", os.path.join(SextanteUtils.userFolder(),"outputs" )))
"Output folder", SextanteUtils.tempFolder()))
SextanteConfig.addSetting(Setting("General", SextanteConfig.RASTER_STYLE,"Style for raster layers",""))
SextanteConfig.addSetting(Setting("General", SextanteConfig.VECTOR_POINT_STYLE,"Style for point layers",""))
SextanteConfig.addSetting(Setting("General", SextanteConfig.VECTOR_LINE_STYLE,"Style for line layers",""))
@@ -7,6 +7,12 @@
from sextante.gdal.GdalAlgorithm import GdalAlgorithm
from sextante.gdal.nearblack import nearblack
from sextante.gdal.information import information
from sextante.gdal.GdalUtils import GdalUtils
from sextante.gdal.warp import warp
from sextante.gdal.rgb2pct import rgb2pct
from sextante.gdal.translate import translate
from sextante.gdal.pct2rgb import pct2rgb
from sextante.gdal.merge import merge

class GdalAlgorithmProvider(AlgorithmProvider):

@@ -44,7 +50,7 @@ def _loadAlgorithms(self):
def createAlgsList(self):
#First we populate the list of algorihtms with those created extending
#GeoAlgorithm directly (those that execute GDAL using the console)
self.preloadedAlgs = [nearblack(), information()]
self.preloadedAlgs = [nearblack(), information(), warp(), translate(), rgb2pct(), pct2rgb(), merge()]
#And then we add those that are created as python scripts
folder = self.scriptsFolder()
for descriptionFile in os.listdir(folder):
@@ -55,3 +61,6 @@ def createAlgsList(self):
self.preloadedAlgs.append(alg)
except WrongScriptException,e:
SextanteLog.addToLog(SextanteLog.LOG_ERROR,e.msg)

def getSupportedOutputRasterLayerExtensions(self):
return GdalUtils.getSupportedRasterExtensions()
@@ -1,10 +1,14 @@
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import subprocess
from sextante.core.SextanteLog import SextanteLog
import os
import gdal

class GdalUtils():

supportedRasters = None

@staticmethod
def runGdal(commands, progress):
settings = QSettings()
@@ -25,4 +29,44 @@ def runGdal(commands, progress):
def getConsoleOutput():
return GdalUtils.consoleOutput

@staticmethod
def getSupportedRasters():
'''this has been adapted from GdalTools plugin'''
if GdalUtils.supportedRasters != None:
return GdalUtils.supportedRasters

if gdal.GetDriverCount() == 0:
gdal.AllRegister()

GdalUtils.supportedRasters = {}
for i in range(gdal.GetDriverCount()):
driver = gdal.GetDriver(i)
if driver == None:
continue

shortName = str(QString(driver.ShortName).remove( QRegExp( '\(.*$' ) ).trimmed())
metadata = driver.GetMetadata()
if metadata.has_key(gdal.DMD_EXTENSION):
extensions = metadata[gdal.DMD_EXTENSION].split("/")
if extensions:
GdalUtils.supportedRasters[shortName] = extensions

return GdalUtils.supportedRasters

@staticmethod
def getSupportedRasterExtensions():
allexts = []
for exts in GdalUtils.getSupportedRasters().values():
for ext in exts:
allexts.append(ext)
return allexts

@staticmethod
def getFormatShortNameFromFilename(filename):
ext = filename[filename.rfind(".")+1:]
supported = GdalUtils.getSupportedRasters()
for name in supported.keys():
exts = supported[name]
if ext in exts:
return name
return "GTiff"
@@ -0,0 +1,44 @@
from PyQt4 import QtGui
from sextante.core.GeoAlgorithm import GeoAlgorithm
from sextante.outputs.OutputRaster import OutputRaster
import os
from sextante.gdal.GdalUtils import GdalUtils
from sextante.core.SextanteUtils import SextanteUtils
from sextante.parameters.ParameterBoolean import ParameterBoolean
from sextante.parameters.ParameterMultipleInput import ParameterMultipleInput

class merge(GeoAlgorithm):

INPUT = "INPUT"
OUTPUT = "OUTPUT"
PCT = "PCT"
SEPARATE = "SEPARATE"

def getIcon(self):
filepath = os.path.dirname(__file__) + "/icons/merge.png"
return QtGui.QIcon(filepath)

def defineCharacteristics(self):
self.name = "rgb2pct"
self.group = "Conversion"
self.addParameter(ParameterMultipleInput(merge.INPUT, "Input layers", ParameterMultipleInput.TYPE_RASTER))
self.addParameter(ParameterBoolean(merge.PCT, "Grab pseudocolor table from first layer", False))
self.addParameter(ParameterBoolean(merge.SEPARATE, "Layer stack", False))
self.addOutput(OutputRaster(merge.OUTPUT, "Output layer"))

def processAlgorithm(self, progress):
if SextanteUtils.isWindows():
commands = ["cmd.exe", "/C ", "merge.bat"]
else:
commands = ["merge.py"]
if self.getParameterValue(merge.SEPARATE):
commands.append("-separate")
if self.getParameterValue(merge.PCT):
commands.append("-pct")
commands.append("-of")
out = self.getOutputValue(merge.OUTPUT)
commands.append(GdalUtils.getFormatShortNameFromFilename(out))
commands.append(self.getParameterValue(merge.INPUT).replace(";", " "))
commands.append(out)

GdalUtils.runGdal(commands, progress)
@@ -0,0 +1,40 @@
from PyQt4 import QtGui
from sextante.core.GeoAlgorithm import GeoAlgorithm
from sextante.parameters.ParameterRaster import ParameterRaster
from sextante.outputs.OutputRaster import OutputRaster
import os
from sextante.gdal.GdalUtils import GdalUtils
from sextante.parameters.ParameterSelection import ParameterSelection
from sextante.core.SextanteUtils import SextanteUtils

class pct2rgb(GeoAlgorithm):

INPUT = "INPUT"
OUTPUT = "OUTPUT"
NBAND = "NBAND"

def getIcon(self):
filepath = os.path.dirname(__file__) + "/icons/8-to-24-bits.png"
return QtGui.QIcon(filepath)

def defineCharacteristics(self):
self.name = "pct2rgb"
self.group = "Conversion"
self.addParameter(ParameterRaster(pct2rgb.INPUT, "Input layer", False))
self.addParameter(ParameterSelection(pct2rgb.NBAND, "Band to convert", range(25)))
self.addOutput(OutputRaster(pct2rgb.OUTPUT, "Output layer"))

def processAlgorithm(self, progress):
if SextanteUtils.isWindows():
commands = ["cmd.exe", "/C ", "pct2rgb.bat"]
else:
commands = ["pct2rgb.py"]
commands.append("-b")
commands.append(str(self.getParameterValue(pct2rgb.NBAND) + 1))
commands.append("-of")
out = self.getOutputValue(pct2rgb.OUTPUT)
commands.append(GdalUtils.getFormatShortNameFromFilename(out))
commands.append(self.getParameterValue(pct2rgb.INPUT))
commands.append(out)

GdalUtils.runGdal(commands, progress)
@@ -0,0 +1,40 @@
from PyQt4 import QtGui
from sextante.core.GeoAlgorithm import GeoAlgorithm
from sextante.parameters.ParameterRaster import ParameterRaster
from sextante.outputs.OutputRaster import OutputRaster
import os
from sextante.gdal.GdalUtils import GdalUtils
from sextante.parameters.ParameterNumber import ParameterNumber
from sextante.core.SextanteUtils import SextanteUtils

class rgb2pct(GeoAlgorithm):

INPUT = "INPUT"
OUTPUT = "OUTPUT"
NCOLORS = "NCOLORS"

def getIcon(self):
filepath = os.path.dirname(__file__) + "/icons/24-to-8-bits.png"
return QtGui.QIcon(filepath)

def defineCharacteristics(self):
self.name = "rgb2pct"
self.group = "Conversion"
self.addParameter(ParameterRaster(rgb2pct.INPUT, "Input layer", False))
self.addParameter(ParameterNumber(rgb2pct.NCOLORS, "Number of colors", 1, None, 2))
self.addOutput(OutputRaster(rgb2pct.OUTPUT, "Output layer"))

def processAlgorithm(self, progress):
if SextanteUtils.isWindows():
commands = ["cmd.exe", "/C ", "rgb2pct.bat"]
else:
commands = ["rgb2pct.py"]
commands.append("-n")
commands.append(str(self.getParameterValue(rgb2pct.NCOLORS)))
commands.append("-of")
out = self.getOutputValue(rgb2pct.OUTPUT)
commands.append(GdalUtils.getFormatShortNameFromFilename(out))
commands.append(self.getParameterValue(rgb2pct.INPUT))
commands.append(out)

GdalUtils.runGdal(commands, progress)
@@ -4,6 +4,7 @@
##src_filename=raster
##dst_filename=output raster
##Analysis=group
from sextante.gdal.GdalUtils import GdalUtils

try:
from osgeo import gdal, ogr
@@ -23,12 +24,11 @@ def CopyBand( srcband, dstband ):
options = []
src_band = 1

format = 'GTiff'
gdal.AllRegister()
src_ds = gdal.Open(src_filename, gdal.GA_ReadOnly)
srcband = src_ds.GetRasterBand(src_band)
maskband = srcband.GetMaskBand()
drv = gdal.GetDriverByName(format)
drv = gdal.GetDriverByName(GdalUtils.getFormatShortNameFromFilename(dst_filename))
dst_ds = drv.Create(dst_filename,src_ds.RasterXSize, src_ds.RasterYSize,1,
srcband.DataType)
wkt = src_ds.GetProjection()
@@ -9,12 +9,12 @@
##nodata=number 0
##distunits=selection PIXEL;GEO
##fixed_buf_val=number 0
from sextante.gdal.GdalUtils import GdalUtils
try:
from osgeo import gdal
except ImportError:
import gdal

format = 'GTiff'
creation_options = []
options = []
src_band_n = 1
@@ -49,7 +49,7 @@
# Create output file.
# =============================================================================
if dst_ds is None:
drv = gdal.GetDriverByName(format)
drv = gdal.GetDriverByName(GdalUtils.getFormatShortNameFromFilename(dst_filename))
dst_ds = drv.Create( dst_filename,
src_ds.RasterXSize, src_ds.RasterYSize, 1,
gdal.GetDataTypeByName(creation_type) )
@@ -5,6 +5,7 @@
##src_filename=raster
##dst_filename=output raster
##connectedness=selection 4;8
from sextante.gdal.GdalUtils import GdalUtils

try:
from osgeo import gdal, ogr
@@ -15,13 +16,12 @@
threshold = 2
connectedness=int(connectedness)
options = []
format = 'GTiff'

src_ds = gdal.Open( src_filename, gdal.GA_ReadOnly )
srcband = src_ds.GetRasterBand(1)
maskband = srcband.GetMaskBand()

drv = gdal.GetDriverByName(format)
drv = gdal.GetDriverByName(GdalUtils.getFormatShortNameFromFilename(dst_filename))
dst_ds = drv.Create( dst_filename,src_ds.RasterXSize, src_ds.RasterYSize,1,
srcband.DataType )
wkt = src_ds.GetProjection()
@@ -0,0 +1,31 @@
from PyQt4 import QtGui
from sextante.core.GeoAlgorithm import GeoAlgorithm
from sextante.parameters.ParameterRaster import ParameterRaster
from sextante.outputs.OutputRaster import OutputRaster
import os
from sextante.gdal.GdalUtils import GdalUtils

class translate(GeoAlgorithm):

INPUT = "INPUT"
OUTPUT = "OUTPUT"

def getIcon(self):
filepath = os.path.dirname(__file__) + "/icons/translate.png"
return QtGui.QIcon(filepath)

def defineCharacteristics(self):
self.name = "translate"
self.group = "Conversion"
self.addParameter(ParameterRaster(translate.INPUT, "Input layer", False))
self.addOutput(OutputRaster(translate.OUTPUT, "Output layer"))

def processAlgorithm(self, progress):
commands = ["gdal_translate"]
commands.append("-of")
out = self.getOutputValue(translate.OUTPUT)
commands.append(GdalUtils.getFormatShortNameFromFilename(out))
commands.append(self.getParameterValue(translate.INPUT))
commands.append(out)

GdalUtils.runGdal(commands, progress)

0 comments on commit 69bc4a0

Please sign in to comment.