def layerWarp(rasterNode: QgsLayerTreeGroup, domainLayer: QgsVectorLayer) -> None: """Description: Reprojects a raster if not already in the desired CRS. Make sure to save the shapefile, as it will be deleted otherwise! Input: QgsLayerTreeGroup rasterNode - node that contains the raster image to process QgsVectorLayer domainLayer - layer that contains a polygon specifying the bounds of the raster image to process """ rasterLayer = rasterNode.layer() fileSource = rasterLayer.source() geotiff = gdal.Open(fileSource) prj = geotiff.GetProjection() srs = osr.SpatialReference(wkt=prj) domainCRS = domainLayer.crs().authid() if srs.GetAttrValue("PROJCS|AUTHORITY", 1) is not None: epsgCode = srs.GetAttrValue("PROJCS|AUTHORITY", 1) elif srs.GetAttrValue("AUTHORITY", 1) is not None: epsgCode = srs.GetAttrValue("AUTHORITY", 1) else: epsgCode = str(32621) rasterCRS = "EPSG:" + epsgCode if (rasterCRS != domainCRS): print('warping...', rasterCRS, domainCRS) if not DRY_RUN: parent = rasterNode.parent() rasterName = rasterLayer.name() outSource = fileSource[0:-4] + "_" + domainCRS[5:] + ".tif" #processing.algorithmHelp("gdal:warpreproject") print(fileSource, outSource) processing.run( "gdal:warpreproject", { 'DATA_TYPE': 5, #Float32 'INPUT': rasterName, 'MULTITHREADING': True, 'NODATA': 0.0, 'OPTIONS': '', 'OUTPUT': outSource, 'RESAMPLING': 1, #Bilinear 'SOURCE_CRS': rasterCRS, 'TARGET_CRS': domainCRS, 'TARGET_EXTENT': None, 'TARGET_EXTENT_CRS': None, 'TARGET_RESOLUTION': None }) print('hello') QgsProject.instance().removeMapLayer(rasterLayer.id()) geotiff = None shutil.copy2(outSource, fileSource) os.remove(outSource) rasterLayer = QgsRasterLayer(fileSource, rasterName) QgsProject.instance().addMapLayer(rasterLayer, False) rasterNode = parent.insertLayer(0, rasterLayer) return rasterNode return rasterNode
def firstGroupWithoutCustomProperty(group: QgsLayerTreeGroup, _property: str) -> QgsLayerTreeGroup: """ Taken from QgsLayerTreeUtils::firstGroupWithoutCustomProperty :param group: :param _property: :return: """ # if the group is embedded go to the first non-embedded group, at worst the top level item while group.customProperty(_property): if not group.parent(): break if QgsLayerTree.isGroup(group.parent()): group = group.parent() else: dbg_info(group) assert False return group