2

I'm having troubles with a pyQGIS script. I'm trying to create a large number of maps showing NDVI in a certain area over the time. The script opens a raster file, applies a style, changes title and exports map.

I made a loop to do that and it doesn't work, the canvas doesn't refresh and many maps are from the same raster file. I Use solutions like How to refresh MapCanvas while PyQGIS-script is running? or Map on canvas renders after image saving [duplicate] with no success.

But, I'm looking a way to create dummy rasters/vectors prior to recreates pyQGIS problems. R have excellent guides, and this also can be applied to spatial data.

So, is there a way to create dummy rasters with random numbers to recreates problems like this?

By the way, the script is something like the code below. I'm looking a way to replaces files item into dummy rasters.

from qgis.core import QgsProject
from qgis.gui import *
from PyQt4.QtCore import QSettings, QTranslator, qVersion, QCoreApplication,QFileInfo,QSizeF,QTimer
from PyQt4.QtGui import QAction, QIcon, QPrinter,QPainter
import os
import glob

files = glob.glob(r'Path/to/monthly/NDVI/*.tif')

aaa = [some list]

n = 287 # 12 year

for i in range(0,n):
    project = QgsProject.instance()
    project.read(QFileInfo('some/Project.qgs'))
    layer1 = QgsRasterLayer(files[i],'NDVI')
    uri = '/path/to/estilo.qml'
    layer1.loadNamedStyle(uri)
    root = QgsProject.instance().layerTreeRoot()
    group = root.findGroup('Raster')
    QgsMapLayerRegistry.instance().addMapLayer(layer1, False)
    group.insertChildNode(-1, QgsLayerTreeLayer(layer1))
    iface.mapCanvas().refresh()
    iface.mapCanvas().refreshAllLayers()
    composers = iface.activeComposers()
    composers[0].items()[2].setText('Test' + str(files[i]))
    c = composers[0].composition()
    c.items()[8].refreshDataDefinedProperty()
    c.items()[8].updateBoundingRect()
    c.refreshItems()

    def ExP():
        imgOut = c.printPageAsRaster (0)
        imgOut.save(os.path.join(r'/path/to/export/',aaa[i]+'.png'),"PNG")
        return

    QTimer.singleShot(2000, ExP)

    def ReM():
        QgsMapLayerRegistry.instance().removeMapLayer( layer1.id() )
        return

    QTimer.singleShot(2000, ReM)

    QgsProject.instance().clear()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.