Saturday 16 March 2019

How to add all ".dat" files (raster) into QGIS, in a defined directory and defined legend (style), using python code


I'm using a QGIS 2.8.3 in Windows 10. I've added just one raster ("dat" file) to the QGIS, with a defined legend, using the following code. If I wanted to add all the "dat" files into a directory how could I correct my code to do that? Any idea?


The python script:


# coding: utf-8
#---------------------------------------------
from PyQt4 import QtGui
from PyQt4.QtCore import *
from PyQt4.QtXml import *

from PyQt4.QtCore import QSize
from PyQt4 import QtCore
from qgis import core, gui

lyr = QgsRasterLayer("C:/PATRICIA/IG/OPERACIONAL/FWI_"+file_date+".dat", "FWI_"+file_date)
s = QgsRasterShader()
c = QgsColorRampShader()
c.setColorRampType(QgsColorRampShader.INTERPOLATED)
i = []


i.append(QgsColorRampShader.ColorRampItem(8.5, QtGui.QColor('#2b9e27'), '8.5'))
i.append(QgsColorRampShader.ColorRampItem(17.2, QtGui.QColor('#fee717'), '17.2'))
i.append(QgsColorRampShader.ColorRampItem(24.6, QtGui.QColor('#ec7000'), '24.6'))
i.append(QgsColorRampShader.ColorRampItem(38.3, QtGui.QColor('#cc292c'), '38.3'))
i.append(QgsColorRampShader.ColorRampItem(100, QtGui.QColor('#75263b'), '100'))

c.setColorRampItemList(i)
s.setRasterShaderFunction(c)
ps = QgsSingleBandPseudoColorRenderer(lyr.dataProvider(), 1, s)
lyr.setRenderer(ps)

QgsMapLayerRegistry.instance().addMapLayer(lyr)

Answer



Building on what Peter has suggested, you could try using the following code (note that you did not define file_date in your code so I used the basename of the raster instead but you can modify it):


from PyQt4 import QtGui
from PyQt4.QtCore import *
from PyQt4.QtXml import *
from PyQt4.QtCore import QSize, QFileInfo
from PyQt4 import QtCore
from qgis import core, gui
import glob


s = QgsRasterShader()
c = QgsColorRampShader()
c.setColorRampType(QgsColorRampShader.INTERPOLATED)
i = []

i.append(QgsColorRampShader.ColorRampItem(8.5, QtGui.QColor('#2b9e27'), '8.5'))
i.append(QgsColorRampShader.ColorRampItem(17.2, QtGui.QColor('#fee717'), '17.2'))
i.append(QgsColorRampShader.ColorRampItem(24.6, QtGui.QColor('#ec7000'), '24.6'))
i.append(QgsColorRampShader.ColorRampItem(38.3, QtGui.QColor('#cc292c'), '38.3'))

i.append(QgsColorRampShader.ColorRampItem(100, QtGui.QColor('#75263b'), '100'))

c.setColorRampItemList(i)
s.setRasterShaderFunction(c)

path = "C:/PATRICIA/IG/OPERACIONAL//"
for ras in glob.glob(path + "*.tif"):
lyr = QgsRasterLayer(ras, QFileInfo(ras).baseName())
ps = QgsSingleBandPseudoColorRenderer(lyr.dataProvider(), 1, s)
lyr.setRenderer(ps)

QgsMapLayerRegistry.instance().addMapLayer(lyr)

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...