Advertisement
xunilk

average_raster.py

Aug 16th, 2015
472
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.30 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. """
  3. /***************************************************************************
  4. AverageRaster
  5.                                 A QGIS plugin
  6. This plugin calculates the average of a raster as active layer
  7.                              -------------------
  8.        begin                : 2015-08-15
  9.        git sha              : $Format:%H$
  10.        copyright            : (C) 2015 by Jose Guerrero
  11.        email                : joseguerreroa@gmail.com
  12. ***************************************************************************/
  13.  
  14. /***************************************************************************
  15. *                                                                         *
  16. *   This program is free software; you can redistribute it and/or modify  *
  17. *   it under the terms of the GNU General Public License as published by  *
  18. *   the Free Software Foundation; either version 2 of the License, or     *
  19. *   (at your option) any later version.                                   *
  20. *                                                                         *
  21. ***************************************************************************/
  22. """
  23. from PyQt4.QtCore import QSettings, QTranslator, qVersion, QCoreApplication
  24. from PyQt4.QtGui import QAction, QIcon, QMessageBox
  25. from qgis.gui import QgsMessageBar
  26. # Initialize Qt resources from file resources.py
  27. import resources_rc
  28. # Import the code for the dialog
  29. from average_raster_dialog import AverageRasterDialog
  30. import os.path
  31. from osgeo import gdal
  32. import struct
  33.  
  34.  
  35. class AverageRaster:
  36.     """QGIS Plugin Implementation."""
  37.  
  38.     def __init__(self, iface):
  39.         """Constructor.
  40.  
  41.        :param iface: An interface instance that will be passed to this class
  42.            which provides the hook by which you can manipulate the QGIS
  43.            application at run time.
  44.        :type iface: QgsInterface
  45.        """
  46.         # Save reference to the QGIS interface
  47.         self.iface = iface
  48.         # initialize plugin directory
  49.         self.plugin_dir = os.path.dirname(__file__)
  50.         # initialize locale
  51.         locale = QSettings().value('locale/userLocale')[0:2]
  52.         locale_path = os.path.join(
  53.             self.plugin_dir,
  54.             'i18n',
  55.             'AverageRaster_{}.qm'.format(locale))
  56.  
  57.         if os.path.exists(locale_path):
  58.             self.translator = QTranslator()
  59.             self.translator.load(locale_path)
  60.  
  61.             if qVersion() > '4.3.3':
  62.                 QCoreApplication.installTranslator(self.translator)
  63.  
  64.         # Create the dialog (after translation) and keep reference
  65.         self.dlg = AverageRasterDialog()
  66.  
  67.         # Declare instance attributes
  68.         self.actions = []
  69.         self.menu = self.tr(u'&Average Raster')
  70.         # TODO: We are going to let the user set this up in a future iteration
  71.         self.toolbar = self.iface.addToolBar(u'AverageRaster')
  72.         self.toolbar.setObjectName(u'AverageRaster')
  73.  
  74.     # noinspection PyMethodMayBeStatic
  75.     def tr(self, message):
  76.         """Get the translation for a string using Qt translation API.
  77.  
  78.        We implement this ourselves since we do not inherit QObject.
  79.  
  80.        :param message: String for translation.
  81.        :type message: str, QString
  82.  
  83.        :returns: Translated version of message.
  84.        :rtype: QString
  85.        """
  86.         # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
  87.         return QCoreApplication.translate('AverageRaster', message)
  88.  
  89.  
  90.     def add_action(
  91.         self,
  92.         icon_path,
  93.         text,
  94.         callback,
  95.         enabled_flag=True,
  96.         add_to_menu=True,
  97.         add_to_toolbar=True,
  98.         status_tip=None,
  99.         whats_this=None,
  100.         parent=None):
  101.         """Add a toolbar icon to the toolbar.
  102.  
  103.        :param icon_path: Path to the icon for this action. Can be a resource
  104.            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
  105.        :type icon_path: str
  106.  
  107.        :param text: Text that should be shown in menu items for this action.
  108.        :type text: str
  109.  
  110.        :param callback: Function to be called when the action is triggered.
  111.        :type callback: function
  112.  
  113.        :param enabled_flag: A flag indicating if the action should be enabled
  114.            by default. Defaults to True.
  115.        :type enabled_flag: bool
  116.  
  117.        :param add_to_menu: Flag indicating whether the action should also
  118.            be added to the menu. Defaults to True.
  119.        :type add_to_menu: bool
  120.  
  121.        :param add_to_toolbar: Flag indicating whether the action should also
  122.            be added to the toolbar. Defaults to True.
  123.        :type add_to_toolbar: bool
  124.  
  125.        :param status_tip: Optional text to show in a popup when mouse pointer
  126.            hovers over the action.
  127.        :type status_tip: str
  128.  
  129.        :param parent: Parent widget for the new action. Defaults None.
  130.        :type parent: QWidget
  131.  
  132.        :param whats_this: Optional text to show in the status bar when the
  133.            mouse pointer hovers over the action.
  134.  
  135.        :returns: The action that was created. Note that the action is also
  136.            added to self.actions list.
  137.        :rtype: QAction
  138.        """
  139.  
  140.         icon = QIcon(icon_path)
  141.         action = QAction(icon, text, parent)
  142.         action.triggered.connect(callback)
  143.         action.setEnabled(enabled_flag)
  144.  
  145.         if status_tip is not None:
  146.             action.setStatusTip(status_tip)
  147.  
  148.         if whats_this is not None:
  149.             action.setWhatsThis(whats_this)
  150.  
  151.         if add_to_toolbar:
  152.             self.toolbar.addAction(action)
  153.  
  154.         if add_to_menu:
  155.             self.iface.addPluginToMenu(
  156.                 self.menu,
  157.                 action)
  158.  
  159.         self.actions.append(action)
  160.  
  161.         return action
  162.  
  163.     def initGui(self):
  164.         """Create the menu entries and toolbar icons inside the QGIS GUI."""
  165.  
  166.         icon_path = ':/plugins/AverageRaster/AverageRaster.png'
  167.         self.add_action(
  168.             icon_path,
  169.             text=self.tr(u'To calculate raster average'),
  170.             callback=self.run,
  171.             parent=self.iface.mainWindow())
  172.  
  173.  
  174.     def unload(self):
  175.         """Removes the plugin menu item and icon from QGIS GUI."""
  176.         for action in self.actions:
  177.             self.iface.removePluginMenu(
  178.                 self.tr(u'&Average Raster'),
  179.                 action)
  180.             self.iface.removeToolBarIcon(action)
  181.         # remove the toolbar
  182.         del self.toolbar
  183.  
  184.  
  185.     def run(self):
  186.         """Run method that performs all the real work"""
  187.         #My code starts here
  188.         layer = self.iface.activeLayer()
  189.        
  190.         if layer is not None:
  191.             provider = layer.dataProvider()
  192.      
  193.             fmttypes = {'Byte':'B', 'UInt16':'H', 'Int16':'h', 'UInt32':'I', 'Int32':'i', 'Float32':'f', 'Float64':'d'}
  194.      
  195.             path= provider.dataSourceUri()
  196.      
  197.             (raiz, filename) = os.path.split(path)
  198.      
  199.             dataset = gdal.Open(path)
  200.      
  201.             band = dataset.GetRasterBand(1)
  202.        
  203.             totHeight = 0
  204.            
  205.             BandType = gdal.GetDataTypeName(band.DataType)
  206.            
  207.             for y in range(band.YSize):
  208.                
  209.                 scanline = band.ReadRaster(0, y, band.XSize, 1, band.XSize, 1, band.DataType)
  210.                 values = struct.unpack(fmttypes[BandType] * band.XSize, scanline)
  211.                
  212.                 for value in values:
  213.                     totHeight += value
  214.            
  215.             average = totHeight / float((band.XSize * band.YSize))
  216.         else:
  217.             self.iface.messageBar().pushMessage("Advertencia:",
  218.                                                u"No hay capa activa",
  219.                                                QgsMessageBar.WARNING, 5)
  220.             return
  221.         #My code ends here
  222.         # show the dialog
  223.         self.dlg.show()
  224.         # Run the dialog event loop
  225.         result = self.dlg.exec_()
  226.         # See if OK was pressed
  227.         if result:
  228.             # Do something useful here - delete the line containing pass and
  229.             # substitute with your code.
  230.             #My code starts here
  231.             message = "the raster average of " + filename + " is = " + str(average)
  232.             QMessageBox.information(None, "Raster Average", message)
  233.             #My code ends here
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement