Skip to content

Instantly share code, notes, and snippets.

@timlinux
Last active February 1, 2016 12:17
Show Gist options
  • Save timlinux/f5c4c6dcbd7c0e478c52 to your computer and use it in GitHub Desktop.
Save timlinux/f5c4c6dcbd7c0e478c52 to your computer and use it in GitHub Desktop.
Simple example of how to convert a QGIS raster layer to an XYZ ascii file
from PyQt4.QtGui import QProgressBar
from PyQt4.QtCore import Qt
l = iface.activeLayer()
w = l.width()
h = l.height()
p = l.dataProvider()
# layers are base 1 for block reader
b = p.block(1, p.extent(), w, h)
f = file('/tmp/test.xyz', 'w')
f.write('Longitude,Latitude,VI')
pix_x = l.rasterUnitsPerPixelX()
pix_y = l.rasterUnitsPerPixelY()
half_x = pix_x / 2
half_y = pix_y / 2
bar = QProgressBar(None)
bar.setMaximum(h)
bar.setAlignment(Qt.AlignLeft|Qt.AlignVCenter)
progressMessageBar = iface.messageBar().createMessage("Exporting to XYZ...")
progressMessageBar.layout().addWidget(bar)
iface.messageBar().pushWidget(progressMessageBar, iface.messageBar().INFO)
extent = p.extent()
count = 0
y = extent.yMinimum()
while y < extent.yMaximum():
y += pix_y
bar.setValue(count)
count += 1
x = extent.xMinimum()
while x < extent.xMaximum():
x += pix_x
pos = QgsPoint(x - half_x, y - half_y)
result = p.identify(pos, QgsRaster.IdentifyFormatValue).results()[1]
if result > 0:
f.write('%s,%s,%i\n' % (pos.x(), pos.y(), result))
f.close()
iface.messageBar().clearWidgets()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment