def __init__(self, methodName): """Run once on class initialisation.""" unittest.TestCase.__init__(self, methodName) myPath = os.path.join(TEST_DATA_DIR, 'landsat.tif') rasterFileInfo = QFileInfo(myPath) mRasterLayer = QgsRasterLayer(rasterFileInfo.filePath(), rasterFileInfo.completeBaseName()) rasterRenderer = QgsMultiBandColorRenderer( mRasterLayer.dataProvider(), 2, 3, 4) mRasterLayer.setRenderer(rasterRenderer) #pipe = mRasterLayer.pipe() #assert pipe.set(rasterRenderer), 'Cannot set pipe renderer' QgsMapLayerRegistry.instance().addMapLayers([mRasterLayer]) # create composition with composer map self.mMapRenderer = QgsMapRenderer() layerStringList = QStringList() layerStringList.append(mRasterLayer.id()) self.mMapRenderer.setLayerSet(layerStringList) self.mMapRenderer.setProjectionsEnabled(False) self.mComposition = QgsComposition(self.mMapRenderer) self.mComposition.setPaperSize(297, 210) self.mComposerMap = QgsComposerMap(self.mComposition, 20, 20, 200, 100) self.mComposerMap.setFrameEnabled(True) self.mComposition.addComposerMap(self.mComposerMap)
def createDefaultProject(available_maps, visible_maps, project_template, authcfg=None): """Create a default project from a template and return it as a string""" layers = [] for m in available_maps: connstring = u'type=xyz&url={url}' if authcfg is not None: connstring = u'authcfg={authcfg}&' + connstring layer = QgsRasterLayer(connstring.format(url=urllib2.quote("{}?version={}".format(m['endpoint'], pluginSetting("apiVersion"))), authcfg=authcfg), m['name'], "wms") # I've no idea why the following is required even if the crs is specified # in the layer definition layer.setCrs(QgsCoordinateReferenceSystem('EPSG:3857')) layers.append(layer) if len(layers): xml = QgsMapLayer.asLayerDefinition(layers) maplayers = "\n".join(xml.toString().split("\n")[3:-3]) layer_tree_layer = "" custom_order = "" legend_layer = "" layer_coordinate_transform = "" for layer in layers: is_visible = layer.name() in visible_maps values = {'name': layer.name(), 'id': layer.id(), 'visible': ('1' if is_visible else '0'), 'checked': ('Qt::Checked' if is_visible else 'Qt::Unchecked')} custom_order += "<item>%s</item>" % layer.id() layer_tree_layer += """ <layer-tree-layer expanded="1" checked="%(checked)s" id="%(id)s" name="%(name)s"> <customproperties/> </layer-tree-layer>""" % values legend_layer += """ <legendlayer drawingOrder="-1" open="true" checked="%(checked)s" name="%(name)s" showFeatureCount="0"> <filegroup open="true" hidden="false"> <legendlayerfile isInOverview="0" layerid="%(id)s" visible="%(visible)s"/> </filegroup> </legendlayer>""" % values layer_coordinate_transform += '<layer_coordinate_transform destAuthId="EPSG:3857" srcAuthId="EPSG:3857" srcDatumTransform="-1" destDatumTransform="-1" layerid="%s"/>' % layer.id() tpl = "" with open(project_template, 'rb') as f: tpl = f.read() for tag in ['custom_order', 'layer_tree_layer', 'legend_layer', 'layer_coordinate_transform', 'maplayers']: tpl = tpl.replace("#%s#" % tag.upper(), locals()[tag]) return tpl else: return None
def testPrintMapFromTemplate(self): """Test that we can get a map to render in the template.""" myPath = os.path.join(TEST_DATA_DIR, 'landsat.tif') myFileInfo = QFileInfo(myPath) myRasterLayer = QgsRasterLayer(myFileInfo.filePath(), myFileInfo.completeBaseName()) myRenderer = QgsMultiBandColorRenderer( myRasterLayer.dataProvider(), 2, 3, 4 ) #mRasterLayer.setRenderer( rasterRenderer ) myPipe = myRasterLayer.pipe() assert myPipe.set(myRenderer), "Cannot set pipe renderer" QgsMapLayerRegistry.instance().addMapLayers([myRasterLayer]) myMapRenderer = QgsMapRenderer() myLayerStringList = [] myLayerStringList.append(myRasterLayer.id()) myMapRenderer.setLayerSet(myLayerStringList) myMapRenderer.setProjectionsEnabled(False) myComposition = QgsComposition(myMapRenderer) myFile = os.path.join(TEST_DATA_DIR, 'template-for-substitution.qpt') myTemplateFile = file(myFile, 'rt') myTemplateContent = myTemplateFile.read() myTemplateFile.close() myDocument = QDomDocument() myDocument.setContent(myTemplateContent) myComposition.loadFromTemplate(myDocument) # now render the map, first zooming to the raster extents myMap = myComposition.getComposerMapById(0) myMessage = ('Map 0 could not be found in template %s', myFile) assert myMap is not None, myMessage myExtent = myRasterLayer.extent() myMap.setNewExtent(myExtent) myImagePath = os.path.join(str(QDir.tempPath()), 'template_map_render_python.png') myPageNumber = 0 myImage = myComposition.printPageAsRaster(myPageNumber) myImage.save(myImagePath) assert os.path.exists(myImagePath), 'Map render was not created.' # Not sure if this is a predictable way to test but its quicker than # rendering. myFileSize = QFileInfo(myImagePath).size() myExpectedFileSize = 100000 myMessage = ('Expected file size to be greater than %s, got %s' ' for %s' % (myExpectedFileSize, myFileSize, myImagePath)) assert myFileSize > myExpectedFileSize, myMessage
def __init__(self, methodName): """Run once on class initialization.""" unittest.TestCase.__init__(self, methodName) myPath = os.path.join(TEST_DATA_DIR, "rgb256x256.png") rasterFileInfo = QFileInfo(myPath) mRasterLayer = QgsRasterLayer(rasterFileInfo.filePath(), rasterFileInfo.completeBaseName()) rasterRenderer = QgsMultiBandColorRenderer(mRasterLayer.dataProvider(), 1, 2, 3) mRasterLayer.setRenderer(rasterRenderer) # pipe = mRasterLayer.pipe() # assert pipe.set(rasterRenderer), 'Cannot set pipe renderer' QgsMapLayerRegistry.instance().addMapLayers([mRasterLayer]) # create composition with composer map self.mMapSettings = QgsMapSettings() self.mMapSettings.setLayers([mRasterLayer.id()]) self.mMapSettings.setCrsTransformEnabled(False) self.mComposition = QgsComposition(self.mMapSettings) self.mComposition.setPaperSize(297, 210) self.mComposerMap = QgsComposerMap(self.mComposition, 20, 20, 200, 100) self.mComposerMap.setFrameEnabled(True) self.mComposition.addComposerMap(self.mComposerMap)
def refreshtiles_apply(self, tilestoclean, tilestoload, tilefiles, extent): #clean layerstoclean = [self.loadedlayers[tile] for tile in tilestoclean] for tile in tilestoclean: del self.loadedlayers[tile] QgsMapLayerRegistry.instance().removeMapLayers(layerstoclean) log("defining self.actualzoom") if len(tilestoload) > 0: self.actualzoom = tilestoload[0][2] else: self.actualzoom = None #load log("loading tiles") for i in range(len(tilestoload)): #check file exists if os.path.exists(tilefiles[i]): auxfile = tm.auxfilename(tilefiles[i]) if not os.path.exists(auxfile): osm.writeauxfile(*tilestoload[i], filename=auxfile, imagesize=tm.tilesize(self.tiletype)) #create layer, add to self.loadedlayers layername = "qosm_%s_x%s_y%s_z%s" % ((self.tiletype,) + tilestoload[i]) layer = QgsRasterLayer(tilefiles[i], layername) if layer.isValid(): layer = QgsMapLayerRegistry.instance().addMapLayer(layer, False) layer.resampleFilter().setZoomedOutResampler(QgsBilinearRasterResampler()) layer.resampleFilter().setZoomedInResampler(QgsBilinearRasterResampler()) self.loadedlayers[tilestoload[i]] = layer.id() else: log("ERROR invalid layer produced:" + layername) else: #report error? log("tile filename does not exist: " + tilefiles[i]) log("setting extent: " + extent.toString()) self.setExtent(extent)
def testClone(self): myPath = os.path.join(unitTestDataPath('raster'), 'band1_float32_noct_epsg4326.tif') myFileInfo = QFileInfo(myPath) myBaseName = myFileInfo.baseName() layer = QgsRasterLayer(myPath, myBaseName) renderer = layer.renderer().clone() renderer.setOpacity(33.3) layer.setRenderer(renderer) # clone layer clone = layer.clone() # generate xml from layer layer_doc = QDomDocument("doc") layer_elem = layer_doc.createElement("maplayer") layer.writeLayerXml(layer_elem, layer_doc, QgsReadWriteContext()) # generate xml from clone clone_doc = QDomDocument("doc") clone_elem = clone_doc.createElement("maplayer") clone.writeLayerXml(clone_elem, clone_doc, QgsReadWriteContext()) # replace id within xml of clone clone_id_elem = clone_elem.firstChildElement("id") clone_id_elem_patch = clone_doc.createElement("id") clone_id_elem_patch_value = clone_doc.createTextNode(layer.id()) clone_id_elem_patch.appendChild(clone_id_elem_patch_value) clone_elem.replaceChild(clone_id_elem_patch, clone_id_elem) # update doc clone_doc.appendChild(clone_elem) layer_doc.appendChild(layer_elem) # compare xml documents self.assertEqual(layer_doc.toString(), clone_doc.toString())
def processAlgorithm(self, parameters, context, feedback): # extract input parameters alg = self.parameterAsEnum(parameters, self.INPUT_ALG_NAME, context) extent = self.parameterAsVectorLayer(parameters, self.INPUT_EXTENT, context) raster_1_id = self.parameterAsString(parameters, self.INPUT_RASTER_1, context) raster_1 = QgsProject.instance().mapLayer(raster_1_id) raster_2_id = self.parameterAsString(parameters, self.INPUT_RASTER_2, context) raster_2 = QgsProject.instance().mapLayer(raster_2_id) (sink, self.dest_id) = self.parameterAsSink( parameters, self.OUTPUT_BUFFER, context, QgsFields(), extent.wkbType(), extent.sourceCrs(), ) outputFile = self.parameterAsRasterLayer( parameters, self.OUTPUT_CHANGES, context ) # create a temporary vector layer tmp = tempfile.mkdtemp() path_roi = os.path.join(tmp, "roi.shp") writer = QgsVectorFileWriter( path_roi, "UTF-8", QgsFields(), QgsWkbTypes.Polygon, extent.sourceCrs(), "ESRI Shapefile", ) # create buffered extent and update temporary shp for detector for feature in extent.getFeatures(): geom = feature.geometry() buffer = geom.buffer( 10, 100, QgsGeometry.CapFlat, QgsGeometry.JoinStyleMiter, 100 ) feature.setGeometry(buffer) feature.setFields(QgsFields()) sink.addFeature(feature) writer.addFeature(feature) del writer # run change detector path1 = raster_1.source() path2 = raster_2.source() detector = LittoDynChangeDetectorPca(path1, path2, path_roi) if alg == 1: detector = LittoDynChangeDetectorEvi(path1, path2, path_roi) elif alg == 2: detector = LittoDynChangeDetectorNdvi(path1, path2, path_roi) elif alg == 3: detector = LittoDynChangeDetectorNgrdi(path1, path2, path_roi) elif alg == 4: detector = LittoDynChangeDetectorNormEuclid(path1, path2, path_roi) elif alg == 5: detector = LittoDynChangeDetectorNormCorr(path1, path2, path_roi) elif alg == 6: detector = LittoDynChangeDetectorNormCos(path1, path2, path_roi) detector.detect() # store output layers in group alg_name = self.options[alg].lower().replace(" ", "_") if Qgis.QGIS_VERSION_INT >= 31500: name = "{}_{}_{}".format(raster_1.name(), raster_2.name(), alg_name) ProcessingConfig.setSettingValue(ProcessingConfig.RESULTS_GROUP_NAME, name) # save result in temporary file tmp = tempfile.mkdtemp() path_changes = os.path.join(tmp, "{}_changes.tif".format(alg_name)) detector.save(path_changes) rl = QgsRasterLayer(path_changes, "{}_changes".format(alg_name), "gdal") context.temporaryLayerStore().addMapLayer(rl) context.addLayerToLoadOnCompletion( rl.id(), QgsProcessingContext.LayerDetails( "{}_changes".format(alg_name), context.project(), self.OUTPUT_CHANGES ), ) return { self.OUTPUT_CHANGES: rl.id(), self.OUTPUT_BUFFER: self.dest_id, self.OUTPUT_CHANGES: rl.id(), }
class TestQgsBlendModes(TestCase): def __init__(self, methodName): """Run once on class initialisation.""" unittest.TestCase.__init__(self, methodName) # initialize class MapRegistry, Canvas, MapRenderer, Map and PAL self.mMapRegistry = QgsMapLayerRegistry.instance() # create point layer myShpFile = os.path.join(TEST_DATA_DIR, 'points.shp') self.mPointLayer = QgsVectorLayer(myShpFile, 'Points', 'ogr') self.mMapRegistry.addMapLayer(self.mPointLayer) # create polygon layer myShpFile = os.path.join(TEST_DATA_DIR, 'polys.shp') self.mPolygonLayer = QgsVectorLayer(myShpFile, 'Polygons', 'ogr') self.mMapRegistry.addMapLayer(self.mPolygonLayer) # create two raster layers myRasterFile = os.path.join(TEST_DATA_DIR, 'landsat.tif') self.mRasterLayer1 = QgsRasterLayer(myRasterFile, "raster1") self.mRasterLayer2 = QgsRasterLayer(myRasterFile, "raster2") myMultiBandRenderer1 = QgsMultiBandColorRenderer(self.mRasterLayer1.dataProvider(), 2, 3, 4) self.mRasterLayer1.setRenderer(myMultiBandRenderer1) self.mMapRegistry.addMapLayer(self.mRasterLayer1) myMultiBandRenderer2 = QgsMultiBandColorRenderer(self.mRasterLayer2.dataProvider(), 2, 3, 4) self.mRasterLayer2.setRenderer(myMultiBandRenderer2) self.mMapRegistry.addMapLayer(self.mRasterLayer2) # to match blend modes test comparisons background self.mCanvas = CANVAS self.mCanvas.setCanvasColor(QColor(152, 219, 249)) self.mMap = self.mCanvas.map() self.mMap.resize(QSize(400, 400)) self.mMapRenderer = self.mCanvas.mapRenderer() self.mMapRenderer.setOutputSize(QSize(400, 400), 72) def testVectorBlending(self): """Test that blend modes work for vector layers.""" #Add vector layers to map myLayers = QStringList() myLayers.append(self.mPointLayer.id()) myLayers.append(self.mPolygonLayer.id()) self.mMapRenderer.setLayerSet(myLayers) self.mMapRenderer.setExtent(self.mPointLayer.extent()) #Set blending modes for both layers self.mPointLayer.setBlendMode(QPainter.CompositionMode_Overlay) self.mPolygonLayer.setBlendMode(QPainter.CompositionMode_Multiply) checker = QgsRenderChecker() checker.setControlName("expected_vector_blendmodes") checker.setMapRenderer(self.mMapRenderer) myResult = checker.runTest("vector_blendmodes"); myMessage = ('vector blending failed') assert myResult, myMessage def testRasterBlending(self): """Test that blend modes work for raster layers.""" #Add raster layers to map myLayers = QStringList() myLayers.append(self.mRasterLayer1.id()) myLayers.append(self.mRasterLayer2.id()) self.mMapRenderer.setLayerSet(myLayers) self.mMapRenderer.setExtent(self.mRasterLayer1.extent()) #Set blending mode for top layer self.mRasterLayer1.setBlendMode(QPainter.CompositionMode_Plus) checker = QgsRenderChecker() checker.setControlName("expected_raster_blendmodes") checker.setMapRenderer(self.mMapRenderer) myResult = checker.runTest("raster_blendmodes"); myMessage = ('raster blending failed') assert myResult, myMessage
def processAlgorithm(self, parameters, context, feedback): """ Here is where the processing itself takes place. """ inputLyr = self.parameterAsVectorLayer(parameters, self.INPUT, context) if inputLyr is None: raise QgsProcessingException( self.invalidSourceError(parameters, self.INPUT)) onlySelected = self.parameterAsBool(parameters, self.SELECTED, context) attributeName = self.parameterAsFields(parameters, self.IMAGE_ATTRIBUTE, context)[0] groupExpression = self.parameterAsExpression(parameters, self.GROUP_EXPRESSION, context) imageTag = self.parameterAsString(parameters, self.NAME_TAG, context) boundingBoxGeometry = self.parameterAsExtentGeometry( parameters, self.EXTENT, context) loadToCanvas = self.parameterAsBoolean(parameters, self.ADD_TO_CANVAS, context) uniqueLoad = self.parameterAsBoolean(parameters, self.UNIQUE_LOAD, context) loadedLayers = { i.dataProvider().dataSourceUri() : i.id() for i in iface.mapCanvas().layers()\ if isinstance(i, QgsRasterLayer) } if uniqueLoad else {} outputLayers = {} request = QgsFeatureRequest() if boundingBoxGeometry is not None: request.setFilterRect(boundingBoxGeometry.boundingBox()) request.setFlags(QgsFeatureRequest.NoGeometry) request.addOrderBy(attributeName, ascending=True) features = inputLyr.getFeatures(request) if not onlySelected \ else inputLyr.getSelectedFeatures(request) #calculate size featList = [i for i in features] listSize = len(featList) progressStep = 100 / listSize if listSize else 0 #remaining parameters if loadToCanvas: rootNode = QgsProject.instance().layerTreeRoot() datasetImageNode = self.createGroup(self.tr('Dataset Images'), rootNode) iface.mapCanvas().freeze(True) else: datasetImageNode = None for current, feat in enumerate(featList): if feedback.isCanceled(): break image_path = feat[attributeName] if image_path in loadedLayers: outputLayers[image_path] = loadedLayers[image_path] feedback.setProgress(current * progressStep) continue newImage = QgsRasterLayer( image_path, '_'.join( [imageTag, os.path.basename(image_path)] if imageTag != ''\ else [os.path.basename(image_path)] ) ) QgsProject.instance().addMapLayer(newImage, False) if datasetImageNode is not None: currentNode = datasetImageNode if groupExpression is None\ else self.getLayerCategoryNode( newImage, datasetImageNode, groupExpression ) currentNode.addLayer(newImage) outputLayers[image_path] = newImage.id() feedback.setProgress(current * progressStep) if loadToCanvas: iface.mapCanvas().freeze(False) iface.mapCanvas().refresh() return {self.OUTPUT: list(outputLayers.values())}
class TestQgsBlendModes(unittest.TestCase): def __init__(self, methodName): """Run once on class initialization.""" unittest.TestCase.__init__(self, methodName) self.iface = get_iface() # initialize class MapRegistry, Canvas, MapRenderer, Map and PAL self.mMapRegistry = QgsMapLayerRegistry.instance() # create point layer myShpFile = os.path.join(TEST_DATA_DIR, 'points.shp') self.mPointLayer = QgsVectorLayer(myShpFile, 'Points', 'ogr') self.mMapRegistry.addMapLayer(self.mPointLayer) self.mSimplifyMethod = QgsVectorSimplifyMethod() self.mSimplifyMethod.setSimplifyHints(QgsVectorSimplifyMethod.NoSimplification) # create polygon layer myShpFile = os.path.join(TEST_DATA_DIR, 'polys.shp') self.mPolygonLayer = QgsVectorLayer(myShpFile, 'Polygons', 'ogr') self.mPolygonLayer.setSimplifyMethod(self.mSimplifyMethod) self.mMapRegistry.addMapLayer(self.mPolygonLayer) # create line layer myShpFile = os.path.join(TEST_DATA_DIR, 'lines.shp') self.mLineLayer = QgsVectorLayer(myShpFile, 'Lines', 'ogr') self.mLineLayer.setSimplifyMethod(self.mSimplifyMethod) self.mMapRegistry.addMapLayer(self.mLineLayer) # create two raster layers myRasterFile = os.path.join(TEST_DATA_DIR, 'rgb256x256.png') self.mRasterLayer1 = QgsRasterLayer(myRasterFile, "raster1") self.mRasterLayer2 = QgsRasterLayer(myRasterFile, "raster2") myMultiBandRenderer1 = QgsMultiBandColorRenderer(self.mRasterLayer1.dataProvider(), 1, 2, 3) self.mRasterLayer1.setRenderer(myMultiBandRenderer1) self.mMapRegistry.addMapLayer(self.mRasterLayer1) myMultiBandRenderer2 = QgsMultiBandColorRenderer(self.mRasterLayer2.dataProvider(), 1, 2, 3) self.mRasterLayer2.setRenderer(myMultiBandRenderer2) self.mMapRegistry.addMapLayer(self.mRasterLayer2) # to match blend modes test comparisons background self.mapSettings = QgsMapSettings() self.mapSettings.setLayers([self.mRasterLayer1.id(), self.mRasterLayer2.id()]) self.mapSettings.setBackgroundColor(QColor(152, 219, 249)) self.mapSettings.setOutputSize(QSize(400, 400)) self.mapSettings.setOutputDpi(96) self.extent = QgsRectangle(-118.8888888888887720, 22.8002070393376783, -83.3333333333331581, 46.8719806763287536) def testVectorBlending(self): """Test that blend modes work for vector layers.""" # Add vector layers to map myLayers = [] myLayers.append(self.mLineLayer.id()) myLayers.append(self.mPolygonLayer.id()) self.mapSettings.setLayers(myLayers) self.mapSettings.setExtent(self.extent) # Set blending modes for both layers self.mLineLayer.setBlendMode(QPainter.CompositionMode_Difference) self.mPolygonLayer.setBlendMode(QPainter.CompositionMode_Difference) checker = QgsMultiRenderChecker() checker.setControlName("expected_vector_blendmodes") checker.setMapSettings(self.mapSettings) checker.setColorTolerance(1) myResult = checker.runTest("vector_blendmodes", 20) myMessage = ('vector blending failed') assert myResult, myMessage # Reset layers self.mLineLayer.setBlendMode(QPainter.CompositionMode_SourceOver) self.mPolygonLayer.setBlendMode(QPainter.CompositionMode_SourceOver) def testVectorFeatureBlending(self): """Test that feature blend modes work for vector layers.""" # Add vector layers to map myLayers = [] myLayers.append(self.mLineLayer.id()) myLayers.append(self.mPolygonLayer.id()) self.mapSettings.setLayers(myLayers) self.mapSettings.setExtent(self.extent) # Set feature blending for line layer self.mLineLayer.setFeatureBlendMode(QPainter.CompositionMode_Plus) checker = QgsMultiRenderChecker() checker.setControlName("expected_vector_featureblendmodes") checker.setMapSettings(self.mapSettings) checker.setColorTolerance(1) myResult = checker.runTest("vector_featureblendmodes", 20) myMessage = ('vector feature blending failed') assert myResult, myMessage # Reset layers self.mLineLayer.setFeatureBlendMode(QPainter.CompositionMode_SourceOver) def testVectorLayerTransparency(self): """Test that layer transparency works for vector layers.""" # Add vector layers to map myLayers = [] myLayers.append(self.mLineLayer.id()) myLayers.append(self.mPolygonLayer.id()) self.mapSettings.setLayers(myLayers) self.mapSettings.setExtent(self.extent) # Set feature blending for line layer self.mLineLayer.setLayerTransparency(50) checker = QgsMultiRenderChecker() checker.setControlName("expected_vector_layertransparency") checker.setMapSettings(self.mapSettings) checker.setColorTolerance(1) myResult = checker.runTest("vector_layertransparency", 20) myMessage = ('vector layer transparency failed') assert myResult, myMessage def testRasterBlending(self): """Test that blend modes work for raster layers.""" # Add raster layers to map myLayers = [] myLayers.append(self.mRasterLayer1.id()) myLayers.append(self.mRasterLayer2.id()) self.mapSettings.setLayers(myLayers) self.mapSettings.setExtent(self.mRasterLayer1.extent()) # Set blending mode for top layer self.mRasterLayer1.setBlendMode(QPainter.CompositionMode_Difference) checker = QgsMultiRenderChecker() checker.setControlName("expected_raster_blendmodes") checker.setMapSettings(self.mapSettings) checker.setColorTolerance(1) checker.setColorTolerance(1) myResult = checker.runTest("raster_blendmodes", 20) myMessage = ('raster blending failed') assert myResult, myMessage
def add_ee_image_layer(imageid, name, date, bands, scale, b_min=None, b_max=None, palette=None, qml=None, extent=None, shown=False, destination=None): nbands = len(bands) # if nbands > 3: # rgb = ee.Image(imageid).select(bands[0:3]) # pan = ee.Image(imageid).select(bands[3]) # huesat = rgb.rgbToHsv().select('hue', 'saturation') # image = ee.Image.cat(huesat, pan).hsvToRgb().select([0, 1, 2], bands[0:3]) # nbands = 3 # else: image = ee.Image(imageid) if not any([b_min, b_max, palette, qml]): image_stats = image.select(bands[0:nbands]).reduceRegion(ee.Reducer.minMax(), None, scale, None, None, False, 1.0E13).getInfo() b_min = [image_stats[bands[n] + '_min'] for n in range(nbands)] b_max = [image_stats[bands[n] + '_max'] for n in range(nbands)] # b_min = [image_stats[bands[0] + '_min'], image_stats[bands[1] + '_min'], image_stats[bands[2] + '_min']] # b_max = [image_stats[bands[0] + '_max'], image_stats[bands[1] + '_max'], image_stats[bands[2] + '_max']] rgb = image.visualize(bands=bands[0:nbands], min=b_min, max=b_max, palette=palette) tms = get_ee_image_tms(rgb) if extent is None: image_geojson = get_ee_image_bb(rgb) extent = geojson_to_wkt(image_geojson) bb = QgsRectangle.fromWkt(extent) url = tms_to_gdalurl(tms) xml = get_gdal_xml(url, nbands=nbands+1) # vfn = write_vsimem_xml(xml) # changed to named temporary file tmp, fn = write_xmlfile(xml, name, dest=destination) layer = QgsRasterLayer(fn, name) if layer.isValid(): if qml is not None: if isfile(qml + '_' + QSettings().value('locale/userLocale') + '.qml'): layer.loadNamedStyle(qml + '_' + QSettings().value('locale/userLocale') + '.qml') else: layer.loadNamedStyle(qml + '.qml') layer.setExtent(bb) if tmp: layer.setCustomProperty('ee-image', 'MEM') else: layer.setCustomProperty('ee-image', 'XML') layer.setCustomProperty('ee-image-id', imageid) layer.setCustomProperty('ee-image-date', date) layer.setCustomProperty('ee-image-bands', bands) layer.setCustomProperty('ee-image-scale', scale) layer.setCustomProperty('ee-image-b_min', b_min) layer.setCustomProperty('ee-image-b_max', b_max) layer.setCustomProperty('ee-image-palette', palette) layer.setCustomProperty('ee-image-qml', qml) layer.setCustomProperty('ee-image-wkt', extent) # else: # layer.setAbstract(f"ee.Image('{imageid}')") # if len(bands) < 4: # try: # layer.setCustomProperty('ee-image-stats', image_stats) # except NameError: # pass if date is not None: layer.setAbstract(f"ee.Image('{imageid}') \n\nDate: {date}") else: layer.setAbstract(f"ee.Image('{imageid}')") QgsProject.instance().addMapLayer(layer) if not shown: QgsProject.instance().layerTreeRoot().findLayer(layer.id()).setItemVisibilityChecked(shown)
class TestQgsBlendModes(unittest.TestCase): def __init__(self, methodName): """Run once on class initialization.""" unittest.TestCase.__init__(self, methodName) self.iface = get_iface() # initialize class MapRegistry, Canvas, MapRenderer, Map and PAL self.mMapRegistry = QgsMapLayerRegistry.instance() # create point layer myShpFile = os.path.join(TEST_DATA_DIR, 'points.shp') self.mPointLayer = QgsVectorLayer(myShpFile, 'Points', 'ogr') self.mMapRegistry.addMapLayer(self.mPointLayer) self.mSimplifyMethod = QgsVectorSimplifyMethod() self.mSimplifyMethod.setSimplifyHints( QgsVectorSimplifyMethod.NoSimplification) # create polygon layer myShpFile = os.path.join(TEST_DATA_DIR, 'polys.shp') self.mPolygonLayer = QgsVectorLayer(myShpFile, 'Polygons', 'ogr') self.mPolygonLayer.setSimplifyMethod(self.mSimplifyMethod) self.mMapRegistry.addMapLayer(self.mPolygonLayer) # create line layer myShpFile = os.path.join(TEST_DATA_DIR, 'lines.shp') self.mLineLayer = QgsVectorLayer(myShpFile, 'Lines', 'ogr') self.mLineLayer.setSimplifyMethod(self.mSimplifyMethod) self.mMapRegistry.addMapLayer(self.mLineLayer) # create two raster layers myRasterFile = os.path.join(TEST_DATA_DIR, 'rgb256x256.png') self.mRasterLayer1 = QgsRasterLayer(myRasterFile, "raster1") self.mRasterLayer2 = QgsRasterLayer(myRasterFile, "raster2") myMultiBandRenderer1 = QgsMultiBandColorRenderer( self.mRasterLayer1.dataProvider(), 1, 2, 3) self.mRasterLayer1.setRenderer(myMultiBandRenderer1) self.mMapRegistry.addMapLayer(self.mRasterLayer1) myMultiBandRenderer2 = QgsMultiBandColorRenderer( self.mRasterLayer2.dataProvider(), 1, 2, 3) self.mRasterLayer2.setRenderer(myMultiBandRenderer2) self.mMapRegistry.addMapLayer(self.mRasterLayer2) # to match blend modes test comparisons background self.mCanvas = self.iface.mapCanvas() self.mCanvas.setCanvasColor(QColor(152, 219, 249)) self.mMap = self.mCanvas.map() self.mMap.resize(QSize(400, 400)) self.mapSettings = self.mCanvas.mapSettings() self.mapSettings.setOutputSize(QSize(400, 400)) self.mapSettings.setOutputDpi(96) self.extent = QgsRectangle(-118.8888888888887720, 22.8002070393376783, -83.3333333333331581, 46.8719806763287536) def testVectorBlending(self): """Test that blend modes work for vector layers.""" # Add vector layers to map myLayers = [] myLayers.append(self.mLineLayer.id()) myLayers.append(self.mPolygonLayer.id()) self.mapSettings.setLayers(myLayers) self.mapSettings.setExtent(self.extent) # Set blending modes for both layers self.mLineLayer.setBlendMode(QPainter.CompositionMode_Difference) self.mPolygonLayer.setBlendMode(QPainter.CompositionMode_Difference) checker = QgsMultiRenderChecker() checker.setControlName("expected_vector_blendmodes") checker.setMapSettings(self.mapSettings) checker.setColorTolerance(1) myResult = checker.runTest("vector_blendmodes", 20) myMessage = ('vector blending failed') assert myResult, myMessage # Reset layers self.mLineLayer.setBlendMode(QPainter.CompositionMode_SourceOver) self.mPolygonLayer.setBlendMode(QPainter.CompositionMode_SourceOver) def testVectorFeatureBlending(self): """Test that feature blend modes work for vector layers.""" # Add vector layers to map myLayers = [] myLayers.append(self.mLineLayer.id()) myLayers.append(self.mPolygonLayer.id()) self.mapSettings.setLayers(myLayers) self.mapSettings.setExtent(self.extent) # Set feature blending for line layer self.mLineLayer.setFeatureBlendMode(QPainter.CompositionMode_Plus) checker = QgsMultiRenderChecker() checker.setControlName("expected_vector_featureblendmodes") checker.setMapSettings(self.mapSettings) checker.setColorTolerance(1) myResult = checker.runTest("vector_featureblendmodes", 20) myMessage = ('vector feature blending failed') assert myResult, myMessage # Reset layers self.mLineLayer.setFeatureBlendMode( QPainter.CompositionMode_SourceOver) def testVectorLayerTransparency(self): """Test that layer transparency works for vector layers.""" # Add vector layers to map myLayers = [] myLayers.append(self.mLineLayer.id()) myLayers.append(self.mPolygonLayer.id()) self.mapSettings.setLayers(myLayers) self.mapSettings.setExtent(self.extent) # Set feature blending for line layer self.mLineLayer.setLayerTransparency(50) checker = QgsMultiRenderChecker() checker.setControlName("expected_vector_layertransparency") checker.setMapSettings(self.mapSettings) checker.setColorTolerance(1) myResult = checker.runTest("vector_layertransparency", 20) myMessage = ('vector layer transparency failed') assert myResult, myMessage def testRasterBlending(self): """Test that blend modes work for raster layers.""" # Add raster layers to map myLayers = [] myLayers.append(self.mRasterLayer1.id()) myLayers.append(self.mRasterLayer2.id()) self.mapSettings.setLayers(myLayers) self.mapSettings.setExtent(self.mRasterLayer1.extent()) # Set blending mode for top layer self.mRasterLayer1.setBlendMode(QPainter.CompositionMode_Difference) checker = QgsMultiRenderChecker() checker.setControlName("expected_raster_blendmodes") checker.setMapSettings(self.mapSettings) checker.setColorTolerance(1) checker.setColorTolerance(1) myResult = checker.runTest("raster_blendmodes", 20) myMessage = ('raster blending failed') assert myResult, myMessage
def processAlgorithm(self, parameters, context, feedback): self.PreRun(parameters, context, feedback) commands = self.getConsoleCommands(parameters, context, feedback) ChloeUtils.runChloe(commands, feedback) print('parameters : {}'.format(str(parameters))) # Auto generate outputs: dict {'name parameter' : 'value', ...} for output in self.destinationParameterDefinitions(): print(str(output) + " " + str(output.metadata())) results = {} for o in self.outputDefinitions(): if o.name() in parameters: results[o.name()] = parameters[o.name()] for k, v in self.output_values.items(): results[k] = v # Load OUTPUT_ASC on temp layer on context id checked box checked # (it will be load after in the project) # #print('context : {}'.format(context)) #print('parameterDefinitions : {}'.format(self.parameterDefinitions())) if ('OUTPUT_ASC' in parameters ) and 'openLayer' in parameters['OUTPUT_ASC'] and parameters[ 'OUTPUT_ASC']['openLayer'] == True: # Load OUTPUT_ASC on temp layer on context # (it will be load after in the project) output_asc = parameters['OUTPUT_ASC']["data"] rlayer = QgsRasterLayer(output_asc, "hillshade") if not rlayer.isValid(): raise QgsProcessingException( self.tr("""Cannot load the output in the application""")) rLayerName = ChloeUtils.deduceLayerName(rlayer, self.name()) ChloeUtils.setLayerSymbology(rlayer, 'continuous.qml') context.temporaryLayerStore().addMapLayer(rlayer) layerDetails = QgsProcessingContext.LayerDetails( rLayerName, context.project(), self.OUTPUT_ASC) #postProcess = ChloeOutputLayerPostProcessor()t #layerDetails.setPostProcessor(postProcess) context.addLayerToLoadOnCompletion(rlayer.id(), layerDetails) results[self.OUTPUT_ASC] = rlayer.id() if ('OUTPUT_CSV' in parameters ) and parameters['OUTPUT_CSV']['openLayer'] == True: uri = "file:///" + str( results['OUTPUT_CSV'] ) + "?type=csv&delimiter=;&detectTypes=yes&geomType=none&subsetIndex=no&watchFile=no" output_csv = parameters['OUTPUT_CSV']["data"] if 'OUTPUT_ASC' in parameters: output_csv = ChloeUtils.adjustExtension( output_csv, parameters['OUTPUT_ASC']["data"]) print("output_csv " + str(uri) + " " + str(output_csv)) tLayerName = ChloeUtils.deduceLayerName(output_csv, self.name()) tLayer = QgsVectorLayer(uri, tLayerName, 'delimitedtext') if not tLayer.isValid(): raise QgsProcessingException( self.tr("""Cannot load the outpout in the application""")) context.temporaryLayerStore().addMapLayer(tLayer) layerDetails = QgsProcessingContext.LayerDetails( tLayerName, context.project(), self.OUTPUT_CSV) context.addLayerToLoadOnCompletion(tLayer.id(), layerDetails) results[self.OUTPUT_CSV] = tLayer.id() if ('OUTPUT_DIR' in parameters) and self.outputFilenames and parameters[ 'OUTPUT_DIR']['openLayer'] == True: # === import all asc for multi algorithm outputDir = self.parameterAsString(parameters, self.OUTPUT_DIR, context) if outputDir != None: self.prepareMultiProjectionFiles() for file in self.outputFilenames: print(file + " " + os.path.splitext(os.path.basename(file))[0]) rlayer = QgsRasterLayer( file, os.path.splitext(os.path.basename(file))[0]) #rlayer = QgsRasterLayer(load_it, "hillshade") if not rlayer.isValid(): raise QgsProcessingException( self. tr("""Cannot load the outpout in the application""" )) rLayerName = ChloeUtils.deduceLayerName( rlayer, self.name()) ChloeUtils.setLayerSymbology(rlayer, 'continuous.qml') context.temporaryLayerStore().addMapLayer(rlayer) layerDetails = QgsProcessingContext.LayerDetails( rLayerName, context.project(), self.OUTPUT_DIR) context.addLayerToLoadOnCompletion(rlayer.id(), layerDetails) return results
def testTransparency(self): myPath = os.path.join(unitTestDataPath('raster'), 'band1_float32_noct_epsg4326.tif') myFileInfo = QFileInfo(myPath) myBaseName = myFileInfo.baseName() myRasterLayer = QgsRasterLayer(myPath, myBaseName) myMessage = 'Raster not loaded: %s' % myPath assert myRasterLayer.isValid(), myMessage renderer = QgsSingleBandGrayRenderer(myRasterLayer.dataProvider(), 1) myRasterLayer.setRenderer(renderer) myRasterLayer.setContrastEnhancement( QgsContrastEnhancement.StretchToMinimumMaximum, QgsRaster.ContrastEnhancementMinMax) myContrastEnhancement = myRasterLayer.renderer().contrastEnhancement() # print ("myContrastEnhancement.minimumValue = %.17g" % # myContrastEnhancement.minimumValue()) # print ("myContrastEnhancement.maximumValue = %.17g" % # myContrastEnhancement.maximumValue()) # Unfortunately the minimum/maximum values calculated in C++ and Python # are slightly different (e.g. 3.3999999521443642e+38 x # 3.3999999521444001e+38) # It is not clear where the precision is lost. # We set the same values as C++. myContrastEnhancement.setMinimumValue(-3.3319999287625854e+38) myContrastEnhancement.setMaximumValue(3.3999999521443642e+38) #myType = myRasterLayer.dataProvider().dataType(1); #myEnhancement = QgsContrastEnhancement(myType); myTransparentSingleValuePixelList = [] rasterTransparency = QgsRasterTransparency() myTransparentPixel1 = \ QgsRasterTransparency.TransparentSingleValuePixel() myTransparentPixel1.min = -2.5840000772112106e+38 myTransparentPixel1.max = -1.0879999684602689e+38 myTransparentPixel1.percentTransparent = 50 myTransparentSingleValuePixelList.append(myTransparentPixel1) myTransparentPixel2 = \ QgsRasterTransparency.TransparentSingleValuePixel() myTransparentPixel2.min = 1.359999960575336e+37 myTransparentPixel2.max = 9.520000231087593e+37 myTransparentPixel2.percentTransparent = 70 myTransparentSingleValuePixelList.append(myTransparentPixel2) rasterTransparency.setTransparentSingleValuePixelList( myTransparentSingleValuePixelList) rasterRenderer = myRasterLayer.renderer() assert rasterRenderer rasterRenderer.setRasterTransparency(rasterTransparency) QgsMapLayerRegistry.instance().addMapLayers([ myRasterLayer, ]) myMapSettings = QgsMapSettings() myMapSettings.setLayers([myRasterLayer.id()]) myMapSettings.setExtent(myRasterLayer.extent()) myChecker = QgsRenderChecker() myChecker.setControlName("expected_raster_transparency") myChecker.setMapSettings(myMapSettings) myResultFlag = myChecker.runTest("raster_transparency_python") assert myResultFlag, "Raster transparency rendering test failed"
def addRasterLayers(project, server, schema): """ add postgis raster layers to qgis project """ groups = [] # get postgis raster table records = server.getTableNames(schema, match='^rast_[0-9]{8}_.*') print('processing {count} tables in schema {schema}'.format( count=len(records), schema=schema)) for record in records: # get gdal postgis raster connection string table = record[0] uri_config = { # database parameters 'dbname': server.getDatabase(), # The PostgreSQL database to connect to. 'host': server.getHost(), # The host IP address or localhost. 'port': server.getPort(), # The port to connect on. 'sslmode': QgsDataSourceUri. SslDisable, # SslAllow, SslPrefer, SslRequire, SslVerifyCa, SslVerifyFull # user and password are not needed if stored in the authcfg or service 'authcfg': None, # The QGIS athentication database ID holding connection details. 'service': None, # The PostgreSQL service to be used for connection to the database. 'username': '******', # The PostgreSQL user name. 'password': '******', # The PostgreSQL password for the user. # table and raster column details 'schema': schema, # The database schema that the table is located in. 'table': table, # The database table to be loaded. 'geometrycolumn': 'rast', # raster column in PostGIS table 'sql': None, # An SQL WHERE clause. It should be placed at the end of the string. 'key': None, # A key column from the table. 'srid': '27700', # A string designating the SRID of the coordinate reference system. 'estimatedmetadata': 'False', # A boolean value telling if the metadata is estimated. 'type': None, # A WKT string designating the WKB Type. 'selectatid': None, # Set to True to disable selection by feature ID. 'options': None, # other PostgreSQL connection options not in this list. 'enableTime': None, 'temporalDefaultTime': None, 'temporalFieldIndex': None, 'mode': '2', # GDAL 'mode' parameter, 2 unions raster tiles, 1 adds tiles separately (may require user input) } # remove any NULL parameters uri_config = { key: val for key, val in uri_config.items() if val is not None } # get metadata for raster provider and configure uri md = QgsProviderRegistry.instance().providerMetadata('postgresraster') uri = QgsDataSourceUri(md.encodeUri(uri_config)) # create layer layer = QgsRasterLayer(uri.uri(False), table, "postgresraster") if layer.isValid(): try: # add to project layer.setContrastEnhancement( QgsContrastEnhancement.StretchToMinimumMaximum, QgsRasterMinMaxOrigin.CumulativeCut) QgsProject.instance().addMapLayer(layer) # extract date from table name dt = datetime.strptime( re.search('[0-9]{8}', table)[0], '%Y%m%d') sub_group = next( (item for item in groups if str(dt.year) == item['year']), None) if sub_group is None: groups.append({'year': str(dt.year), 'layers': []}) # add layer id to schema / year indexed lists sub_group = next( (item for item in groups if str(dt.year) == item['year']), None) sub_group['layers'].append({ 'id': layer.id(), 'dt': dt, 'name': table }) except Exception as e: print('ERROR: {conn} {msg}'.format(conn=uri.uri(False), msg=e)) # return layers in yearly slices in descending order return sorted(groups, key=lambda k: k['year'], reverse=True)
def _test(is_dbf): QgsProject.instance().removeAllMapLayers() tmp_dir = QTemporaryDir() shutil.copy( os.path.join(os.path.dirname(__file__), 'data', 'raster-palette.tif'), tmp_dir.path()) rat_path = os.path.join( tmp_dir.path(), 'raster-palette.tif' + ('.vat.dbf' if is_dbf else '.aux.xml')) self.assertFalse(os.path.exists(rat_path)) raster_layer = QgsRasterLayer( os.path.join(tmp_dir.path(), 'raster-palette.tif'), 'rat_test', 'gdal') QgsProject.instance().addMapLayer(raster_layer) self.assertTrue(raster_layer.isValid()) self.assertFalse(can_create_rat(raster_layer)) self.assertFalse(has_rat(raster_layer)) band = 1 # Set renderer ramp = QgsRandomColorRamp() renderer = QgsPalettedRasterRenderer( raster_layer.dataProvider(), 1, QgsPalettedRasterRenderer.classDataFromRaster( raster_layer.dataProvider(), band, ramp)) raster_layer.setRenderer(renderer) self.assertTrue(can_create_rat(raster_layer)) rat = create_rat_from_raster(raster_layer, is_dbf, rat_path) self.assertTrue(rat.isValid()) self.assertEqual(rat.data['Count'], [78, 176, 52]) self.assertEqual( rat.data['Value'], [2.257495271713565, 7.037407804695962, 270.4551067154352]) self.assertEqual(rat.data['A'], [255, 255, 255]) self.assertNotEqual(rat.data['R'], [0, 0, 0]) self.assertTrue(rat.save(band)) self.assertTrue(os.path.exists(rat_path)) QgsProject.instance().removeMapLayers([raster_layer.id()]) del (raster_layer) self.assertTrue(os.path.exists(rat_path)) QgsApplication.processEvents() # Reload and check raster_layer = QgsRasterLayer( os.path.join(tmp_dir.path(), 'raster-palette.tif'), 'rat_test', 'gdal') self.assertTrue(raster_layer.isValid()) self.assertFalse(can_create_rat(raster_layer)) self.assertTrue(has_rat(raster_layer), rat_path) os.unlink(rat_path)
class ElevationDockWidget(QtWidgets.QDockWidget, FORM_CLASS): closingPlugin = pyqtSignal() dataChange = pyqtSignal(QRiSProject, str) def __init__(self, raster, qris_project, parent=None): """Constructor.""" super(ElevationDockWidget, self).__init__(parent) # Set up the user interface from Designer. # After setupUI you can access any designer object by doing # self.<objectname>, and you can use autoconnect slots - see # http://doc.qt.io/qt-5/designer-using-a-ui-file.html # #widgets-and-dialogs-with-auto-connect self.setupUi(self) self.qris_project = qris_project self.raster = raster self.elevation_value = 1.0 self.txtRasterName.setText(self.raster.name) self.raster_path = os.path.join(self.qris_project.project_path, raster.path) self.group_layer = None self.raster_layer = QgsRasterLayer(self.raster_path, 'Elevation Explorer') self.base_raster_layer = QgsRasterLayer(self.raster_path, self.raster.name) self.base_raster_layer.loadNamedStyle(os.path.join(os.path.dirname(__file__), "..", 'resources', 'symbology', 'hand.qml')) self.updateElevationLayer(self.elevation_value) QgsProject.instance().addMapLayer(self.base_raster_layer) QgsProject.instance().addMapLayer(self.raster_layer) # TODO Get min max of raster and apply to slider tools self.elevationSlider.valueChanged.connect(self.sliderElevationChange) self.numElevation.valueChanged.connect(self.spinBoxElevationChange) self.btnExport.clicked.connect(self.exportPolygonDlg) # self.closingPlugin.connect(self.closeWidget) def closeEvent(self, event): QgsProject.instance().removeMapLayer(self.base_raster_layer.id()) QgsProject.instance().removeMapLayer(self.raster_layer.id()) iface.mapCanvas().refresh() self.close() self.destroy() def updateElevationLayer(self, value=1.0): fcn = QgsColorRampShader() fcn.setColorRampType(QgsColorRampShader.Discrete) fcn.setColorRampItemList([QgsColorRampShader.ColorRampItem(value, QColor(255, 20, 225), f'Elevation {value}')]) shader = QgsRasterShader() shader.setRasterShaderFunction(fcn) renderer = QgsSingleBandPseudoColorRenderer(self.raster_layer.dataProvider(), 1, shader) self.raster_layer.setRenderer(renderer) self.raster_layer.triggerRepaint() def sliderElevationChange(self, value): self.elevation_value = value / 10 self.updateElevationLayer(value / 10) self.numElevation.setValue(value / 10) def spinBoxElevationChange(self, value): self.elevation_value = value self.updateElevationLayer(value) self.elevationSlider.setValue(int(value * 10)) def exportPolygonDlg(self): self.export_dlg = ExportElevationSurfaceDlg(self.raster, self.elevation_value, self.qris_project) self.export_dlg.dataChange.connect(self.exportPolgyon) self.export_dlg.show() def exportPolgyon(self, updated_project, surface_name): self.qris_project = updated_project self.dataChange.emit(self.qris_project, surface_name) self.closeWidget() return def closeWidget(self): QgsProject.instance().removeMapLayer(self.base_raster_layer.id()) QgsProject.instance().removeMapLayer(self.raster_layer.id()) self.close() self.destroy() return
def renderer(self): if 'QGIS_AUTH_DB_DIR_PATH' not in os.environ: os.environ['QGIS_AUTH_DB_DIR_PATH'] = '/tmp' qgis = None while True: options, result = self.queue.get() # Don't start QGIS until first request if qgis is None: qgis = QgsApplication([], False) qgis.setPrefixPath(self.settings.get('path'), True) qgis.setDefaultSvgPaths(qgis.svgPaths() + self.settings.get('svgpaths')) qgis.setMaxThreads(1) qgis.initQgis() try: if isinstance(options, LegendOptions): style, = options layer = self._qgs_memory_layer(style) layer.setName(style.parent.display_name) QgsMapLayerRegistry.instance().addMapLayer(layer) root = QgsLayerTreeGroup() root.addLayer(layer) # 'Cannot create a QPixmap when no GUI is being used' # warning occurs here model = QgsLayerTreeModel(root) settings = QgsLegendSettings() settings.setTitle('') settings.setBoxSpace(1) settings.setSymbolSize(QSizeF(5, 3)) settings.setDpi(96) renderer = QgsLegendRenderer(model, settings) # Dots per mm dpmm = settings.dpi() / 25.4 min_size = renderer.minimumSize() size = QSize(dpmm * min_size.width(), dpmm * min_size.height()) img = QImage(size, QImage.Format_ARGB32) img.fill(QColor(0, 0, 0, 0)) painter = QPainter() painter.begin(img) painter.scale(dpmm, dpmm) renderer.drawLegend(painter) painter.end() QgsMapLayerRegistry.instance().removeAllMapLayers() ba = QByteArray() bf = QBuffer(ba) bf.open(QIODevice.WriteOnly) img.save(bf, 'PNG') bf.close() buf = StringIO() buf.write(bf.data()) buf.seek(0) result.put(buf) else: path = features = None if isinstance(options, VectorRenderOptions): style, features, render_size, \ extended, target_box = options layer = self._qgs_memory_layer(style, features=features) elif isinstance(options, RasterRenderOptions): style, path, render_size, \ extended, target_box = options layer = QgsRasterLayer(path) layer.loadNamedStyle( self.env.file_storage.filename(style.qml_fileobj)) settings = QgsMapSettings() settings.setLayers([layer.id()]) settings.setFlag(QgsMapSettings.DrawLabeling) settings.setFlag(QgsMapSettings.Antialiasing) settings.setCrsTransformEnabled(True) settings.setDestinationCrs(layer.crs()) settings.setMapUnits(layer.crs().mapUnits()) settings.setOutputSize(QSize(*render_size)) settings.setExtent(QgsRectangle(*extended)) settings.setOutputImageFormat(QImage.Format_ARGB32) bgcolor = QColor.fromRgba(qRgba(255, 255, 255, 0)) settings.setBackgroundColor(bgcolor) settings.setOutputDpi(96) QgsMapLayerRegistry.instance().addMapLayer(layer) settings.setLayers([layer.id()]) # Create QImage by hand to be able to use # QgsMapRendererCustomPainterJob. Others will not # allow to workaround a bug with overlay rendering. img = QImage(settings.outputSize(), QImage.Format_ARGB32) # These cludges are needed for rendering # on transparent background, otherwise it's a mess. img.fill(QColor.fromRgba(qRgba(255, 255, 255, 255))) img.fill(QColor.fromRgba(qRgba(255, 255, 255, 0))) # DPI should be equal to settings, otherwise an error. # In QImage the resolution is set in dots per meter # for each axis. dpm = settings.outputDpi() / 25.4 * 1000 img.setDotsPerMeterX(dpm) img.setDotsPerMeterY(dpm) painter = QPainter(img) job = QgsMapRendererCustomPainterJob(settings, painter) job.renderSynchronously() painter.end() QgsMapLayerRegistry.instance().removeAllMapLayers() img = self._qimage_to_pil(img) # Clip needed part result.put(img.crop(target_box)) # Cleanup if path is not None: gdal.Unlink(path) except Exception as exc: self.logger.error(exc.message) result.put(exc) qgis.exitQgis()
def testTransparency(self): myPath = os.path.join(unitTestDataPath('raster'), 'band1_float32_noct_epsg4326.tif') myFileInfo = QFileInfo(myPath) myBaseName = myFileInfo.baseName() myRasterLayer = QgsRasterLayer(myPath, myBaseName) myMessage = 'Raster not loaded: %s' % myPath assert myRasterLayer.isValid(), myMessage renderer = QgsSingleBandGrayRenderer(myRasterLayer.dataProvider(), 1) myRasterLayer.setRenderer(renderer) myRasterLayer.setContrastEnhancementAlgorithm( QgsContrastEnhancement.StretchToMinimumMaximum, QgsRasterLayer.ContrastEnhancementMinMax) myContrastEnhancement = myRasterLayer.renderer().contrastEnhancement() #print ("myContrastEnhancement.minimumValue = %.17g" % # myContrastEnhancement.minimumValue()) #print ("myContrastEnhancement.maximumValue = %.17g" % # myContrastEnhancement.maximumValue()) # Unfortunately the minimum/maximum values calculated in C++ and Python # are slightly different (e.g. 3.3999999521443642e+38 x # 3.3999999521444001e+38) # It is not clear where the precision is lost. # We set the same values as C++. myContrastEnhancement.setMinimumValue(-3.3319999287625854e+38) myContrastEnhancement.setMaximumValue(3.3999999521443642e+38) #myType = myRasterLayer.dataProvider().dataType(1); #myEnhancement = QgsContrastEnhancement(myType); myTransparentSingleValuePixelList = [] rasterTransparency = QgsRasterTransparency() myTransparentPixel1 = \ QgsRasterTransparency.TransparentSingleValuePixel() myTransparentPixel1.min = -2.5840000772112106e+38 myTransparentPixel1.max = -1.0879999684602689e+38 myTransparentPixel1.percentTransparent = 50 myTransparentSingleValuePixelList.append(myTransparentPixel1) myTransparentPixel2 = \ QgsRasterTransparency.TransparentSingleValuePixel() myTransparentPixel2.min = 1.359999960575336e+37 myTransparentPixel2.max = 9.520000231087593e+37 myTransparentPixel2.percentTransparent = 70 myTransparentSingleValuePixelList.append(myTransparentPixel2) rasterTransparency.setTransparentSingleValuePixelList( myTransparentSingleValuePixelList) rasterRenderer = myRasterLayer.renderer() assert rasterRenderer rasterRenderer.setRasterTransparency(rasterTransparency) QgsMapLayerRegistry.instance().addMapLayers([ myRasterLayer, ]) myMapRenderer = QgsMapRenderer() myLayers = QStringList() myLayers.append(myRasterLayer.id()) myMapRenderer.setLayerSet(myLayers) myMapRenderer.setExtent(myRasterLayer.extent()) myChecker = QgsRenderChecker() myChecker.setControlName("expected_raster_transparency") myChecker.setMapRenderer(myMapRenderer) myResultFlag = myChecker.runTest("raster_transparency_python"); assert myResultFlag, "Raster transparency rendering test failed"
class TestQgsBlendModes(TestCase): def __init__(self, methodName): """Run once on class initialisation.""" unittest.TestCase.__init__(self, methodName) # initialize class MapRegistry, Canvas, MapRenderer, Map and PAL self.mMapRegistry = QgsMapLayerRegistry.instance() # create point layer myShpFile = os.path.join(TEST_DATA_DIR, 'points.shp') self.mPointLayer = QgsVectorLayer(myShpFile, 'Points', 'ogr') self.mMapRegistry.addMapLayer(self.mPointLayer) # create polygon layer myShpFile = os.path.join(TEST_DATA_DIR, 'polys.shp') self.mPolygonLayer = QgsVectorLayer(myShpFile, 'Polygons', 'ogr') self.mMapRegistry.addMapLayer(self.mPolygonLayer) # create line layer myShpFile = os.path.join(TEST_DATA_DIR, 'lines.shp') self.mLineLayer = QgsVectorLayer(myShpFile, 'Lines', 'ogr') self.mMapRegistry.addMapLayer(self.mLineLayer) # create two raster layers myRasterFile = os.path.join(TEST_DATA_DIR, 'landsat.tif') self.mRasterLayer1 = QgsRasterLayer(myRasterFile, "raster1") self.mRasterLayer2 = QgsRasterLayer(myRasterFile, "raster2") myMultiBandRenderer1 = QgsMultiBandColorRenderer( self.mRasterLayer1.dataProvider(), 2, 3, 4) self.mRasterLayer1.setRenderer(myMultiBandRenderer1) self.mMapRegistry.addMapLayer(self.mRasterLayer1) myMultiBandRenderer2 = QgsMultiBandColorRenderer( self.mRasterLayer2.dataProvider(), 2, 3, 4) self.mRasterLayer2.setRenderer(myMultiBandRenderer2) self.mMapRegistry.addMapLayer(self.mRasterLayer2) # to match blend modes test comparisons background self.mCanvas = CANVAS self.mCanvas.setCanvasColor(QColor(152, 219, 249)) self.mMap = self.mCanvas.map() self.mMap.resize(QSize(400, 400)) self.mMapRenderer = self.mCanvas.mapRenderer() self.mMapRenderer.setOutputSize(QSize(400, 400), 72) def testVectorBlending(self): """Test that blend modes work for vector layers.""" #Add vector layers to map myLayers = QStringList() myLayers.append(self.mLineLayer.id()) myLayers.append(self.mPolygonLayer.id()) self.mMapRenderer.setLayerSet(myLayers) self.mMapRenderer.setExtent(self.mPointLayer.extent()) #Set blending modes for both layers self.mLineLayer.setBlendMode(QPainter.CompositionMode_Difference) self.mPolygonLayer.setBlendMode(QPainter.CompositionMode_Difference) checker = QgsRenderChecker() checker.setControlName("expected_vector_blendmodes") checker.setMapRenderer(self.mMapRenderer) myResult = checker.runTest("vector_blendmodes") myMessage = ('vector blending failed') assert myResult, myMessage #Reset layers self.mLineLayer.setBlendMode(QPainter.CompositionMode_SourceOver) self.mPolygonLayer.setBlendMode(QPainter.CompositionMode_SourceOver) def testVectorFeatureBlending(self): """Test that feature blend modes work for vector layers.""" #Add vector layers to map myLayers = QStringList() myLayers.append(self.mLineLayer.id()) myLayers.append(self.mPolygonLayer.id()) self.mMapRenderer.setLayerSet(myLayers) self.mMapRenderer.setExtent(self.mPointLayer.extent()) #Set feature blending for line layer self.mLineLayer.setFeatureBlendMode(QPainter.CompositionMode_Plus) checker = QgsRenderChecker() checker.setControlName("expected_vector_featureblendmodes") checker.setMapRenderer(self.mMapRenderer) myResult = checker.runTest("vector_featureblendmodes") myMessage = ('vector feature blending failed') assert myResult, myMessage #Reset layers self.mLineLayer.setFeatureBlendMode( QPainter.CompositionMode_SourceOver) def testVectorLayerTransparency(self): """Test that layer transparency works for vector layers.""" #Add vector layers to map myLayers = QStringList() myLayers.append(self.mLineLayer.id()) myLayers.append(self.mPolygonLayer.id()) self.mMapRenderer.setLayerSet(myLayers) self.mMapRenderer.setExtent(self.mPointLayer.extent()) #Set feature blending for line layer self.mLineLayer.setLayerTransparency(50) checker = QgsRenderChecker() checker.setControlName("expected_vector_layertransparency") checker.setMapRenderer(self.mMapRenderer) myResult = checker.runTest("vector_layertransparency") myMessage = ('vector layer transparency failed') assert myResult, myMessage def testRasterBlending(self): """Test that blend modes work for raster layers.""" #Add raster layers to map myLayers = QStringList() myLayers.append(self.mRasterLayer1.id()) myLayers.append(self.mRasterLayer2.id()) self.mMapRenderer.setLayerSet(myLayers) self.mMapRenderer.setExtent(self.mRasterLayer1.extent()) #Set blending mode for top layer self.mRasterLayer1.setBlendMode(QPainter.CompositionMode_Plus) checker = QgsRenderChecker() checker.setControlName("expected_raster_blendmodes") checker.setMapRenderer(self.mMapRenderer) myResult = checker.runTest("raster_blendmodes") myMessage = ('raster blending failed') assert myResult, myMessage
def processAlgorithm(self, parameters, context, feedback): """ Here is where the processing itself takes place. """ source = self.parameterAsVectorLayer(parameters, self.INPUT, context) field_insee = self.parameterAsString(parameters, self.INSEE_CODE, context) field_commune = self.parameterAsString(parameters, self.COMMUNE_NAME, context) value_epsg = self.parameterAsString(parameters, self.EPSG_CODE, context) if value_epsg == '2154' or value_epsg == '3942' or value_epsg == '3943' or value_epsg == '3944' or value_epsg == '3945' or value_epsg == '3946' or value_epsg == '3947' or value_epsg == '3948' or value_epsg == '3949' or value_epsg == '3950' or value_epsg == '32630' or value_epsg == ' 32631' or value_epsg == '32632' or value_epsg == '3857' or value_epsg == '4326' or value_epsg == '4258' or value_epsg == '32620' or value_epsg == '2970' or value_epsg == '2972' or value_epsg == '2973' or value_epsg == '2975' or value_epsg == '32622' or value_epsg == '32740' or value_epsg == '32738' or value_epsg == '4471' or value_epsg == '32621': feedback.pushInfo('EPSG code' + value_epsg) tab = [] for f in source.getFeatures(): col_select = f[field_insee], (''.join( (c for c in unicodedata.normalize('NFD', f[field_commune]) if unicodedata.category(c) != 'Mn'))) # Insere chaque ligne du CSV dans le tableau tab.append(col_select) #Permet la suppression des doublons et le tri Lt = sorted(set(tab)) print(Lt) for c_insee, n_couche in Lt: urlWithParams = "url=http://inspire.cadastre.gouv.fr/scpc/" + c_insee + ".wms?contextualWMSLegend=0&crs=EPSG:" + value_epsg + "&dpiMode=7&featureCount=10&format=image/png&layers=VOIE_COMMUNICATION&styles=&maxHeight=1024&maxWidth=1280" rlayer = QgsRasterLayer( urlWithParams, 'Petites_voies_de_communication_' + n_couche + '_' + c_insee, 'wms') feedback.pushInfo('Category :' + n_couche + ' - ' + c_insee) feedback.pushInfo('Validity of WMS : %s' % rlayer.isValid()) if not rlayer.isValid(): print('Petites_voies_de_communication_' + n_couche + '_' + c_insee + ' failed to load!') feedback.pushInfo('WMS INVALID : Cadastre_' + n_couche + '_' + c_insee) else: #Source : https://gis.stackexchange.com/questions/342802/loading-openstreetmap-in-pyqgis output_layers = [] output_layers.append(rlayer) context.temporaryLayerStore().addMapLayer(rlayer) context.addLayerToLoadOnCompletion( rlayer.id(), QgsProcessingContext.LayerDetails( 'Petites_voies_de_communication_' + n_couche + '_' + c_insee, context.project(), self.OUTPUT_LAYERS)) else: feedback.pushInfo('Error EPSG code') # Return the results of the algorithm. In this case our only result is # the feature sink which contains the processed features, but some # algorithms may return multiple feature sinks, calculated numeric # statistics, etc. These should all be included in the returned # dictionary, with keys matching the feature corresponding parameter # or output names. # At the end of the processAlgorithmn # Add the layer to the project return {}
def addToDefaultProject(maps, visibleMaps, authcfg=None): """Add basemaps to the existing default project""" layers = [] for m in maps: connstring = u'type=xyz&url={url}' if authcfg is not None: connstring = u'authcfg={authcfg}&' + connstring layer = QgsRasterLayer(connstring.format(url=urllib2.quote("{}?version={}".format(m['endpoint'], pluginSetting("apiVersion"))), authcfg=authcfg), m['name'], 'wms') # I've no idea why the following is required even if the crs is specified # in the layer definition layer.setCrs(QgsCoordinateReferenceSystem('EPSG:3857')) layers.append(layer) if os.path.isfile(defaultProjectPath()): backup = defaultProjectPath().replace( '.qgs', '-%s.qgs' % datetime.now().strftime('%Y-%m-%d-%H_%M_%S')) shutil.copy2(defaultProjectPath(), backup) # open default project with open(defaultProjectPath()) as f: content = f.read() doc = QDomDocument() setOk, errorString, errorLine, errorColumn = doc.setContent(content) if not setOk: return False root = doc.documentElement() for layer in layers: is_visible = layer.name() in visibleMaps xml = QgsMapLayer.asLayerDefinition([layer]) r = xml.documentElement() mapLayerElement = r.firstChildElement("maplayers").firstChildElement("maplayer") layerTreeLayerElement = doc.createElement("layer-tree-layer") layerTreeLayerElement.setAttribute("expanded", "1") layerTreeLayerElement.setAttribute("checked", "Qt::Checked" if is_visible else "Qt::Unchecked") layerTreeLayerElement.setAttribute("id", layer.id()) layerTreeLayerElement.setAttribute("name", layer.name()) customPropertiesElement = doc.createElement("customproperties") layerTreeLayerElement.appendChild(customPropertiesElement) legendLayerElement = doc.createElement("legendlayer") legendLayerElement.setAttribute("drawingOrder", "-1") legendLayerElement.setAttribute("open", "true") legendLayerElement.setAttribute("checked", "Qt::Checked" if is_visible else "Qt::Unchecked") legendLayerElement.setAttribute("name", layer.name()) legendLayerElement.setAttribute("showFeatureCount", "0") filegroupElement = doc.createElement("filegroup") filegroupElement.setAttribute("open", "true") filegroupElement.setAttribute("hidden", "false") legendlayerfileElement = doc.createElement("legendlayerfile") legendlayerfileElement.setAttribute("isInOverview", "0") legendlayerfileElement.setAttribute("layerid", layer.id()) legendlayerfileElement.setAttribute("visible", "1" if is_visible else "0") filegroupElement.appendChild(legendlayerfileElement) legendLayerElement.appendChild(filegroupElement) crsElement = doc.createElement("layer_coordinate_transform") crsElement.setAttribute("destAuthId", "EPSG:3857") crsElement.setAttribute("srcAuthId", "EPSG:3857") crsElement.setAttribute("srcDatumTransform", "-1") crsElement.setAttribute("destDatumTransform", "-1") crsElement.setAttribute("layerid", layer.id()) itemElement = doc.createElement("item") text = doc.createTextNode(layer.id()) itemElement.appendChild(text) e = root.firstChildElement("layer-tree-group") e.appendChild(layerTreeLayerElement) e = root.firstChildElement("mapcanvas").firstChildElement("layer_coordinate_transform_info") e.appendChild(crsElement) e = root.firstChildElement("layer-tree-canvas").firstChildElement("custom-order") e.appendChild(itemElement) e = root.firstChildElement("legend") e.appendChild(legendLayerElement) e = root.firstChildElement("projectlayers") e.appendChild(mapLayerElement) with open(defaultProjectPath(), "wb+") as f: f.write(doc.toString(2)) settings = QSettings() settings.setValue('/qgis/newProjectDefault', True) return True
class TestQgsBlendModes(TestCase): def __init__(self, methodName): """Run once on class initialisation.""" unittest.TestCase.__init__(self, methodName) # initialize class MapRegistry, Canvas, MapRenderer, Map and PAL self.mMapRegistry = QgsMapLayerRegistry.instance() # create point layer myShpFile = os.path.join(TEST_DATA_DIR, 'points.shp') self.mPointLayer = QgsVectorLayer(myShpFile, 'Points', 'ogr') self.mMapRegistry.addMapLayer(self.mPointLayer) self.mSimplifyMethod = QgsVectorSimplifyMethod() ; self.mSimplifyMethod.setSimplifyHints(QgsVectorSimplifyMethod.NoSimplification); # create polygon layer myShpFile = os.path.join(TEST_DATA_DIR, 'polys.shp') self.mPolygonLayer = QgsVectorLayer(myShpFile, 'Polygons', 'ogr') self.mPolygonLayer.setSimplifyMethod(self.mSimplifyMethod) self.mMapRegistry.addMapLayer(self.mPolygonLayer) # create line layer myShpFile = os.path.join(TEST_DATA_DIR, 'lines.shp') self.mLineLayer = QgsVectorLayer(myShpFile, 'Lines', 'ogr') self.mLineLayer.setSimplifyMethod(self.mSimplifyMethod) self.mMapRegistry.addMapLayer(self.mLineLayer) # create two raster layers myRasterFile = os.path.join(TEST_DATA_DIR, 'landsat.tif') self.mRasterLayer1 = QgsRasterLayer(myRasterFile, "raster1") self.mRasterLayer2 = QgsRasterLayer(myRasterFile, "raster2") myMultiBandRenderer1 = QgsMultiBandColorRenderer(self.mRasterLayer1.dataProvider(), 2, 3, 4) self.mRasterLayer1.setRenderer(myMultiBandRenderer1) self.mMapRegistry.addMapLayer(self.mRasterLayer1) myMultiBandRenderer2 = QgsMultiBandColorRenderer(self.mRasterLayer2.dataProvider(), 2, 3, 4) self.mRasterLayer2.setRenderer(myMultiBandRenderer2) self.mMapRegistry.addMapLayer(self.mRasterLayer2) # to match blend modes test comparisons background self.mCanvas = CANVAS self.mCanvas.setCanvasColor(QColor(152, 219, 249)) self.mMap = self.mCanvas.map() self.mMap.resize(QSize(400, 400)) self.mapSettings = self.mCanvas.mapSettings() self.mapSettings.setOutputSize(QSize(400, 400)) def testVectorBlending(self): """Test that blend modes work for vector layers.""" #Add vector layers to map myLayers = [] myLayers.append(self.mLineLayer.id()) myLayers.append(self.mPolygonLayer.id()) self.mapSettings.setLayers(myLayers) self.mapSettings.setExtent(self.mPointLayer.extent()) #Set blending modes for both layers self.mLineLayer.setBlendMode(QPainter.CompositionMode_Difference) self.mPolygonLayer.setBlendMode(QPainter.CompositionMode_Difference) checker = QgsRenderChecker() checker.setControlName("expected_vector_blendmodes") checker.setMapSettings(self.mapSettings) myResult = checker.runTest("vector_blendmodes"); myMessage = ('vector blending failed') assert myResult, myMessage #Reset layers self.mLineLayer.setBlendMode(QPainter.CompositionMode_SourceOver) self.mPolygonLayer.setBlendMode(QPainter.CompositionMode_SourceOver) def testVectorFeatureBlending(self): """Test that feature blend modes work for vector layers.""" #Add vector layers to map myLayers = [] myLayers.append(self.mLineLayer.id()) myLayers.append(self.mPolygonLayer.id()) self.mapSettings.setLayers(myLayers) self.mapSettings.setExtent(self.mPointLayer.extent()) #Set feature blending for line layer self.mLineLayer.setFeatureBlendMode(QPainter.CompositionMode_Plus) checker = QgsRenderChecker() checker.setControlName("expected_vector_featureblendmodes") checker.setMapSettings(self.mapSettings) myResult = checker.runTest("vector_featureblendmodes"); myMessage = ('vector feature blending failed') assert myResult, myMessage #Reset layers self.mLineLayer.setFeatureBlendMode(QPainter.CompositionMode_SourceOver) def testVectorLayerTransparency(self): """Test that layer transparency works for vector layers.""" #Add vector layers to map myLayers = [] myLayers.append(self.mLineLayer.id()) myLayers.append(self.mPolygonLayer.id()) self.mapSettings.setLayers(myLayers) self.mapSettings.setExtent(self.mPointLayer.extent()) #Set feature blending for line layer self.mLineLayer.setLayerTransparency( 50 ) checker = QgsRenderChecker() checker.setControlName("expected_vector_layertransparency") checker.setMapSettings(self.mapSettings) myResult = checker.runTest("vector_layertransparency"); myMessage = ('vector layer transparency failed') assert myResult, myMessage def testRasterBlending(self): """Test that blend modes work for raster layers.""" #Add raster layers to map myLayers = [] myLayers.append(self.mRasterLayer1.id()) myLayers.append(self.mRasterLayer2.id()) self.mapSettings.setLayers(myLayers) self.mapSettings.setExtent(self.mRasterLayer1.extent()) #Set blending mode for top layer self.mRasterLayer1.setBlendMode(QPainter.CompositionMode_Plus) checker = QgsRenderChecker() checker.setControlName("expected_raster_blendmodes") checker.setMapSettings(self.mapSettings) myResult = checker.runTest("raster_blendmodes"); myMessage = ('raster blending failed') assert myResult, myMessage
def __add_images(images, description, outdir, msgbar, check, vrt=True, shown=True): if check.isChecked() and vrt: pan = images.pop('pan', None) # take out pan if len(images) > 1: # stack images in a VRT file if there are more than one image left vrtfile = os.path.join(outdir, description + '.vrt') # to sort in r/g/b/nir order here sort(images.keys, key=lambda k: rgbn[k]) _RGBN = {'red': 1, 'green': 2, 'blue': 3, 'nir': 4} images_keys_ordered = sorted(images.keys(), key=lambda k: _RGBN.get(k, 5)) filenames = [images[k] for k in images_keys_ordered ] # filenames list in RGBN order ds = gdal.BuildVRT( vrtfile, filenames, options=gdal.BuildVRTOptions(separate=True, resolution='highest')) for i, bn in enumerate(images_keys_ordered): b = ds.GetRasterBand(i + 1) b.SetDescription(bn) ds.FlushCache() ds = None if pan is None: # nothing to do anymore, add VRT file __add_images({'vrt': vrtfile}, description, outdir, msgbar, check, vrt=False) else: # VERY SLOW TO DO HERE (perhaps as ProcessingProvider?) # nbands = len(images) # if nbands > 2: # may be a setting here for pansharpening choice # pan_ds = gdal.Open(pan) # pansharpened_ds = gdal.CreatePansharpenedVRT(__pszXML(nbands), pan_ds.GetRasterBand(1), # [ds.GetRasterBand(i + 1) for i in range(nbands)]) # pansharpened_filename = os.path.join(outdir, description + '_pansharpened.vrt') # driver = gdal.GetDriverByName('VRT') # driver.CreateCopy(pansharpened_filename, pansharpened_ds, 0) # # add ALL # __add_images({'pansharpened': pansharpened_filename, # 'pan': pan, 'vrt': vrtfile}, description, outdir, msgbar, check, vrt=False, shown=False) # else: # # just add pan and vrt files __add_images({ 'pan': pan, 'vrt': vrtfile }, description, outdir, msgbar, check, vrt=False) else: # do not stack since there are not enough images assert pan is not None # 'pan' should be not 'None' here images.update({'pan': pan}) # restore pan __add_images(images, description, outdir, msgbar, check, vrt=False) else: for k in images.keys(): fn = images[k] name = os.path.basename(fn).split('.')[0] layer = QgsRasterLayer(fn, name) if layer.isValid(): QgsProject.instance().addMapLayer(layer) if not shown: QgsProject.instance().layerTreeRoot().findLayer( layer.id()).setItemVisibilityChecked(shown) msgbar.dismiss()