I'm currently having some trouble converting a raster to an array. Ultimately I would like to convert a raster from an integer to a float32 so that I can run a gdal_calc however, I could not change the type properly in order to do this.
SO, I would appreciate any help that someone could provide. Here is my script, very short.
import gdal
import numpy as np
import math
import osgeo
import os
import scipy
# Open Rasters
hvRaster = gdal.Open("C:\\Users\\moses\\Desktop\\Calc_Test\\IMG-HV-ALOS2110871010-160611-HBQR1.5RUA.img")
vhRaster = gdal.Open("C:\\Users\\moses\\Desktop\\Calc_Test\\IMG-VH-ALOS2110871010-160611-HBQR1.5RUA.img")
# Get Raster Band
hvRasterBand = hvRaster.GetRasterBand(1)
vhRasterBand = vhRaster.GetRasterBand(1)
# Convert Raster to Array
hvArray = np.array(hvRaster.GetRasterBand(1).ReadAsArray())
vhArray = np.array(vhRaster.GetRasterBand(1).ReadAsArray())
print hvArray
print vhArray
Thank you in advance,
Moses
The method ReadAsArray() will create a numpy.ndarray with a dtype of the raster dataset. Your goal is to transform an integer dtype to a float32. The simplest way to do this is to use the astype() method for ndarray.
# Convert Raster to Array
hvArray = hvRaster.GetRasterBand(1).ReadAsArray().astype(np.float32)
vhArray = vhRaster.GetRasterBand(1).ReadAsArray().astype(np.float32)
Disclaimer: I'm the author of the following library.
lidario.Translator can help you to transform a raster into a point cloud (np.array):
import lidario as lio
# Create a Translator object which will take a tif file and return a np.array
translator = lio.Translator("geotiff", "np")
# Translate the tif file and get the np.array
point_cloud = translator.translate("/path/to/file.tif")
Lidario use GDAL under the hood.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.