2

I am extracting raster data using GDAL from a map that has different shades of red depending on the temperature. When I run the code within QGIS only the beginning and end of the code shows up. This is why I want to export the data into Excel, but QGIS keeps crashing when I run that part of the code. I have tried exporting the data into .csv and .txt formats but I get a Permission Denied error.

from osgeo import gdal

import pandas as pd

import openpyxl

layers=QgsProject.instance ().mapLayersByName ('1970-2000, 2.5, feb')

layer=layers [0]

ds=gdal.Open (layer.dataProvider().dataSourceUri ())

dem_arr=ds.GetRasterBand (1).ReadAsArray ()

print (dem_arr)

df=pd.DataFrame (dem_arr)

df.to_excel ("colorfirst.xlsx")

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
avinator
  • 127
  • 1
  • 6
  • 1
    Why not export it using pyqgis? I recommend this answer: https://gis.stackexchange.com/a/309117/120426 – Leo Cardona Aug 13 '20 at 21:16
  • Thank you for the response. For QgsVectorFileWriter.writeAsVectorFormat(layer, path, "utf-8", layer.crs(), 'xlsx') would I substitute the layer name as a string in place for the layer parameter. I tried this and it does not seem to work. Sorry, I am new to QGIS. – avinator Aug 13 '20 at 21:29
  • In fact, I get the error: overload 3: argument 1 has unexpected type 'QgsRasterLayer' – avinator Aug 13 '20 at 21:48
  • Sorry, the QgsVectorFileWriter class is used for vectoreal files. Would you like to export your data to xyz format (https://gdal.org/drivers/raster/xyz.html) and then to excel? – Leo Cardona Aug 13 '20 at 22:24
  • Yes, that is what I would like to do. Thanks. – avinator Aug 13 '20 at 22:27

1 Answers1

2

You can export your raster file to xyz file, which you can open from Excel. The conversion is done using GDAL alg.

import processing

layers = QgsProject.instance().mapLayersByName('1970-2000, 2.5, feb') layer = layers[0] output = '/home/grand/Desktop/QGISOutputs/colorfirst.xyz'

Export raster layer to xyz file

result = processing.run("gdal:translate", {'INPUT': layer, 'TARGET_CRS':None, 'NODATA':None, # Assign a specified nodata value to output bands. 'COPY_SUBDATASETS':False, 'OPTIONS':'', 'EXTRA':'', 'DATA_TYPE':0, 'OUTPUT': output})

print('Your file was created: {}'.format(result['OUTPUT']))

Note: Verify that the output directory exists before running the script otherwise the output file will not be created

You can also use gdal directly to do the conversion:

gdal_translate -of XYZ /home/ai/Desktop/input.tif /home/ai/Desktop/output.xyz
Leo Cardona
  • 1,363
  • 10
  • 14