def doWork(self, tableLayer): workLayer = self.layerCombo.currentLayer() cutGeom = QgsGeometry().fromRect(workLayer.extent()) cutLayer = QgsVectorLayer( "Polygon?crs={}".format(workLayer.crs().authid()), "temp_cut", "memory") cut_feature = QgsFeature() cut_feature.setGeometry(cutGeom) cutLayer.dataProvider().addFeatures([cut_feature]) restLayers = self.getLayers() if restLayers: for layer in restLayers: cutLayer = processing.run("native:difference", { 'INPUT': cutLayer, 'OVERLAY': layer, 'OUTPUT': 'memory:' })['OUTPUT'] cutted_raster_path = processing.run("gdal:cliprasterbymasklayer", { 'INPUT': workLayer, 'MASK': cutLayer, 'OUTPUT': 'TEMPORARY_OUTPUT' })['OUTPUT'] cutted_raster = QgsRasterLayer(cutted_raster_path) else: cutted_raster = workLayer slopeLayer_path = processing.run( "gdal:slope", { 'INPUT': cutted_raster, 'BAND': 1, 'SCALE': 1, 'AS_PERCENT': False, 'OUTPUT': 'TEMPORARY_OUTPUT' })['OUTPUT'] slopeLayer = QgsRasterLayer(slopeLayer_path) classLayer_path = processing.run( "native:reclassifybylayer", { 'INPUT_RASTER': slopeLayer, 'RASTER_BAND': 1, 'INPUT_TABLE': tableLayer, 'MIN_FIELD': 'Minimo', 'MAX_FIELD': 'Maximo', 'VALUE_FIELD': 'Valor', 'RANGE_BOUNDARIES': 1, 'OUTPUT': 'TEMPORARY_OUTPUT' })['OUTPUT'] classLayer = QgsRasterLayer(classLayer_path) classLayer.setName('Mapa de trafegabilidade') QgsProject.instance().addMapLayer(classLayer) self.setRasterStyle(classLayer, tableLayer) return
def multibandRasterLayer(self) -> QgsRasterLayer: try: from utilities import unitTestDataPath path = pathlib.Path(unitTestDataPath()) / 'landsat_4326.tif' except ModuleNotFoundError: path = pathlib.Path(__file__).parent / 'landsat_4326.tif' assert isinstance(path, pathlib.Path) and path.is_file() lyr = QgsRasterLayer(path.as_posix()) lyr.setName(path.name) self.assertIsInstance(lyr, QgsRasterLayer) self.assertTrue(lyr.isValid()) self.assertTrue(lyr.bandCount() > 1) return lyr
def testWriteSld(self): """Test SLD generation for the XMLS fields geneerated at RasterLayer level and not to the deeper renderer level.""" myPath = os.path.join(unitTestDataPath(), 'landsat.tif') myFileInfo = QFileInfo(myPath) myBaseName = myFileInfo.baseName() myRasterLayer = QgsRasterLayer(myPath, myBaseName) myMessage = 'Raster not loaded: %s' % myPath assert myRasterLayer.isValid(), myMessage # do generic export with default layer values dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = root.elementsByTagName('sld:LayerFeatureConstraints') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() elements = element.elementsByTagName('sld:FeatureTypeConstraint') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() elements = root.elementsByTagName('sld:UserStyle') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() name = element.firstChildElement('sld:Name') self.assertFalse(name.isNull()) self.assertEqual(name.text(), 'landsat') abstract = element.firstChildElement('sld:Abstract') self.assertTrue(abstract.isNull()) title = element.firstChildElement('sld:Title') self.assertTrue(title.isNull()) featureTypeStyle = element.firstChildElement('sld:FeatureTypeStyle') self.assertFalse(featureTypeStyle.isNull()) rule = featureTypeStyle.firstChildElement('sld:Rule') self.assertFalse(rule.isNull()) temp = rule.firstChildElement('sld:MinScaleDenominator') self.assertTrue(temp.isNull()) temp = rule.firstChildElement('sld:MaxScaleDenominator') self.assertTrue(temp.isNull()) rasterSymbolizer = rule.firstChildElement('sld:RasterSymbolizer') self.assertFalse(rule.isNull()) vendorOptions = rasterSymbolizer.elementsByTagName('sld:VendorOption') self.assertTrue(vendorOptions.size() == 0) # set no default values and check exported sld myRasterLayer.setName('') myRasterLayer.setAbstract('fake') myRasterLayer.setTitle('fake') dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = root.elementsByTagName('sld:LayerFeatureConstraints') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() elements = element.elementsByTagName('sld:FeatureTypeConstraint') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() elements = root.elementsByTagName('sld:UserStyle') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() # no generated if empty name = element.firstChildElement('sld:Name') self.assertTrue(name.isNull()) # generated if not empty abstract = element.firstChildElement('sld:Abstract') self.assertFalse(abstract.isNull()) self.assertEqual(abstract.text(), 'fake') title = element.firstChildElement('sld:Title') self.assertFalse(title.isNull()) self.assertEqual(title.text(), 'fake') # if setScaleBasedVisibility is true print scales myRasterLayer.setScaleBasedVisibility(True) myRasterLayer.setMaximumScale(0.0001) myRasterLayer.setMinimumScale(0.01) dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = dom.elementsByTagName('sld:Rule') self.assertEqual(len(elements), 1) rule = elements.at(0).toElement() self.assertFalse(rule.isNull()) temp = rule.firstChildElement('sld:MinScaleDenominator') self.assertFalse(temp.isNull()) self.assertEqual(temp.text(), '0.0001') temp = rule.firstChildElement('sld:MaxScaleDenominator') self.assertFalse(temp.isNull()) self.assertEqual(temp.text(), '0.01') # check non default hueSaturationFilter values hue = myRasterLayer.hueSaturationFilter() hue.setGrayscaleMode(QgsHueSaturationFilter.GrayscaleLightness) dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = dom.elementsByTagName('sld:RasterSymbolizer') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() self.assertFalse(element.isNull()) self.assertVendorOption(element, 'grayScale', 'lightness') hue = myRasterLayer.hueSaturationFilter() hue.setGrayscaleMode(QgsHueSaturationFilter.GrayscaleLuminosity) dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = dom.elementsByTagName('sld:RasterSymbolizer') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() self.assertFalse(element.isNull()) self.assertVendorOption(element, 'grayScale', 'luminosity') hue = myRasterLayer.hueSaturationFilter() hue.setGrayscaleMode(QgsHueSaturationFilter.GrayscaleAverage) dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = dom.elementsByTagName('sld:RasterSymbolizer') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() self.assertFalse(element.isNull()) self.assertVendorOption(element, 'grayScale', 'average') hue = myRasterLayer.hueSaturationFilter() hue.setGrayscaleMode(QgsHueSaturationFilter.GrayscaleOff) dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = dom.elementsByTagName('sld:RasterSymbolizer') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() self.assertFalse(element.isNull()) self.assertVendorOption(element, 'grayScale', None) # manage colorize vendorOption tags hue = myRasterLayer.hueSaturationFilter() hue.setColorizeOn(True) hue.setColorizeStrength(50) dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = dom.elementsByTagName('sld:RasterSymbolizer') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() self.assertFalse(element.isNull()) self.assertVendorOption(element, 'colorizeOn', '1') self.assertVendorOption(element, 'colorizeRed', '255') self.assertVendorOption(element, 'colorizeGreen', '128') self.assertVendorOption(element, 'colorizeBlue', '128') self.assertVendorOption(element, 'colorizeStrength', '0.5') self.assertVendorOption(element, 'saturation', '0.498039') # other hue non default values, no colorize and saturation = 0 hue = myRasterLayer.hueSaturationFilter() hue.setColorizeOn(False) hue.setSaturation(0) dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = dom.elementsByTagName('sld:RasterSymbolizer') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() self.assertFalse(element.isNull()) self.assertVendorOption(element, 'colorizeOn', None) self.assertVendorOption(element, 'colorizeRed', None) self.assertVendorOption(element, 'colorizeGreen', None) self.assertVendorOption(element, 'colorizeBlue', None) self.assertVendorOption(element, 'colorizeStrength', None) self.assertVendorOption(element, 'saturation', None) self.assertVendorOption(element, 'brightness', None) self.assertVendorOption(element, 'contrast', None) # other hue non default values, no colorize and saturation = 100 hue = myRasterLayer.hueSaturationFilter() hue.setColorizeOn(False) hue.setSaturation(100) dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = dom.elementsByTagName('sld:RasterSymbolizer') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() self.assertFalse(element.isNull()) self.assertVendorOption(element, 'colorizeOn', None) self.assertVendorOption(element, 'colorizeRed', None) self.assertVendorOption(element, 'colorizeGreen', None) self.assertVendorOption(element, 'colorizeBlue', None) self.assertVendorOption(element, 'colorizeStrength', None) self.assertVendorOption(element, 'saturation', '1') hue.setSaturation(-100) dom, root, errorMessage = self.layerToSld(myRasterLayer) self.assertVendorOption(root, 'saturation', '0') # brightness filter default values dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = dom.elementsByTagName('sld:RasterSymbolizer') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() self.assertFalse(element.isNull()) self.assertTrue(myRasterLayer.brightnessFilter().brightness() == 0) self.assertTrue(myRasterLayer.brightnessFilter().contrast() == 0) self.assertVendorOption(element, 'brightness', None) self.assertVendorOption(element, 'contrast', None) # brightness filter no default values bf = myRasterLayer.brightnessFilter() bf.setBrightness(-255) bf.setContrast(-100) dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = dom.elementsByTagName('sld:RasterSymbolizer') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() self.assertFalse(element.isNull()) self.assertVendorOption(element, 'brightness', '0') self.assertVendorOption(element, 'contrast', '0') bf.setBrightness(255) bf.setContrast(100) dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = dom.elementsByTagName('sld:RasterSymbolizer') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() self.assertFalse(element.isNull()) self.assertVendorOption(element, 'brightness', '1') self.assertVendorOption(element, 'contrast', '1')
class ArchiwalnaOrtofotomapa: """QGIS Plugin Implementation.""" def __init__(self, iface): """Constructor. :param iface: An interface instance that will be passed to this class which provides the hook by which you can manipulate the QGIS application at run time. :type iface: QgsInterface """ if Qgis.QGIS_VERSION_INT >= 31000: from .qgis_feed import QgisFeed self.feed = QgisFeed() self.feed.initFeed() # Save reference to the QGIS interface self.iface = iface # initialize plugin directory self.plugin_dir = os.path.dirname(__file__) # initialize locale locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join( self.plugin_dir, 'i18n', 'ArchiwalnaOrtofotomapa_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) QCoreApplication.installTranslator(self.translator) # Declare instance attributes self.actions = [] self.menu = self.tr(u'&EnviroSolutions') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.mainWindow().findChild( QToolBar, 'EnviroSolutions') if not self.toolbar: self.toolbar = self.iface.addToolBar(u'EnviroSolutions') self.toolbar.setObjectName(u'EnviroSolutions') #print "** INITIALIZING ArchiwalnaOrtofotomapa" self.pluginIsActive = False self.dockwidget = None self.canvas = self.iface.mapCanvas() self.orto = None # -------------------------------------------------------------------------- # noinspection PyMethodMayBeStatic def tr(self, message): """Get the translation for a string using Qt translation API. We implement this ourselves since we do not inherit QObject. :param message: String for translation. :type message: str, QString :returns: Translated version of message. :rtype: QString """ # noinspection PyTypeChecker,PyArgumentList,PyCallByClass return QCoreApplication.translate('ArchiwalnaOrtofotomapa', message) def add_action(self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None): """Add a toolbar icon to the toolbar. :param icon_path: Path to the icon for this action. Can be a resource path (e.g. ':/plugins/foo/bar.png') or a normal file system path. :type icon_path: str :param text: Text that should be shown in menu items for this action. :type text: str :param callback: Function to be called when the action is triggered. :type callback: function :param enabled_flag: A flag indicating if the action should be enabled by default. Defaults to True. :type enabled_flag: bool :param add_to_menu: Flag indicating whether the action should also be added to the menu. Defaults to True. :type add_to_menu: bool :param add_to_toolbar: Flag indicating whether the action should also be added to the toolbar. Defaults to True. :type add_to_toolbar: bool :param status_tip: Optional text to show in a popup when mouse pointer hovers over the action. :type status_tip: str :param parent: Parent widget for the new action. Defaults None. :type parent: QWidget :param whats_this: Optional text to show in the status bar when the mouse pointer hovers over the action. :returns: The action that was created. Note that the action is also added to self.actions list. :rtype: QAction """ icon = QIcon(icon_path) action = QAction(icon, text, parent) action.triggered.connect(callback) action.setEnabled(enabled_flag) if status_tip is not None: action.setStatusTip(status_tip) if whats_this is not None: action.setWhatsThis(whats_this) if add_to_toolbar: self.toolbar.addAction(action) if add_to_menu: self.iface.addPluginToMenu(self.menu, action) self.actions.append(action) return action def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" icon_path = ':/plugins/archiwalna_ortofotomapa/icon_pw2.png' self.add_action(icon_path, text=self.tr(u'Archiwalna Ortofotomapa'), callback=self.run, parent=self.iface.mainWindow()) def onClosePlugin(self): """Cleanup necessary items here when plugin dockwidget is closed""" #print "** CLOSING ArchiwalnaOrtofotomapa" # disconnects self.dockwidget.closingPlugin.disconnect(self.onClosePlugin) # remove this statement if dockwidget is to remain # for reuse if plugin is reopened # Commented next statement since it causes QGIS crashe # when closing the docked window: # self.dockwidget = None self.pluginIsActive = False def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" #print "** UNLOAD ArchiwalnaOrtofotomapa" for action in self.actions: self.iface.removePluginMenu(self.tr(u'&EnviroSolutions'), action) #self.iface.removeToolBarIcon(action) self.toolbar.removeAction(action) # remove the toolbar del self.toolbar #-------------------------------------------------------------------------- def run(self): """Run method that loads and starts the plugin""" if not self.pluginIsActive: self.pluginIsActive = True #print "** STARTING ArchiwalnaOrtofotomapa" if self.orto: self.orto.willBeDeleted.disconnect() # dockwidget may not exist if: # first run of plugin # removed on close (see self.onClosePlugin method) if self.dockwidget == None: # Create the dockwidget (after translation) and keep reference self.dockwidget = ArchiwalnaOrtofotomapaDockWidget() # Eventy slider = self.dockwidget.timeSlider slider.setMinimum(1997) currentYear = datetime.now().year slider.setMaximum(currentYear) self.isSliderPressed = False slider.valueChanged.connect(self.slider_changed) slider.sliderReleased.connect(self.slider_released) slider.sliderPressed.connect(self.slider_pressed) slider.sliderMoved.connect(self.slider_moved) # connect to provide cleanup on closing of dockwidget self.dockwidget.closingPlugin.connect(self.onClosePlugin) # informacje o wersji self.dockwidget.lbl_pluginVersion.setText( '%s %s' % (plugin_name, plugin_version)) # show the dockwidget # TODO: fix to allow choice of dock location self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.dockwidget) self.dockwidget.show() self.orto = QgsRasterLayer( self.makeDataSourceUri(slider.value()), "Ortofotomapa Archiwalna %d" % slider.value(), 'wms') self.orto.willBeDeleted.connect(self.orto_removal) QgsProject.instance().addMapLayer(self.orto) else: #reopened pass def orto_removal(self): self.dockwidget.close() self.orto = None def slider_changed(self): slider = self.dockwidget.sender() self.dockwidget.timeLabel.setText(str(slider.value())) if not self.isSliderPressed: self.changeOrtoLayer(slider) def slider_moved(self): pass def slider_pressed(self): slider = self.dockwidget.sender() self.isSliderPressed = True def slider_released(self): slider = self.dockwidget.sender() self.isSliderPressed = False self.changeOrtoLayer(slider) def changeOrtoLayer(self, slider): # SET DATASOURCE AND RELOAD DATA uri = self.makeDataSourceUri(slider.value()) self.orto.dataProvider().setDataSourceUri(uri) self.orto.triggerRepaint() # self.orto.dataProvider().reloadData() #QGIS 3.12 and above self.orto.setName("Ortofotomapa Archiwalna %d" % slider.value()) def makeDataSourceUri(self, year): serviceUrl = "http://mapy.geoportal.gov.pl/wss/service/img/guest/ORTO_TIME/MapServer/WMSServer" return "IgnoreGetFeatureInfoUrl=1&IgnoreGetMapUrl=1&contextualWMSLegend=0&crs=EPSG:2180&format=image/jpeg&layers=Raster&styles=&url=" \ + serviceUrl + \ "?TIME=" + \ str(year) + \ "-01-01T00%3A00%3A00.000%2B01%3A00"
def load_raster(self, tif_file, qml_file=None, temporal=False): self.temporal = temporal bn = Path(tif_file).name raster_layer = QgsRasterLayer(str(tif_file), bn) # this too? Lead to layer loaded twice. # QgsMapLayerRegistry.instance().addMapLayer(raster_layer) if not raster_layer.isValid(): self._show_message(Qgis.Critical, bn) return """ The new raster layer is ok and we will continue to work with it in the following """ """ --- Clean: If necessary remove existing layer --- If a raster layer with the above name already exists, it will be removed beforehand. The "legend" apparently has nothing to do with the composer legend! """ # for layer in self._iface.legendInterface().layers(): # QGIS 2 # for layer in self._iface.layerTreeView().selectedLayers(): """ the complicated way: project = QgsProject.instance() raster_layers = [rl for rl in project.mapLayers().values() if rl.type() == 1] self.out("current project: {} raster layers found.".format(len(raster_layers))) for layer in raster_layers: #if layer.type() == QgsMapLayer.RasterLayer and layer.name() == radolan_layer_name: if layer.name() == layer_name: self.out('RasterLayer with existing name "{}" found.'.format(layer.name())) ''' Ausgabe 1 Raster 0 DEU_adm0 ''' # print(layerType, layer.name()) print(" removing layer \"{}\"".format(layer.name())) project.removeMapLayer( layer.id() ) """ layer_name = Path(tif_file).stem self._layer_name = layer_name raster_layer.setName(layer_name) self._remove_layer_with_same_name(layer_name) # # Load result raster # # previous version without insert at specific position (was also ok): # self._iface.addRasterLayer(raster_to_load, path.basename(raster_to_load) ) # Einfaches result_layer.setLayerName('Raster') bringt leider nichts. # Unser Rasterlayer kann zuverlässig so bestimmt werden (kann gleich noch einmal gebraucht werden): # raster_layer = self._iface.activeLayer() self._insert_layer(raster_layer, qml_file, 3)