def displaced_people_style(layer): """Simple style to display a displaced count with a binary style. :param layer: The layer to style. :type layer: QgsRasterLayer """ color_ramp = QgsColorRampShader() color_ramp.setColorRampType(QgsColorRampShader.INTERPOLATED) color_ramp.setColorRampItemList(legend_raster_displaced) shader = QgsRasterShader() shader.setRasterShaderFunction(color_ramp) renderer = QgsSingleBandPseudoColorRenderer(layer.dataProvider(), 1, shader) layer.setRenderer(renderer)
def test_setRenderer(self): myPath = os.path.join(unitTestDataPath('raster'), 'band1_float32_noct_epsg4326.tif') myFileInfo = QFileInfo(myPath) myBaseName = myFileInfo.baseName() layer = QgsRasterLayer(myPath, myBaseName) self.rendererChanged = False QObject.connect(layer, SIGNAL("rendererChanged()"), self.onRendererChanged) rShader = QgsRasterShader() r = QgsSingleBandPseudoColorRenderer(layer.dataProvider(), 1, rShader) layer.setRenderer(r) assert self.rendererChanged assert layer.renderer() == r
def testSingleBandPseudoColorRenderer_Discrete(self): # get min and max of the band to renderer bandNo = 3 stats = self.raster_layer.dataProvider().bandStatistics( bandNo, QgsRasterBandStats.Min | QgsRasterBandStats.Max) minValue = stats.minimumValue maxValue = stats.maximumValue # create shader for the renderer shader = QgsRasterShader(minValue, maxValue) colorRampShaderFcn = QgsColorRampShader(minValue, maxValue) colorRampShaderFcn.setColorRampType(QgsColorRampShader.Discrete) colorRampShaderFcn.setClassificationMode(QgsColorRampShader.Continuous) colorRampShaderFcn.setClip(True) items = [] for index in range(10): items.append( QgsColorRampShader.ColorRampItem( index, QColor('#{0:02d}{0:02d}{0:02d}'.format(index)), "{}".format(index))) colorRampShaderFcn.setColorRampItemList(items) shader.setRasterShaderFunction(colorRampShaderFcn) # create instance to test rasterRenderer = QgsSingleBandPseudoColorRenderer( self.raster_layer.dataProvider(), bandNo, shader) self.raster_layer.setRenderer(rasterRenderer) # do test dom, root = self.rendererToSld(self.raster_layer.renderer()) self.assertNoOpacity(root) self.assertChannelBand(root, 'sld:GrayChannel', '{}'.format(bandNo)) # check ColorMapEntry classes colorMap = root.elementsByTagName('sld:ColorMap') colorMap = colorMap.item(0).toElement() self.assertFalse(colorMap.isNull()) self.assertEqual(colorMap.attribute('type'), 'intervals') colorMapEntries = colorMap.elementsByTagName('sld:ColorMapEntry') self.assertEqual(colorMapEntries.count(), 10) for index in range(colorMapEntries.count()): colorMapEntry = colorMapEntries.at(index).toElement() self.assertEqual(colorMapEntry.attribute('quantity'), '{}'.format(index)) self.assertEqual(colorMapEntry.attribute('label'), '{}'.format(index)) self.assertEqual(colorMapEntry.attribute('opacity'), '') self.assertEqual(colorMapEntry.attribute('color'), '#{0:02d}{0:02d}{0:02d}'.format(index))
def setRasterStyle(self, raster_layer): shaderType = QgsColorRampShader() shaderType.setColorRampType(QgsColorRampShader.Discrete) item_list = [] item_list.append( QgsColorRampShader.ColorRampItem(1, QColor(0, 0, 0, 0), lbl="Sem visada")) item_list.append( QgsColorRampShader.ColorRampItem(1, QColor(0, 255, 0), lbl="Visível")) shaderType.setColorRampItemList(item_list) shader = QgsRasterShader() shader.setRasterShaderFunction(shaderType) renderer = QgsSingleBandPseudoColorRenderer( raster_layer.dataProvider(), 1, shader) raster_layer.setRenderer(renderer)
def loadLabelImage(imagepath, labeldescriptor=None): """ Load a labeled single band raster in the canvas Keyword arguments: imagepath -- the path to the image labeldescriptor -- a dictionnary for label (int) to tuple (QColor, QString) conversion """ if imagepath is None: return name = os.path.splitext(os.path.basename(imagepath))[0] qgslayer = QgsRasterLayer(imagepath, name) if not qgslayer.isValid(): QtGui.QMessageBox.critical( None, u"Erreur", u"Impossible de charger la couche %s" % unicode(imagepath)) QgsMapLayerRegistry.instance().addMapLayer(qgslayer) qgslayer.setDrawingStyle('SingleBandPseudoColor') colorlist = [] max_label = 0 for label in sorted(labeldescriptor.keys()): color = labeldescriptor[label][0] labeltxt = labeldescriptor[label][1] colorlist.append( QgsColorRampShader.ColorRampItem(label, color, labeltxt)) if labeltxt > max_label: max_label = labeltxt s = QgsRasterShader() c = QgsColorRampShader() c.setColorRampType(QgsColorRampShader.INTERPOLATED) c.setColorRampItemList(colorlist) s.setRasterShaderFunction(c) ps = QgsSingleBandPseudoColorRenderer(qgslayer.dataProvider(), 1, s) qgslayer.setRenderer(ps) QGisLayers.iface.legendInterface().refreshLayerSymbology(qgslayer) if hasattr(qgslayer, "setCacheImage"): qgslayer.setCacheImage(None) qgslayer.triggerRepaint()
def save_pointwise_deficit_as_raster(self, iface, points_grid, end_date_index, save_file_path, layer_name): cols = len(points_grid[0]) rows = len(points_grid) originX = points_grid[0][0].qgsPoint.x() originY = points_grid[0][0].qgsPoint.y() #top-left driver = gdal.GetDriverByName('GTiff') outRaster = driver.Create(save_file_path, cols, rows, 1, gdal.GDT_Byte) outRaster.SetGeoTransform((originX, STEP, 0, originY, 0, STEP)) outband = outRaster.GetRasterBand(1) deficit_values_array = np.array([[ p.budget.PET_minus_AET_till_date[end_date_index] if not p.is_no_evaluation_point else -9999 for p in p_row ] for p_row in points_grid]) max_deficit = np.max(deficit_values_array) outband.WriteArray(deficit_values_array) outRasterSRS = osr.SpatialReference() outRasterSRS.ImportFromEPSG(32643) outRaster.SetProjection(outRasterSRS.ExportToWkt()) outband.FlushCache() layer = iface.addRasterLayer( save_file_path, layer_name + '_max_deficit_' + str(int(max_deficit))) layer.dataProvider().setNoDataValue(1, -9999) fcn = QgsColorRampShader() fcn.setColorRampType(QgsColorRampShader.INTERPOLATED) lst = [ QgsColorRampShader.ColorRampItem(0, QColor(240, 240, 240)), QgsColorRampShader.ColorRampItem(max_deficit, QColor(255, 0, 0)) ] fcn.setColorRampItemList(lst) shader = QgsRasterShader() shader.setRasterShaderFunction(fcn) renderer = QgsSingleBandPseudoColorRenderer(layer.dataProvider(), 1, shader) layer.setRenderer(renderer) layer.triggerRepaint()
def setRasterStyle(self, raster_layer, layer_values): shaderType = QgsColorRampShader() shaderType.setColorRampType(QgsColorRampShader.Discrete) item_list = [] j = 1 for i in list(layer_values.getFeatures()): color_temp = QColor(0, 0, 0) color_temp.setHsvF(j / layer_values.featureCount(), 1, 1) item_list.append( QgsColorRampShader.ColorRampItem(i[3], color_temp, lbl=str(i[0]))) j += 1 shaderType.setColorRampItemList(item_list) shader = QgsRasterShader() shader.setRasterShaderFunction(shaderType) renderer = QgsSingleBandPseudoColorRenderer( raster_layer.dataProvider(), 1, shader) raster_layer.setRenderer(renderer)
def style_sdg_ld(outfile): # Significance layer layer = iface.addRasterLayer(outfile, QtGui.QApplication.translate('LDMPPlugin', 'Degradation (SDG 15.3 - without soil carbon)')) if not layer.isValid(): log('Failed to add layer') return None fcn = QgsColorRampShader() fcn.setColorRampType(QgsColorRampShader.EXACT) lst = [QgsColorRampShader.ColorRampItem(-1, QtGui.QColor(153, 51, 4), QtGui.QApplication.translate('LDMPPlugin', 'Degradation')), QgsColorRampShader.ColorRampItem(0, QtGui.QColor(246, 246, 234), QtGui.QApplication.translate('LDMPPlugin', 'Stable')), QgsColorRampShader.ColorRampItem(1, QtGui.QColor(0, 140, 121), QtGui.QApplication.translate('LDMPPlugin', 'Improvement')), QgsColorRampShader.ColorRampItem(2, QtGui.QColor(58, 77, 214), QtGui.QApplication.translate('LDMPPlugin', 'Water')), QgsColorRampShader.ColorRampItem(3, QtGui.QColor(192, 105, 223), QtGui.QApplication.translate('LDMPPlugin', 'Urban land cover'))] fcn.setColorRampItemList(lst) shader = QgsRasterShader() shader.setRasterShaderFunction(fcn) pseudoRenderer = QgsSingleBandPseudoColorRenderer(layer.dataProvider(), 1, shader) layer.setRenderer(pseudoRenderer) layer.triggerRepaint() iface.legendInterface().refreshLayerSymbology(layer)
def runFilter(iface, dlg, conf, dir_dest, rasterSeuilName, rasterFilterName): # Passage des parametres pour le filtrage layer = filterRaster(dlg, conf, dir_dest, rasterSeuilName, rasterFilterName) if layer != None: # Informations de style canvas = iface.mapCanvas() QgsProject.instance().addMapLayer(layer) fcn = QgsColorRampShader() fcn.setColorRampType(QgsColorRampShader.Type.Exact) lst = [ QgsColorRampShader.ColorRampItem(1, QColor(QColor(255, 177, 67))) ] fcn.setColorRampItemList(lst) shader = QgsRasterShader() shader.setRasterShaderFunction(fcn) renderer = QgsSingleBandPseudoColorRenderer(layer.dataProvider(), 1, shader) if renderer: layer.setRenderer(renderer) if layer.renderer(): layer.renderer().setOpacity(0.5) layer.triggerRepaint() setLayerVisible(layer, True) canvas.refresh() messInfo( dlg, "---> Lancez 'Filtrer' (fonction du radius choisi) pour appliquer un nouveau filtrage ou 'Vectoriser' pour poursuivre le traitement. <---" ) messInfo(dlg, "") QMessageBox.information(None, "Traitement de filtrage", " Filtrage terminé. ", QMessageBox.Ok, QMessageBox.NoButton) return
def style_prod_state_emerg(outfile): # Significance layer layer = iface.addRasterLayer( outfile, QtGui.QApplication.translate('LDMPPlugin', 'Productivity state (emerging)')) if not layer.isValid(): return None fcn = QgsColorRampShader() fcn.setColorRampType(QgsColorRampShader.EXACT) lst = [ QgsColorRampShader.ColorRampItem( -2, QtGui.QColor(0, 0, 0), QtGui.QApplication.translate('LDMPPlugin', 'No data')), QgsColorRampShader.ColorRampItem( -1, QtGui.QColor(153, 51, 4), QtGui.QApplication.translate('LDMPPlugin', 'Significant decrease')), QgsColorRampShader.ColorRampItem( 0, QtGui.QColor(246, 246, 234), QtGui.QApplication.translate('LDMPPlugin', 'No significant change')), QgsColorRampShader.ColorRampItem( 1, QtGui.QColor(0, 140, 121), QtGui.QApplication.translate('LDMPPlugin', 'Significant increase')), QgsColorRampShader.ColorRampItem( 2, QtGui.QColor(58, 77, 214), QtGui.QApplication.translate('LDMPPlugin', 'Water')), QgsColorRampShader.ColorRampItem( 3, QtGui.QColor(192, 105, 223), QtGui.QApplication.translate('LDMPPlugin', 'Urban land cover')) ] fcn.setColorRampItemList(lst) shader = QgsRasterShader() shader.setRasterShaderFunction(fcn) pseudoRenderer = QgsSingleBandPseudoColorRenderer(layer.dataProvider(), 1, shader) layer.setRenderer(pseudoRenderer) layer.triggerRepaint() iface.legendInterface().refreshLayerSymbology(layer)
def style_land_cover_land_deg(outfile): layer_deg = iface.addRasterLayer(outfile, 'Land cover (degradation)') fcn = QgsColorRampShader() fcn.setColorRampType(QgsColorRampShader.EXACT) #TODO The GPG doesn't seem to allow for possibility of improvement...? lst = [ QgsColorRampShader.ColorRampItem(-1, QtGui.QColor(153, 51, 4), 'Degradation'), QgsColorRampShader.ColorRampItem(0, QtGui.QColor(246, 246, 234), 'Stable'), QgsColorRampShader.ColorRampItem(1, QtGui.QColor(0, 140, 121), 'Improvement') ] fcn.setColorRampItemList(lst) shader = QgsRasterShader() shader.setRasterShaderFunction(fcn) pseudoRenderer = QgsSingleBandPseudoColorRenderer(layer_deg.dataProvider(), 1, shader) layer_deg.setRenderer(pseudoRenderer) layer_deg.triggerRepaint() iface.legendInterface().refreshLayerSymbology(layer_deg)
def set_color_heatmap_symbology(layer: QgsRasterLayer, color: QtGui.QColor): provider = layer.dataProvider() renderer = layer.renderer() color_ramp_items = __get_color_ramp_items(renderer, provider, color) color_ramp = QgsColorRampShader() color_ramp.setColorRampItemList(color_ramp_items) color_ramp.setColorRampType(QgsColorRampShader.Interpolated) raster_shader = QgsRasterShader() raster_shader.setRasterShaderFunction(color_ramp) renderer = QgsSingleBandPseudoColorRenderer( layer.dataProvider(), layer.type(), raster_shader ) layer.setBlendMode(QPainter.CompositionMode_Multiply) layer.setRenderer(renderer)
def apply_symbology(rlayer, symbology, transparent=None): """ Apply classification symbology to raster layer """ # See: QgsRasterRenderer* QgsSingleBandPseudoColorRendererWidget::renderer() # https://github.com/qgis/QGIS/blob/master/src/gui/raster/qgssinglebandpseudocolorrendererwidget.cpp # Get raster shader raster_shader = QgsRasterShader() # Color ramp shader color_ramp_shader = QgsColorRampShader() # Loop over Fmask values and add to color item list color_ramp_item_list = [] for name, value, color in symbology: # Color ramp item - color, label, value color_ramp_item = QgsColorRampShader.ColorRampItem( value, QColor(color[0], color[1], color[2], color[3]), name) color_ramp_item_list.append(color_ramp_item) # After getting list of color ramp items color_ramp_shader.setColorRampItemList(color_ramp_item_list) # Exact color ramp color_ramp_shader.setColorRampType('EXACT') # Add color ramp shader to raster shader raster_shader.setRasterShaderFunction(color_ramp_shader) # Create color renderer for raster layer renderer = QgsSingleBandPseudoColorRenderer(rlayer.dataProvider(), 1, raster_shader) # Set renderer for raster layer rlayer.setRenderer(renderer) # Set NoData transparency to layer qgis (temporal) if transparent is not None: if not isinstance(transparent, list): transparent = [transparent] nodata = [QgsRasterRange(t, t) for t in transparent] if nodata: rlayer.dataProvider().setUserNoDataValue(1, nodata) # Repaint if hasattr(rlayer, 'setCacheImage'): rlayer.setCacheImage(None) rlayer.triggerRepaint()
def setStyle(self, layer): provider = layer.dataProvider() extent = layer.extent() stats = provider.bandStatistics(1, QgsRasterBandStats.All, extent, 0) if stats.minimumValue < 0: min = 0 else: min = stats.minimumValue max = stats.maximumValue range = max - min add = range // 2 interval = min + add colDic = {'red': '#ff0000', 'yellow': '#ffff00', 'blue': '#0000ff'} valueList = [min, interval, max] lst = [QgsColorRampShader.ColorRampItem(valueList[0], QColor(colDic['red'])), QgsColorRampShader.ColorRampItem(valueList[1], QColor(colDic['yellow'])), QgsColorRampShader.ColorRampItem(valueList[2], QColor(colDic['blue']))] myRasterShader = QgsRasterShader() myColorRamp = QgsColorRampShader() myColorRamp.setColorRampItemList(lst) myColorRamp.setColorRampType(QgsColorRampShader.INTERPOLATED) # TODO: add classificationMode=Continuos # myColorRamp.setClassificationMode(QgsColorRampShader.ClassificationMode(1)) # AttributeError: type object 'QgsColorRampShader' has no attribute 'setClassificationMode' myRasterShader.setRasterShaderFunction(myColorRamp) myPseudoRenderer = QgsSingleBandPseudoColorRenderer(layer.dataProvider(), layer.type(), myRasterShader) layer.setRenderer(myPseudoRenderer) layer.triggerRepaint()
def getRenderer(self, layer_data_provider, color_map): """ Get QgsSingleBandPseudoColorRenderer for NDVI display. :param layer_data_provider: layer data provider :type: QgsDataProvider :param color_map: color list :type: [ColorRampItem...] :return: QgsSingleBandPseudoColorRenderer """ self.LOGGER.debug("getting renderer") raster_shader = QgsRasterShader() color_ramp_shader = QgsColorRampShader() color_ramp_shader.setColorRampType(QgsColorRampShader.DISCRETE) color_ramp_shader.setColorRampItemList(color_map) raster_shader.setRasterShaderFunction(color_ramp_shader) return QgsSingleBandPseudoColorRenderer(layer_data_provider, 1, raster_shader)
def colormap(self): self.project.read('C:/Users/william/Documents/Qgis/example.qgs') #project = QgsProject.instance() path_to_tif = os.path.join(QgsProject.instance().homePath(), "qgis_sample_data", "raster", "SR_50M_alaska_nad.TIF") self.rlayer = QgsRasterLayer(path_to_tif) fcn = QgsColorRampShader() fcn.setColorRampType(QgsColorRampShader.Interpolated) lst = [ QgsColorRampShader.ColorRampItem(0, QColor(0, 25, 25)), QgsColorRampShader.ColorRampItem(255, QColor(255, 255, 0)) ] fcn.setColorRampItemList(lst) shader = QgsRasterShader() shader.setRasterShaderFunction(fcn) renderer = QgsSingleBandPseudoColorRenderer(self.rlayer.dataProvider(), 1, shader) self.rlayer.setRenderer(renderer) QgsProject.instance().addMapLayer(self.rlayer) QgsProject.instance().layerTreeRoot() QMessageBox.information(None, 'Example:', 'Colormap is loaded!')
def render(self): t_0 = self.dlg.threshold_0_slider.value() / (10.0**self.precision) t_1 = self.dlg.threshold_1_slider.value() / (10.0**self.precision) t_2 = self.dlg.threshold_2_slider.value() / (10.0**self.precision) base = self.dlg.base_slider.value() / (10.0**self.precision) lst = [ QgsColorRampShader.ColorRampItem(t_0 - base, self.CLEAR), QgsColorRampShader.ColorRampItem(t_0, self.t_0_COLOR), QgsColorRampShader.ColorRampItem(t_1, self.t_1_COLOR), QgsColorRampShader.ColorRampItem(t_2, self.t_2_COLOR), ] self.fcn = QgsColorRampShader() self.fcn.setColorRampType(QgsColorRampShader.Interpolated) self.fcn.setColorRampItemList(lst) self.shader = QgsRasterShader() self.shader.setRasterShaderFunction(self.fcn) self.renderer = QgsSingleBandPseudoColorRenderer( self.layer.dataProvider(), 1, self.shader) self.layer.setRenderer(self.renderer) self.layer.triggerRepaint()
def categoraize_raster_layer(self, layer=None, layer_name=None): """ """ if not layer: layer = self.get_layer_by_name(layer_name) if not layer: return fnc = QgsColorRampShader() fnc.setColorRampType(QgsColorRampShader.Discrete) fnc.setColorRampItemList([ QgsColorRampShader.ColorRampItem(0, QColor(0, 0, 0, 0), '-'), QgsColorRampShader.ColorRampItem(1, QColor(187, 187, 187), '1 - Cloud'), QgsColorRampShader.ColorRampItem(2, QColor(255, 255, 26), '2 - Subsurface'), QgsColorRampShader.ColorRampItem(3, QColor(247, 126, 60), '3 - Surface'), QgsColorRampShader.ColorRampItem(4, QColor(0, 0, 0), '4 - NoData') ]) shader = QgsRasterShader() shader.setRasterShaderFunction(fnc) renderer = QgsSingleBandPseudoColorRenderer(layer.dataProvider(), 1, shader) layer.setRenderer(renderer)
def style_land_cover_lc_target(outfile): layer_lc_target = iface.addRasterLayer( outfile, QtGui.QApplication.translate('LDMPPlugin', 'Land cover (target)')) if not layer_lc_target.isValid(): log('Failed to add layer') return None fcn = QgsColorRampShader() fcn.setColorRampType(QgsColorRampShader.EXACT) lst = [ QgsColorRampShader.ColorRampItem( 1, QtGui.QColor('#a50f15'), QtGui.QApplication.translate('LDMPPlugin', 'Cropland')), QgsColorRampShader.ColorRampItem( 2, QtGui.QColor('#006d2c'), QtGui.QApplication.translate('LDMPPlugin', 'Forest land')), QgsColorRampShader.ColorRampItem( 3, QtGui.QColor('#d8d800'), QtGui.QApplication.translate('LDMPPlugin', 'Grassland')), QgsColorRampShader.ColorRampItem( 4, QtGui.QColor('#08519c'), QtGui.QApplication.translate('LDMPPlugin', 'Wetlands')), QgsColorRampShader.ColorRampItem( 5, QtGui.QColor('#54278f'), QtGui.QApplication.translate('LDMPPlugin', 'Settlements')), QgsColorRampShader.ColorRampItem( 6, QtGui.QColor('#252525'), QtGui.QApplication.translate('LDMPPlugin', 'Other land')) ] fcn.setColorRampItemList(lst) shader = QgsRasterShader() shader.setRasterShaderFunction(fcn) pseudoRenderer = QgsSingleBandPseudoColorRenderer( layer_lc_target.dataProvider(), 1, shader) layer_lc_target.setRenderer(pseudoRenderer) layer_lc_target.triggerRepaint() iface.legendInterface().refreshLayerSymbology(layer_lc_target)
def mmi_ramp_roman(raster_layer): """Generate an mmi ramp using range of 1-10 on roman. A standarised range is used so that two shakemaps of different intensities can be properly compared visually with colours stretched accross the same range. The colours used are the 'standard' colours commonly shown for the mercalli scale e.g. on wikipedia and other sources. :param raster_layer: A raster layer that will have an mmi style applied. :type raster_layer: QgsRasterLayer .. versionadded:: 4.0 """ items = [] sorted_mmi_scale = sorted( earthquake_mmi_scale['classes'], key=itemgetter('value')) for class_max in sorted_mmi_scale: colour = class_max['color'] label = '%s' % class_max['key'] ramp_item = QgsColorRampShader.ColorRampItem( class_max['value'], colour, label) items.append(ramp_item) raster_shader = QgsRasterShader() ramp_shader = QgsColorRampShader() ramp_shader.setColorRampType(QgsColorRampShader.INTERPOLATED) ramp_shader.setColorRampItemList(items) raster_shader.setRasterShaderFunction(ramp_shader) band = 1 renderer = QgsSingleBandPseudoColorRenderer( raster_layer.dataProvider(), band, raster_shader) raster_layer.setRenderer(renderer)
def style_prod_state_init(outfile): # Significance layer layer = iface.addRasterLayer(outfile, 'Productivity state (initial)') fcn = QgsColorRampShader() fcn.setColorRampType(QgsColorRampShader.EXACT) lst = [ QgsColorRampShader.ColorRampItem(-2, QtGui.QColor(0, 0, 0), 'No data'), QgsColorRampShader.ColorRampItem(-1, QtGui.QColor(153, 51, 4), 'Potentially degraded'), QgsColorRampShader.ColorRampItem(0, QtGui.QColor(246, 246, 234), 'Stable'), QgsColorRampShader.ColorRampItem(2, QtGui.QColor(58, 77, 214), 'Water'), QgsColorRampShader.ColorRampItem(3, QtGui.QColor(192, 105, 223), 'Urban land cover') ] fcn.setColorRampItemList(lst) shader = QgsRasterShader() shader.setRasterShaderFunction(fcn) pseudoRenderer = QgsSingleBandPseudoColorRenderer(layer.dataProvider(), 1, shader) layer.setRenderer(pseudoRenderer) layer.triggerRepaint() iface.legendInterface().refreshLayerSymbology(layer)
def style_prod_perf(outfile): layer_perf = iface.addRasterLayer( outfile, QtGui.QApplication.translate('LDMPPlugin', 'Productivity performance (degradation)')) if not layer_perf.isValid(): log('Failed to add layer') return None fcn = QgsColorRampShader() fcn.setColorRampType(QgsColorRampShader.EXACT) #TODO The GPG doesn't seem to allow for possibility of improvement...? lst = [ QgsColorRampShader.ColorRampItem( -1, QtGui.QColor(153, 51, 4), QtGui.QApplication.translate('LDMPPlugin', 'Degradation')), QgsColorRampShader.ColorRampItem( 0, QtGui.QColor(246, 246, 234), QtGui.QApplication.translate('LDMPPlugin', 'Stable')), QgsColorRampShader.ColorRampItem( 1, QtGui.QColor(0, 140, 121), QtGui.QApplication.translate('LDMPPlugin', 'Improvement')), QgsColorRampShader.ColorRampItem( 2, QtGui.QColor(58, 77, 214), QtGui.QApplication.translate('LDMPPlugin', 'Water')), QgsColorRampShader.ColorRampItem( 3, QtGui.QColor(192, 105, 223), QtGui.QApplication.translate('LDMPPlugin', 'Urban land cover')) ] fcn.setColorRampItemList(lst) shader = QgsRasterShader() shader.setRasterShaderFunction(fcn) pseudoRenderer = QgsSingleBandPseudoColorRenderer( layer_perf.dataProvider(), 1, shader) layer_perf.setRenderer(pseudoRenderer) layer_perf.triggerRepaint() iface.legendInterface().refreshLayerSymbology(layer_perf)
def set_raster_style(raster_layer, style): """Set QGIS raster style based on InaSAFE style dictionary for QGIS >= 2.0. This function will set both the colour map and the transparency for the passed in layer. :param raster_layer: A QGIS raster layer that will be styled. :type raster_layer: QgsVectorLayer :param style: List of the form as in the example below. :type style: list Example:: style_classes = [dict(colour='#38A800', quantity=2, transparency=0), dict(colour='#38A800', quantity=5, transparency=50), dict(colour='#79C900', quantity=10, transparency=50), dict(colour='#CEED00', quantity=20, transparency=50), dict(colour='#FFCC00', quantity=50, transparency=34), dict(colour='#FF6600', quantity=100, transparency=77), dict(colour='#FF0000', quantity=200, transparency=24), dict(colour='#7A0000', quantity=300, transparency=22)] :returns: A two tuple containing a range list and a transparency list. :rtype: (list, list) """ # Note imports here to prevent importing on unsupported QGIS versions # pylint: disable=E0611 # pylint: disable=W0621 # pylint: disable=W0404 # noinspection PyUnresolvedReferences from qgis.core import (QgsRasterShader, QgsColorRampShader, QgsSingleBandPseudoColorRenderer, QgsRasterTransparency) # pylint: enable=E0611 # pylint: enable=W0621 # pylint: enable=W0404 ramp_item_list = [] transparency_list = [] LOGGER.debug(style) for style_class in style: LOGGER.debug('Evaluating class:\n%s\n' % style_class) if 'quantity' not in style_class: LOGGER.exception('Class has no quantity attribute') continue class_max = style_class['max'] if math.isnan(class_max): LOGGER.debug('Skipping class - max is nan.') continue class_min = style_class['min'] if math.isnan(class_min): LOGGER.debug('Skipping class - min is nan.') continue colour = QtGui.QColor(style_class['colour']) label = '' if 'label' in style_class: label = style_class['label'] # noinspection PyCallingNonCallable ramp_item = QgsColorRampShader.ColorRampItem(class_max, colour, label) ramp_item_list.append(ramp_item) # Create opacity entries for this range transparency_percent = 0 if 'transparency' in style_class: transparency_percent = int(style_class['transparency']) if transparency_percent > 0: # Check if range extrema are integers so we know if we can # use them to calculate a value range # noinspection PyCallingNonCallable pixel = QgsRasterTransparency.TransparentSingleValuePixel() pixel.min = class_min # We want it just a little bit smaller than max # so that ranges are discrete pixel.max = class_max # noinspection PyPep8Naming pixel.percentTransparent = transparency_percent transparency_list.append(pixel) band = 1 # gdal counts bands from base 1 LOGGER.debug('Setting colour ramp list') raster_shader = QgsRasterShader() color_ramp_shader = QgsColorRampShader() color_ramp_shader.setColorRampType(QgsColorRampShader.INTERPOLATED) color_ramp_shader.setColorRampItemList(ramp_item_list) LOGGER.debug('Setting shader function') raster_shader.setRasterShaderFunction(color_ramp_shader) LOGGER.debug('Setting up renderer') renderer = QgsSingleBandPseudoColorRenderer(raster_layer.dataProvider(), band, raster_shader) LOGGER.debug('Assigning renderer to raster layer') raster_layer.setRenderer(renderer) LOGGER.debug('Setting raster transparency list') renderer = raster_layer.renderer() transparency = QgsRasterTransparency() transparency.setTransparentSingleValuePixelList(transparency_list) renderer.setRasterTransparency(transparency) # For interest you can also view the list like this: # pix = t.transparentSingleValuePixelList() # for px in pix: # print 'Min: %s Max %s Percent %s' % ( # px.min, px.max, px.percentTransparent) LOGGER.debug('Saving style as default') raster_layer.saveDefaultStyle() LOGGER.debug('Setting raster style done!') return ramp_item_list, transparency_list
def add_layer(f, band_number, band_info): try: style = styles[band_info['name']] except KeyError: QtWidgets.QMessageBox.information(None, tr("Information"), tr(u"Trends.Earth does not have a style assigned for {}. To use this layer, manually add it to your map.".format(f))) log(u'No style found for {}'.format(band_info['name'] )) return False title = get_band_title(band_info) l = iface.addRasterLayer(f, title) if not l.isValid(): log('Failed to add layer') return False if style['ramp']['type'] == 'categorical': r = [] for item in style['ramp']['items']: r.append(QgsColorRampShader.ColorRampItem(item['value'], QtWidgets.QColor(item['color']), tr_style_text(item['label']))) elif style['ramp']['type'] == 'categorical with dynamic ramp': r = [] for item in style['ramp']['items']: r.append(QgsColorRampShader.ColorRampItem(item['value'], QtWidgets.QColor(item['color']), tr_style_text(item['label']))) # Now add in the continuous ramp with min/max values and labels # determined from the band info min/max r.append(QgsColorRampShader.ColorRampItem(band_info['metadata']['ramp_min'], QtWidgets.QColor(style['ramp']['ramp min']['color']), tr_style_text(style['ramp']['ramp min']['label'], band_info))) r.append(QgsColorRampShader.ColorRampItem(band_info['metadata']['ramp_max'], QtWidgets.QColor(style['ramp']['ramp max']['color']), tr_style_text(style['ramp']['ramp max']['label'], band_info))) elif style['ramp']['type'] == 'zero-centered stretch': # Set a colormap centred on zero, going to the max of the min and max # extreme value significant to three figures. cutoff = get_cutoff(f, band_number, band_info, [style['ramp']['percent stretch'], 100 - style['ramp']['percent stretch']]) log('Cutoff for {} percent stretch: {}'.format(style['ramp']['percent stretch'], cutoff)) r = [] r.append(QgsColorRampShader.ColorRampItem(-cutoff, QtWidgets.QColor(style['ramp']['min']['color']), '{}'.format(-cutoff))) r.append(QgsColorRampShader.ColorRampItem(0, QtWidgets.QColor(style['ramp']['zero']['color']), '0')) r.append(QgsColorRampShader.ColorRampItem(cutoff, QtWidgets.QColor(style['ramp']['max']['color']), '{}'.format(cutoff))) r.append(QgsColorRampShader.ColorRampItem(style['ramp']['no data']['value'], QtWidgets.QColor(style['ramp']['no data']['color']), tr_style_text(style['ramp']['no data']['label']))) elif style['ramp']['type'] == 'min zero stretch': # Set a colormap from zero to percent stretch significant to # three figures. cutoff = get_cutoff(f, band_number, band_info, [100 - style['ramp']['percent stretch']]) log('Cutoff for min zero max {} percent stretch: {}'.format(100 - style['ramp']['percent stretch'], cutoff)) r = [] r.append(QgsColorRampShader.ColorRampItem(0, QtWidgets.QColor(style['ramp']['zero']['color']), '0')) if 'mid' in style['ramp']: r.append(QgsColorRampShader.ColorRampItem(cutoff/2, QtWidgets.QColor(style['ramp']['mid']['color']), str(cutoff/2))) r.append(QgsColorRampShader.ColorRampItem(cutoff, QtWidgets.QColor(style['ramp']['max']['color']), '{}'.format(cutoff))) r.append(QgsColorRampShader.ColorRampItem(style['ramp']['no data']['value'], QtWidgets.QColor(style['ramp']['no data']['color']), tr_style_text(style['ramp']['no data']['label']))) else: log('Failed to load Trends.Earth style. Adding layer using QGIS defaults.') QtWidgets.QMessageBox.critical(None, tr("Error"), tr("Failed to load Trends.Earth style. Adding layer using QGIS defaults.")) return False fcn = QgsColorRampShader() if style['ramp']['shader'] == 'exact': fcn.setColorRampType("EXACT") elif style['ramp']['shader'] == 'discrete': fcn.setColorRampType("DISCRETE") elif style['ramp']['shader'] == 'interpolated': fcn.setColorRampType("INTERPOLATED") else: raise TypeError("Unrecognized color ramp type: {}".format(style['ramp']['shader'])) # Make sure the items in the color ramp are sorted by value (weird display # errors will otherwise result) r = sorted(r, key=attrgetter('value')) fcn.setColorRampItemList(r) shader = QgsRasterShader() shader.setRasterShaderFunction(fcn) pseudoRenderer = QgsSingleBandPseudoColorRenderer(l.dataProvider(), band_number, shader) l.setRenderer(pseudoRenderer) l.triggerRepaint() iface.legendInterface().refreshLayerSymbology(l) return True
def styleRaster(filename): # Create outfile name outfile = "".join(filename.strip().split('.raw')) # Open layer from filename rasterfile = filename.strip().split('/')[-1] rasterlayer = rasterfile.split('.')[0] rlayer = QgsRasterLayer(filename, rasterlayer, 'gdal') # Check if layer is valid if rlayer.isValid() is True: # Get layer data provider provider = rlayer.dataProvider() # Calculate histrogram provider.initHistogram(QgsRasterHistogram(), 1, 100) hist = provider.histogram(1) # Get histograms stats nbins = hist.binCount minv = hist.minimum maxv = hist.maximum # Create histogram array, bin array, and histogram index hista = np.array(hist.histogramVector) bins = np.arange(minv, maxv, (maxv - minv) / nbins) index = np.where(hista > 5) # Get bottom and top color values from bin values bottomcolor = bins[index[0][0]] topcolor = bins[index[0][-1]] # Calculate range value between the bottom and top color values if bottomcolor < 0: vrange = topcolor + bottomcolor else: vrange = topcolor - bottomcolor # Calculate values for bottom middle, and top middle color values if rasterlayer == 'maxele': bottommiddle = vrange * 0.3333 topmiddle = vrange * 0.6667 else: bottommiddle = vrange * 0.375 topmiddle = vrange * 0.75 # Create list of color values valueList = [bottomcolor, bottommiddle, topmiddle, topcolor] # Create color dictionary if rasterlayer == 'maxele': colDic = { 'bottomcolor': '#0000ff', 'bottommiddle': '#00ffff', 'topmiddle': '#ffff00', 'topcolor': '#ff0000' } else: colDic = { 'bottomcolor': '#000000', 'bottommiddle': '#ff0000', 'topmiddle': '#ffff00', 'topcolor': '#ffffff' } # Create color ramp function and add colors fnc = QgsColorRampShader() fnc.setColorRampType(QgsColorRampShader.Interpolated) lst = [QgsColorRampShader.ColorRampItem(valueList[0], QColor(colDic['bottomcolor'])),\ QgsColorRampShader.ColorRampItem(valueList[1], QColor(colDic['bottommiddle'])), \ QgsColorRampShader.ColorRampItem(valueList[2], QColor(colDic['topmiddle'])), \ QgsColorRampShader.ColorRampItem(valueList[3], QColor(colDic['topcolor']))] fnc.setColorRampItemList(lst) # Create raster shader and add color ramp function shader = QgsRasterShader() shader.setRasterShaderFunction(fnc) # Create color render and set opacity renderer = QgsSingleBandPseudoColorRenderer(provider, 1, shader) renderer.setOpacity(0.75) # Get output format output_format = QgsRasterFileWriter.driverForExtension( os.path.splitext(outfile)[1]) # Open output file for writing rfw = QgsRasterFileWriter(outfile) rfw.setOutputProviderKey('gdal') rfw.setOutputFormat(output_format) # Add EPSG 4326 to layer crs crs = QgsCoordinateReferenceSystem() crs.createFromSrid(4326) # Create Raster pipe and set provider and renderer pipe = QgsRasterPipe() pipe.set(provider.clone()) pipe.set(renderer.clone()) # Get transform context transform_context = QgsProject.instance().transformContext() # Write to file rfw.writeRaster(pipe, provider.xSize(), provider.ySize(), provider.extent(), crs, transform_context) logger.info( 'Conveted data in ' + rasterfile + ' from float64 to 8bit, added color palette and saved to tiff (' + outfile.split('/')[-1] + ') file') if not rlayer.isValid(): raise Exception('Invalid raster') return (valueList)
def style_land_cover_lc_change(outfile): layer_lc_change = iface.addRasterLayer( outfile, QtGui.QApplication.translate('LDMPPlugin', 'Land cover change')) if not layer_lc_change.isValid(): log('Failed to add layer') return None fcn = QgsColorRampShader() fcn.setColorRampType(QgsColorRampShader.EXACT) lst = [ QgsColorRampShader.ColorRampItem(11, QtGui.QColor(246, 246, 234), 'Croplands-Croplands'), QgsColorRampShader.ColorRampItem(12, QtGui.QColor('#de2d26'), 'Croplands-Forest land'), QgsColorRampShader.ColorRampItem(13, QtGui.QColor('#fb6a4a'), 'Croplands-Grassland'), QgsColorRampShader.ColorRampItem(14, QtGui.QColor('#fc9272'), 'Croplands-Wetlands'), QgsColorRampShader.ColorRampItem(15, QtGui.QColor('#fcbba1'), 'Croplands-Settlements'), QgsColorRampShader.ColorRampItem(16, QtGui.QColor('#fee5d9'), 'Croplands-Other land'), QgsColorRampShader.ColorRampItem(22, QtGui.QColor(246, 246, 234), 'Forest land-Forest land'), QgsColorRampShader.ColorRampItem(21, QtGui.QColor('#31a354'), 'Forest land-Croplands'), QgsColorRampShader.ColorRampItem(23, QtGui.QColor('#74c476'), 'Forest land-Grassland'), QgsColorRampShader.ColorRampItem(24, QtGui.QColor('#a1d99b'), 'Forest land-Wetlands'), QgsColorRampShader.ColorRampItem(25, QtGui.QColor('#c7e9c0'), 'Forest land-Settlements'), QgsColorRampShader.ColorRampItem(26, QtGui.QColor('#edf8e9'), 'Forest land-Other land'), QgsColorRampShader.ColorRampItem(33, QtGui.QColor(246, 246, 234), 'Grassland-Grassland'), QgsColorRampShader.ColorRampItem(31, QtGui.QColor('#727200'), 'Grassland-Croplands'), QgsColorRampShader.ColorRampItem(32, QtGui.QColor('#8b8b00'), 'Grassland-Forest land'), QgsColorRampShader.ColorRampItem(34, QtGui.QColor('#a5a500'), 'Grassland-Wetlands'), QgsColorRampShader.ColorRampItem(35, QtGui.QColor('#bebe00'), 'Grassland-Settlements'), QgsColorRampShader.ColorRampItem(36, QtGui.QColor('#d8d800'), 'Grassland-Other land'), QgsColorRampShader.ColorRampItem(44, QtGui.QColor(246, 246, 234), 'Wetlands-Wetlands'), QgsColorRampShader.ColorRampItem(41, QtGui.QColor('#3182bd'), 'Wetlands-Croplands'), QgsColorRampShader.ColorRampItem(42, QtGui.QColor('#6baed6'), 'Wetlands-Forest land'), QgsColorRampShader.ColorRampItem(43, QtGui.QColor('#9ecae1'), 'Wetlands-Grassland'), QgsColorRampShader.ColorRampItem(45, QtGui.QColor('#c6dbef'), 'Wetlands-Settlements'), QgsColorRampShader.ColorRampItem(46, QtGui.QColor('#eff3ff'), 'Wetlands-Other land'), QgsColorRampShader.ColorRampItem(55, QtGui.QColor(246, 246, 234), 'Settlements-Settlements'), QgsColorRampShader.ColorRampItem(51, QtGui.QColor('#756bb1'), 'Settlements-Croplands'), QgsColorRampShader.ColorRampItem(52, QtGui.QColor('#9e9ac8'), 'Settlements-Forest land'), QgsColorRampShader.ColorRampItem(53, QtGui.QColor('#bcbddc'), 'Settlements-Grassland'), QgsColorRampShader.ColorRampItem(54, QtGui.QColor('#dadaeb'), 'Settlements-Wetlands'), QgsColorRampShader.ColorRampItem(56, QtGui.QColor('#f2f0f7'), 'Settlements-Other land'), QgsColorRampShader.ColorRampItem(66, QtGui.QColor(246, 246, 234), 'Other land-Other land'), QgsColorRampShader.ColorRampItem(61, QtGui.QColor('#636363'), 'Other land-Croplands'), QgsColorRampShader.ColorRampItem(62, QtGui.QColor('#969696'), 'Other land-Forest land'), QgsColorRampShader.ColorRampItem(63, QtGui.QColor('#bdbdbd'), 'Other land-Grassland'), QgsColorRampShader.ColorRampItem(64, QtGui.QColor('#d9d9d9'), 'Other land-Wetlands'), QgsColorRampShader.ColorRampItem(65, QtGui.QColor('#f7f7f7'), 'Other land-Settlements') ] fcn.setColorRampItemList(lst) shader = QgsRasterShader() shader.setRasterShaderFunction(fcn) pseudoRenderer = QgsSingleBandPseudoColorRenderer( layer_lc_change.dataProvider(), 1, shader) layer_lc_change.setRenderer(pseudoRenderer) layer_lc_change.triggerRepaint() layer_lc_change.triggerRepaint() iface.legendInterface().refreshLayerSymbology(layer_lc_change)
def processAlgorithm(self, parameters, context, feedback): ''' Here is where the processing itself takes place. ''' # if not is_dependencies_satisfied: return {} # Get get input raster and check its one-band the_layer = self.parameterAsRasterLayer(parameters, self.THE_LAYER, context) # if not self._check_oneband(the_layer): self._error = self._the_strings["ERR_ONEB"] return {} # Get .clr file and check it clr = self.parameterAsFile(parameters, self.THE_CLR, context) if not self._check_clr(clr): self._error = self._the_strings["ERR_NOCLR"] return {} # Get raster min/max values provider = the_layer.dataProvider() ext1 = the_layer.extent() stats = provider.bandStatistics(1, QgsRasterBandStats.All, ext1, 0) minv = stats.minimumValue maxv = stats.maximumValue d = (maxv - minv) / 100. # Scale percentages to raster values with codecs.open(clr, 'r', 'utf-8') as fi: buff = fi.readlines() # 0.00000000000000000 200 215 133 255 ar = [] for e in buff[2:]: br = e[:-1].split() v = float(br[0]) * d + minv ar.append([v, int(br[1]), int(br[2]), int(br[3]), int(br[4])]) if br[0][:3] == '100': # end of colour ramp break # Style raster fcn = qRS() fcn.setColorRampType(qRS.Interpolated) lst = [] for e in ar: lst.append(qRS.ColorRampItem(e[0],QColor(int(e[1]), int(e[2]), int(e[3]), int(e[4])),str(e[0]))) fcn.setColorRampItemList(lst) try: shader = QgsRasterShader() shader.setRasterShaderFunction(fcn) renderer = QgsSingleBandPseudoColorRenderer(the_layer.dataProvider(), the_layer.type(), shader) the_layer.setRenderer(renderer) the_layer.triggerRepaint() except: pass # Get output file name output_file = self.parameterAsFileOutput(parameters, self.OUTPUT, context) if output_file == '': output_file = os.path.join(QgsProcessingUtils.tempFolder(), the_layer.name()) # Save QGIS colour ramp file with codecs.open(output_file, 'w', 'utf-8') as fo: fo.write('# bcclr2tbl Generated Color Map Export File\n') fo.write('INTERPOLATION:INTERPOLATED\n') # 614,46,124,228,255,614 for e in ar: fo.write('%.3f,%d,%d,%d,%d,%.1f\n' % (e[0], int(e[1]), int(e[2]), int(e[3]), int(e[4]), e[0])) return {self.OUTPUT:output_file}
def process(self, data): # data = {upd/npd: {dating = [calendar years BP, ...], uncert = [calendar years, ...], coords = [[x, y], ...], accur = [accuracy, ...]}} UPD_t_ds = np.round(data["upd"]["dating"]).astype( int ) # mean datings of archaeological components (calendar years BP) UPD_uncert_ds = np.round(data["upd"]["uncert"]).astype( int) # uncertainties of the datings (calendar years) UPD_As = np.round(data["upd"]["coords"]).astype( int) # spatial coordinates of archaeological components (metres) UPD_accurs = np.round(data["upd"]["accur"]).astype( int ) # accuracies of spatial coordinates of archaeological components (+-metres) NPD_t_ds = np.round(data["npd"]["dating"]).astype( int ) # measured radiocarbon ages of archaeological components (radiocarbon years) NPD_uncert_ds = np.round(data["npd"]["uncert"]).astype( int ) # 1-sigma uncertainties of the measured radiocarbon ages (radiocarbon years) NPD_As = np.round(data["npd"]["coords"]).astype( int) # spatial coordinates of archaeological components (metres) NPD_accurs = np.round(data["npd"]["accur"]).astype( int ) # accuracies of spatial coordinates of archaeological components (+-metres) if (not UPD_t_ds.size) and (not NPD_t_ds.size): return s_halflife = self.s_duration / 2 # expected half-life of a settlement in years s_radius = self.s_diameter / 2 # expected radius of a settlement in metres # temporal extent t_min = np.inf t_max = -np.inf if UPD_t_ds.size: t_min = min(t_min, (UPD_t_ds - UPD_uncert_ds).min() - self.s_duration) t_max = max(t_max, (UPD_t_ds + UPD_uncert_ds).max() + self.s_duration) if NPD_t_ds.size: t_min = min(t_min, (NPD_t_ds - 2 * NPD_uncert_ds).min() - self.s_duration) t_max = max(t_max, (NPD_t_ds + 2 * NPD_uncert_ds).max() + self.s_duration) t_min, t_max = [ int(round(value / 10) * 10) for value in [t_min, t_max] ] if self.time_from is not None: t_max = min(t_max, self.time_from) if self.time_to is not None: t_min = max(t_min, self.time_to) ts_slices = np.arange(t_max, t_min - 2 * self.time_step, -self.time_step).tolist() # times of time slices # prepare lookup for probability distributions of 14C datings self.setLabelText("Calibrating radiocarbon dates") cal_curve = load_curve( os.path.join(os.path.dirname(__file__), "intcal13.14c") ) # [[CalBP, ConvBP, CalSigma], ...], sorted by CalBP # filter calibration curve to include only time-step dates cal_curve = cal_curve[(cal_curve[:, 0] >= t_min) & (cal_curve[:, 0] <= t_max)][::-1] ts = cal_curve[:, 0] curve_conv_age = cal_curve[:, 1] curve_uncert = cal_curve[:, 2] if ts[-1] < ts_slices[-1]: ts_slices.append(ts[-1]) # calculate probability distributions for all combinations of 14c age and uncertainty unique_dates = set() # ((age, uncert), ...) for idx in range(NPD_t_ds.shape[0]): unique_dates.add((NPD_t_ds[idx], NPD_uncert_ds[idx])) lookup_14c = defaultdict( dict ) # {age: {uncert: D, ...}, ...}; D[ti] = p; where ti = index in ts, p = probability cmax = len(unique_dates) cnt = 0 for age, uncert in unique_dates: QtWidgets.QApplication.processEvents() if not self.running: return self.setValue((cnt / cmax) * 100) cnt += 1 lookup_14c[age][uncert] = calibrate(age, uncert, curve_conv_age, curve_uncert) # prepare lookup of spatial probability distribution around evidence points self.setLabelText("Calculating spatial probability distribution") self.setValue(0) accurs = set() accurs.update(UPD_accurs.tolist()) accurs.update(NPD_accurs.tolist()) lookup_f_s = { } # {accur: M, ...}; M[n, n] = f_s(d, accur, s_radius); where center is point A and n is 2 * [maximum distance from A in raster units] + 1; where f_s > 0 cnt = 0 cmax = len(accurs) for accur in accurs: QtWidgets.QApplication.processEvents() if not self.running: return self.setValue((cnt / cmax) * 100) cnt += 1 r = int(round((accur + 2 * s_radius) / self.cell_size)) n = 2 * r + 1 lookup_f_s[accur] = np.zeros((n, n), dtype=float) rcs = np.argwhere(np.ones((n, n), dtype=bool)) mask = (rcs > r).all(axis=1) for row, col in rcs[mask]: d = (((row - r)**2 + (col - r)**2)**0.5) * self.cell_size if self.approximate: p = f_s_approx(d, accur, s_radius) else: p = f_S_lens(d, accur, s_radius) / f_S(accur, s_radius) if (p == np.inf) or np.isnan(p): p = 0 lookup_f_s[accur][row, col] = p lookup_f_s[accur][n - row, col] = p lookup_f_s[accur][row, n - col] = p lookup_f_s[accur][n - row, n - col] = p lookup_f_s[accur][0, 0] = lookup_f_s[accur][0, 1] # spatial extent row_min, col_min = np.inf, np.inf row_max, col_max = -np.inf, -np.inf for As, accurs in [[UPD_As, UPD_accurs], [NPD_As, NPD_accurs]]: for idx in range(As.shape[0]): A = As[idx] accur = accurs[idx] r = int(lookup_f_s[accur].shape[0] / 2) col, row = np.round(A / self.cell_size).astype(int) row_min = min(row_min, row - r - 1) col_min = min(col_min, col - r - 1) row_max = max(row_max, row + r) col_max = max(col_max, col + r) width, height = (col_max - col_min), (row_max - row_min) x0, y0 = col_min * self.cell_size, row_min * self.cell_size # calculate time-slices self.setLabelText("Generating time-slices") paths = [] summed = [] val_max = -np.inf grid_summed = np.zeros((height, width), dtype=float) t_slice_prev = ts_slices.pop(0) t_slice = ts_slices.pop(0) n_slice = 1 for ti in range(ts.shape[0]): QtWidgets.QApplication.processEvents() if not self.running: return self.setValue((ti / ts.shape[0]) * 100) grid = np.ones((height, width), dtype=float) for idx in range(UPD_t_ds.shape[0]): t_d = UPD_t_ds[idx] uncert_d = UPD_uncert_ds[idx] A = UPD_As[idx] accur = UPD_accurs[idx] M = 1 - lookup_f_s[accur] * f_t_UPD(ts[ti], t_d, uncert_d, s_halflife) r = int((M.shape[0] - 1) / 2) col0, row0 = np.round((A - [x0, y0]) / self.cell_size - r - 1).astype(int) grid[row0:row0 + M.shape[0], col0:col0 + M.shape[0]] *= M for idx in range(NPD_t_ds.shape[0]): t_d = NPD_t_ds[idx] uncert_d = NPD_uncert_ds[idx] A = NPD_As[idx] accur = NPD_accurs[idx] M = 1 - lookup_f_s[accur] * f_t_NPD( ts[ti], s_halflife, lookup_14c[t_d][uncert_d], ts) r = int((M.shape[0] - 1) / 2) col0, row0 = np.round((A - [x0, y0]) / self.cell_size - r - 1).astype(int) grid[row0:row0 + M.shape[0], col0:col0 + M.shape[0]] *= M grid = 1 - grid grid[np.isnan(grid)] = 0 grid[grid == np.inf] = 0 summed.append(grid.sum()) if ts[ti] <= t_slice: val_max = max(val_max, grid_summed.max()) t_ce, cebce = bp_to_ce(t_slice_prev) t_ce2, cebce2 = bp_to_ce(t_slice) datestr = "%03d_%d_%s_-_%d_%s" % (n_slice, t_ce, cebce, t_ce2, cebce2) paths.append([ datestr, os.path.join(self.path_layers, "ede_%s.tif" % (datestr)) ]) self.save_raster(grid_summed, x0, y0, paths[-1][1]) t_slice_prev = t_slice t_slice = ts_slices.pop(0) n_slice += 1 grid_summed[:] = grid else: grid_summed += grid if self.path_summed: self.save_summed(ts, summed) project = QgsProject.instance() val_max = val_max * 0.9 self.setLabelText("Rendering time-slices") cnt = 0 cmax = len(paths) for datestr, path in paths: QtWidgets.QApplication.processEvents() if not self.running: return self.setValue((cnt / cmax) * 100) cnt += 1 layer = QgsRasterLayer(path, "EDE_%s" % (datestr)) layer.setCrs(self.crs) s = QgsRasterShader() c = QgsColorRampShader() c.setColorRampType(QgsColorRampShader.Interpolated) i = [] i.append(QgsColorRampShader.ColorRampItem(0, self.colors[0])) i.append( QgsColorRampShader.ColorRampItem(val_max / 2, self.colors[1])) i.append(QgsColorRampShader.ColorRampItem(val_max, self.colors[2])) c.setColorRampItemList(i) s.setRasterShaderFunction(c) ps = QgsSingleBandPseudoColorRenderer(layer.dataProvider(), 1, s) ps.setClassificationMin(0) ps.setClassificationMax(val_max) layer.setRenderer(ps) self.save_rendered( layer, os.path.join(self.path_rendered, "%s.tif" % (datestr))) project.addMapLayer(layer)
def cvt_vtr(self): QSWATMOD_path_dict = self.dirs_and_paths() selectedVector = self.dlg.comboBox_vector_lyrs.currentText() layer = QgsProject.instance().mapLayersByName(str(selectedVector))[0] # Find .dis file and read number of rows, cols, x spacing, and y spacing (not allowed to change) for filename in glob.glob(str(QSWATMOD_path_dict['SMfolder']) + "/*.dis"): with open(filename, "r") as f: data = [] for line in f.readlines(): if not line.startswith("#"): data.append(line.replace('\n', '').split()) nrow = int(data[0][1]) ncol = int(data[0][2]) delr = float(data[2][1]) # is the cell width along rows (y spacing) delc = float( data[3][1]) # is the cell width along columns (x spacing). # get extent ext = layer.extent() xmin = ext.xMinimum() xmax = ext.xMaximum() ymin = ext.yMinimum() ymax = ext.yMaximum() extent = "{a},{b},{c},{d}".format(a=xmin, b=xmax, c=ymin, d=ymax) fdnames = [ field.name() for field in layer.dataProvider().fields() if not (field.name() == 'fid' or field.name() == 'id' or field.name() == 'xmin' or field.name() == 'xmax' or field.name() == 'ymin' or field.name() == 'ymax' or field.name() == 'grid_id' or field.name() == 'row' or field.name() == 'col' or field.name() == 'elev_mf') ] # Create swatmf_results tree inside root = QgsProject.instance().layerTreeRoot() if root.findGroup("swatmf_results"): swatmf_results = root.findGroup("swatmf_results") else: swatmf_results = root.insertGroup(0, "swatmf_results") if root.findGroup(selectedVector): rastergroup = root.findGroup(selectedVector) else: rastergroup = swatmf_results.insertGroup(0, selectedVector) per = 0 self.dlg.progressBar_cvt_vtr.setValue(0) for fdnam in fdnames: QCoreApplication.processEvents() nodata = float(self.dlg.lineEdit_nodata.text()) mincolor = self.dlg.mColorButton_min_rmap.color().name() maxcolor = self.dlg.mColorButton_max_rmap.color().name() name = fdnam name_ext = "{}.tif".format(name) output_dir = QSWATMOD_path_dict['SMshps'] # create folder for each layer output rasterpath = os.path.join(output_dir, selectedVector) if not os.path.exists(rasterpath): os.makedirs(rasterpath) output_raster = os.path.join(rasterpath, name_ext) params = { 'INPUT': layer, 'FIELD': fdnam, 'UNITS': 1, 'WIDTH': delc, 'HEIGHT': delr, 'EXTENT': extent, 'NODATA': nodata, 'DATA_TYPE': 5, #Float32 'OUTPUT': output_raster } processing.run("gdal:rasterize", params) rasterlayer = QgsRasterLayer(output_raster, '{0} ({1})'.format(fdnam, selectedVector)) QgsProject.instance().addMapLayer(rasterlayer, False) rastergroup.insertChildNode(0, QgsLayerTreeLayer(rasterlayer)) stats = rasterlayer.dataProvider().bandStatistics( 1, QgsRasterBandStats.All) rmin = stats.minimumValue rmax = stats.maximumValue fnc = QgsColorRampShader() lst = [ QgsColorRampShader.ColorRampItem(rmin, QColor(mincolor)), QgsColorRampShader.ColorRampItem(rmax, QColor(maxcolor)) ] fnc.setColorRampItemList(lst) fnc.setColorRampType(QgsColorRampShader.Interpolated) shader = QgsRasterShader() shader.setRasterShaderFunction(fnc) renderer = QgsSingleBandPseudoColorRenderer(rasterlayer.dataProvider(), 1, shader) rasterlayer.setRenderer(renderer) rasterlayer.triggerRepaint() # create image img = QImage(QSize(800, 800), QImage.Format_ARGB32_Premultiplied) # set background color # bcolor = QColor(255, 255, 255, 255) bcolor = QColor(255, 255, 255, 0) img.fill(bcolor.rgba()) # create painter p = QPainter() p.begin(img) p.setRenderHint(QPainter.Antialiasing) # create map settings ms = QgsMapSettings() ms.setBackgroundColor(bcolor) # set layers to render flayer = QgsProject.instance().mapLayersByName(rasterlayer.name()) ms.setLayers([flayer[0]]) # set extent rect = QgsRectangle(ms.fullExtent()) rect.scale(1.1) ms.setExtent(rect) # set ouptut size ms.setOutputSize(img.size()) # setup qgis map renderer render = QgsMapRendererCustomPainterJob(ms, p) render.start() render.waitForFinished() # get timestamp p.drawImage(QPoint(), img) pen = QPen(Qt.red) pen.setWidth(2) p.setPen(pen) font = QFont() font.setFamily('Times') # font.setBold(True) font.setPointSize(18) p.setFont(font) # p.setBackground(QColor('sea green')) doesn't work p.drawText(QRect(0, 0, 800, 800), Qt.AlignRight | Qt.AlignBottom, fdnam) p.end() # save the image img.save(os.path.join(rasterpath, '{:03d}_{}.jpg'.format(per, fdnam))) # Update progress bar per += 1 progress = round((per / len(fdnames)) * 100) self.dlg.progressBar_cvt_vtr.setValue(progress) QCoreApplication.processEvents() self.dlg.raise_() duration = self.dlg.doubleSpinBox_ani_r_time.value() # filepaths fp_in = os.path.join(rasterpath, '*.jpg') fp_out = os.path.join(rasterpath, '{}.gif'.format(selectedVector)) # https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#gif fimg, *fimgs = [Image.open(f) for f in sorted(glob.glob(fp_in))] fimg.save(fp=fp_out, format='GIF', append_images=fimgs, save_all=True, duration=duration * 1000, loop=0, transparency=0) msgBox = QMessageBox() msgBox.setWindowIcon(QtGui.QIcon(':/QSWATMOD2/pics/sm_icon.png')) msgBox.setWindowTitle("Coverted!") msgBox.setText( "Fields from {} were converted successfully!".format(selectedVector)) msgBox.exec_() questionBox = QMessageBox() questionBox.setWindowIcon(QtGui.QIcon(':/QSWATMOD2/pics/sm_icon.png')) reply = QMessageBox.question(questionBox, 'Open?', 'Do you want to open the animated gif file?', QMessageBox.Yes, QMessageBox.No) if reply == QMessageBox.Yes: os.startfile(os.path.join(rasterpath, '{}.gif'.format(selectedVector)))
def Color(self, file_in, calcType=None): """ Color the Inbound file (Essentially the File we JUST exported) and display it to screen) :param file_in: The file that was just exported :type file_in: FileImport :return: TO SCREEN Rendered Image :rtype: None """ k = self.iface.addRasterLayer(file_in.filePath, file_in.baseName) stats = k.dataProvider().bandStatistics(1, QgsRasterBandStats.All, k.extent(), 0) minimum = stats.minimumValue maximum = stats.maximumValue self.com.log("Color func: [Min val: {0} | Max val: {1}".format( str(minimum), str(maximum)), level=0) ramp_shader = QgsColorRampShader() ramp_shader.setColorRampType(QgsColorRampShader.INTERPOLATED) if calcType is None: color_list = [ QgsColorRampShader.ColorRampItem(minimum, QColor(255, 0, 0)), QgsColorRampShader.ColorRampItem(0, QColor(255, 207, 74, 255)), QgsColorRampShader.ColorRampItem(maximum, QColor(0, 255, 0)) ] elif calcType == "EVI": color_list = [ QgsColorRampShader.ColorRampItem(-2, QColor(255, 0, 0)), QgsColorRampShader.ColorRampItem(0, QColor(255, 207, 74, 255)), QgsColorRampShader.ColorRampItem(2, QColor(0, 255, 0)) ] else: color_list = [ QgsColorRampShader.ColorRampItem(minimum, QColor(255, 0, 0)), QgsColorRampShader.ColorRampItem(0, QColor(255, 207, 74, 255)), QgsColorRampShader.ColorRampItem(maximum, QColor(0, 255, 0)) ] ramp_shader.setColorRampItemList(color_list) shader = QgsRasterShader() shader.setRasterShaderFunction(ramp_shader) renderer = QgsSingleBandPseudoColorRenderer(k.dataProvider(), 1, shader) k.setRenderer(renderer) """ Export colored image to file """ export_path = file_in.filePath + ".colored.tif" file_writer = QgsRasterFileWriter(export_path) pipe = QgsRasterPipe() provide = k.dataProvider() # Pipe Setter if not pipe.set(provide.clone()): self.com.error(Bold="PipeProviderError:", String="Cannot set pipe provider", level=1, duration=3) self.com.log( "mainPlug - Color: Pipe provider error on line 473, Continuing...", level=1) self.com.log(str(pipe.renderer()), level=0) pipe.set(renderer.clone()) file_writer.writeRaster(pipe, provide.xSize(), provide.ySize(), provide.extent(), provide.crs())
def set_raster_style(raster_layer, style): """Set QGIS raster style based on InaSAFE style dictionary for QGIS >= 2.0. This function will set both the colour map and the transparency for the passed in layer. :param raster_layer: A QGIS raster layer that will be styled. :type raster_layer: QgsVectorLayer :param style: List of the form as in the example below. :type style: list Example:: style_classes = [dict(colour='#38A800', quantity=2, transparency=0), dict(colour='#38A800', quantity=5, transparency=50), dict(colour='#79C900', quantity=10, transparency=50), dict(colour='#CEED00', quantity=20, transparency=50), dict(colour='#FFCC00', quantity=50, transparency=34), dict(colour='#FF6600', quantity=100, transparency=77), dict(colour='#FF0000', quantity=200, transparency=24), dict(colour='#7A0000', quantity=300, transparency=22)] :returns: A two tuple containing a range list and a transparency list. :rtype: (list, list) """ # Note imports here to prevent importing on unsupported QGIS versions # pylint: disable=E0611 # pylint: disable=W0621 # pylint: disable=W0404 # noinspection PyUnresolvedReferences from qgis.core import (QgsRasterShader, QgsColorRampShader, QgsSingleBandPseudoColorRenderer, QgsRasterTransparency) # pylint: enable=E0611 # pylint: enable=W0621 # pylint: enable=W0404 ramp_item_list = [] transparency_list = [] LOGGER.debug(style) for style_class in style: LOGGER.debug('Evaluating class:\n%s\n' % style_class) if 'quantity' not in style_class: LOGGER.exception('Class has no quantity attribute') continue class_max = style_class['max'] if math.isnan(class_max): LOGGER.debug('Skipping class - max is nan.') continue class_min = style_class['min'] if math.isnan(class_min): LOGGER.debug('Skipping class - min is nan.') continue colour = QtGui.QColor(style_class['colour']) label = '' if 'label' in style_class: label = style_class['label'] # noinspection PyCallingNonCallable ramp_item = QgsColorRampShader.ColorRampItem(class_max, colour, label) ramp_item_list.append(ramp_item) # Create opacity entries for this range transparency_percent = 0 if 'transparency' in style_class: transparency_percent = int(style_class['transparency']) if transparency_percent > 0: # Check if range extrema are integers so we know if we can # use them to calculate a value range # noinspection PyCallingNonCallable pixel = QgsRasterTransparency.TransparentSingleValuePixel() pixel.min = class_min # We want it just a little bit smaller than max # so that ranges are discrete pixel.max = class_max # noinspection PyPep8Naming pixel.percentTransparent = transparency_percent transparency_list.append(pixel) band = 1 # gdal counts bands from base 1 LOGGER.debug('Setting colour ramp list') raster_shader = QgsRasterShader() color_ramp_shader = QgsColorRampShader() color_ramp_shader.setColorRampType(QgsColorRampShader.INTERPOLATED) color_ramp_shader.setColorRampItemList(ramp_item_list) LOGGER.debug('Setting shader function') raster_shader.setRasterShaderFunction(color_ramp_shader) LOGGER.debug('Setting up renderer') renderer = QgsSingleBandPseudoColorRenderer( raster_layer.dataProvider(), band, raster_shader) LOGGER.debug('Assigning renderer to raster layer') raster_layer.setRenderer(renderer) LOGGER.debug('Setting raster transparency list') renderer = raster_layer.renderer() transparency = QgsRasterTransparency() transparency.setTransparentSingleValuePixelList(transparency_list) renderer.setRasterTransparency(transparency) # For interest you can also view the list like this: # pix = t.transparentSingleValuePixelList() # for px in pix: # print 'Min: %s Max %s Percent %s' % ( # px.min, px.max, px.percentTransparent) LOGGER.debug('Saving style as default') raster_layer.saveDefaultStyle() LOGGER.debug('Setting raster style done!') return ramp_item_list, transparency_list
def _setNewRasterStyle(theQgsRasterLayer, theClasses): """Set QGIS raster style based on InaSAFE style dictionary for QGIS >= 2.0. This function will set both the colour map and the transparency for the passed in layer. Args: * theQgsRasterLayer: QgsRasterLayer * theClasses: List of the form as in the example below. Returns: * list: RangeList * list: TransparencyList Example: style_classes = [dict(colour='#38A800', quantity=2, transparency=0), dict(colour='#38A800', quantity=5, transparency=50), dict(colour='#79C900', quantity=10, transparency=50), dict(colour='#CEED00', quantity=20, transparency=50), dict(colour='#FFCC00', quantity=50, transparency=34), dict(colour='#FF6600', quantity=100, transparency=77), dict(colour='#FF0000', quantity=200, transparency=24), dict(colour='#7A0000', quantity=300, transparency=22)] """ # Note imports here to prevent importing on unsupported QGIS versions # pylint: disable=E0611 # pylint: disable=W0621 # pylint: disable=W0404 from qgis.core import (QgsRasterShader, QgsColorRampShader, QgsSingleBandPseudoColorRenderer, QgsRasterTransparency) # pylint: enable=E0611 # pylint: enable=W0621 # pylint: enable=W0404 myRampItemList = [] myTransparencyList = [] LOGGER.debug(theClasses) for myClass in theClasses: LOGGER.debug('Evaluating class:\n%s\n' % myClass) if 'quantity' not in myClass: LOGGER.exception('Class has no quantity attribute') continue myMax = myClass['max'] if math.isnan(myMax): LOGGER.debug('Skipping class - max is nan.') continue myMin = myClass['min'] if math.isnan(myMin): LOGGER.debug('Skipping class - min is nan.') continue myColour = QtGui.QColor(myClass['colour']) myLabel = QtCore.QString() if 'label' in myClass: myLabel = QtCore.QString(myClass['label']) myRampItem = QgsColorRampShader.ColorRampItem(myMax, myColour, myLabel) myRampItemList.append(myRampItem) # Create opacity entries for this range myTransparencyPercent = 0 if 'transparency' in myClass: myTransparencyPercent = int(myClass['transparency']) if myTransparencyPercent > 0: # Check if range extrema are integers so we know if we can # use them to calculate a value range myPixel = QgsRasterTransparency.TransparentSingleValuePixel() myPixel.min = myMin # We want it just a leeetle bit smaller than max # so that ranges are discrete myPixel.max = myMax myPixel.percentTransparent = myTransparencyPercent myTransparencyList.append(myPixel) myBand = 1 # gdal counts bands from base 1 LOGGER.debug('Setting colour ramp list') myRasterShader = QgsRasterShader() myColorRampShader = QgsColorRampShader() myColorRampShader.setColorRampType(QgsColorRampShader.INTERPOLATED) myColorRampShader.setColorRampItemList(myRampItemList) LOGGER.debug('Setting shader function') myRasterShader.setRasterShaderFunction(myColorRampShader) LOGGER.debug('Setting up renderer') myRenderer = QgsSingleBandPseudoColorRenderer( theQgsRasterLayer.dataProvider(), myBand, myRasterShader) LOGGER.debug('Assigning renderer to raster layer') theQgsRasterLayer.setRenderer(myRenderer) LOGGER.debug('Setting raster transparency list') myRenderer = theQgsRasterLayer.renderer() myTransparency = QgsRasterTransparency() myTransparency.setTransparentSingleValuePixelList(myTransparencyList) myRenderer.setRasterTransparency(myTransparency) # For interest you can also view the list like this: #pix = t.transparentSingleValuePixelList() #for px in pix: # print 'Min: %s Max %s Percent %s' % ( # px.min, px.max, px.percentTransparent) LOGGER.debug('Saving style as default') theQgsRasterLayer.saveDefaultStyle() LOGGER.debug('Setting raster style done!') return myRampItemList, myTransparencyList