def load_band(self): file_count = self.ui.listWidget_Layers.count() if file_count < 1: sys.stderr.write('Error: No input files, open a raster file first!\n') else: if self.ui.comboBands.currentText() == 'Band #': sys.stderr.write('Select which band number to load.\n') else: band_num = int(self.ui.comboBands.currentText()) fname = self.ui.listWidget_Layers.currentItem().text() fname_Str = str(fname) basename = os.path.basename(fname_Str) basename = os.path.splitext(basename) basename = basename[0] cleaname_a = string.replace(basename, '.', '_') cleaname = string.replace(cleaname_a, '-', '_') newname = cleaname+'_'+str(band_num) rasterpointer = rasterIO.opengdalraster(fname_Str) global driver, XSize, YSize, proj, geotrans global bandname bandname = newname globals()[bandname] = rasterIO.readrasterband(rasterpointer, band_num) driver, XSize, YSize, proj, geotrans = rasterIO.readrastermeta(rasterpointer) self.ui.textEqEdit.insertPlainText(bandname+" ") sys.stdout.write("Loaded: ") sys.stdout.write(str(fname_Str)) sys.stdout.write(", band: ") sys.stdout.write(str(band_num)) sys.stdout.write("\n") self.ui.textPyout.insertPlainText('# open a file pointer\n') self.ui.textPyout.insertPlainText('rasterpointer = rasterIO.opengdalraster("%s")\n' %(fname_Str)) self.ui.textPyout.insertPlainText('# read a raster band\n') self.ui.textPyout.insertPlainText('%s = rasterIO.readrasterband(rasterpointer, %i)\n' %(bandname, band_num)) self.ui.textPyout.insertPlainText('# get file metadata: format, X, Y, projection, geo-parameters\n') self.ui.textPyout.insertPlainText('driver, XSize, YSize, proj, geotrans = rasterIO.readrastermeta(rasterpointer)\n\n')
def SaveMasiveValues(outfilename,fileLst, pos, band=1): ''' Recibe: :outfilename: nombre de archivo csv de salida :fileLst: lista de archivos a procesar :pos: dict de puntos de observación del tipo {"Santo Domingo": [-31.117368, -60.883001],...} :band: banda donde extraer los valores Escribe en outfilename (formato csv) los valores extraidos por cada archivo en fileLst para cada punto en pos ''' header1 = ['filename'] + pos.keys() header2 = [''] + [str(pos[k][0])+','+str(pos[k][1]) for k in pos.keys()] with open(outfilename, 'wb') as csvfile: spamwriter = csv.writer(csvfile, dialect='excel', delimiter=';', quotechar='|', quoting=csv.QUOTE_MINIMAL) spamwriter.writerow(header1) spamwriter.writerow(header2) for fn in fileLst: file = rasterIO.opengdalraster(fn) driver, Nx, Ny, NBand, proj, geo = rasterIO.readrastermeta(file) lon0,lat0,dlon,dlat = geo[0],geo[3],geo[1],geo[5] etrMap = rasterIO.readrasterband(file, band) csvrow = [fn] for po in pos.keys(): row,col = getRowCol(pos[po][0],pos[po][1],lat0,lon0,dlat,dlon) csvrow += [GetValidValue(etrMap,row,col,Nx,Ny)] spamwriter.writerow(csvrow)
def SaveMasiveValues(outfilename, fileLst, pos, band=1): ''' Recibe: :outfilename: nombre de archivo csv de salida :fileLst: lista de archivos a procesar :pos: dict de puntos de observación del tipo {"Santo Domingo": [-31.117368, -60.883001],...} :band: banda donde extraer los valores Escribe en outfilename (formato csv) los valores extraidos por cada archivo en fileLst para cada punto en pos ''' header1 = ['filename'] + pos.keys() header2 = ['' ] + [str(pos[k][0]) + ',' + str(pos[k][1]) for k in pos.keys()] with open(outfilename, 'wb') as csvfile: spamwriter = csv.writer(csvfile, dialect='excel', delimiter=';', quotechar='|', quoting=csv.QUOTE_MINIMAL) spamwriter.writerow(header1) spamwriter.writerow(header2) for fn in fileLst: file = rasterIO.opengdalraster(fn) driver, Nx, Ny, NBand, proj, geo = rasterIO.readrastermeta(file) lon0, lat0, dlon, dlat = geo[0], geo[3], geo[1], geo[5] etrMap = rasterIO.readrasterband(file, band) csvrow = [fn] for po in pos.keys(): row, col = getRowCol(pos[po][0], pos[po][1], lat0, lon0, dlat, dlon) csvrow += [GetValidValue(etrMap, row, col, Nx, Ny)] spamwriter.writerow(csvrow)
def onOpenFile(self, event): # Show in status bar and log self.filename = self.m_btn_file.GetPath() self.m_txt_log.AppendText("#### Opened File #### \n" + self.filename) self.m_statusBar.SetStatusText(self.filename) # Load image with PyRaster self.file_pointer = rasterIO.opengdalraster(self.filename) driver, self.XSize, self.YSize, self.NBand, proj_wkt, geo = rasterIO.readrastermeta( self.file_pointer) self.lon0, self.lat0, self.dlon, self.dlat = geo[0], geo[3], geo[ 1], geo[5] # Clean band combobox, and load existing bands (Default band: 1) self.m_cmb_band.Clear() bands = [str(b) for b in range(1, self.NBand + 1)] self.m_cmb_band.AppendItems(bands) self.m_cmb_band.SetValue('1') # Get selected band self.data = rasterIO.readrasterband(self.file_pointer, int(self.m_cmb_band.GetValue())) self.data = self.data.astype(np.float32) # Create figure with the colormap selected self.m_figure.clear() self.ax = self.m_figure.add_subplot(111) eval("self.ax.imshow(self.data, cmap = cm." + self.m_cmb_colormap.GetValue() + ")") # Latitude and longitude range max_lat = self.lat0 + self.YSize * self.dlat max_lon = self.lon0 + self.XSize * self.dlon # Show and Log figure metadata sms = "\n+ Metadata \n " + proj_wkt + "\n" sms += " - Size = " + str(self.YSize) + "," + str(self.XSize) + "\n" sms += " - Delta latitude = " + str( self.dlat) + "\n - Delta longitude = " + str(self.dlon) + "\n" sms += " - Latitude limits: \n" sms += " from = " + str(self.lat0) + "\n" sms += " to = " + str(max_lat) + "\n" sms += " - Longitude limits: \n" sms += " from = " + str(self.lon0) + "\n" sms += " to = " + str(max_lon) + "\n" self.m_txt_log.AppendText(sms) self.m_txt_log.ShowPosition(self.m_txt_log.GetLastPosition()) # Set axes labels self.ax.set_xlabel('Col (Lon)') self.ax.set_ylabel('Row (Lat)') # Draw figure self.ax.grid(True) self.m_canvas.draw()
def onOpenFile( self, event ): # Show in status bar and log self.filename = self.m_btn_file.GetPath() self.m_txt_log.AppendText("#### Opened File #### \n"+self.filename) self.m_statusBar.SetStatusText(self.filename) # Load image with PyRaster self.file_pointer = rasterIO.opengdalraster(self.filename) driver, self.XSize, self.YSize, self.NBand, proj_wkt, geo = rasterIO.readrastermeta(self.file_pointer) self.lon0,self.lat0,self.dlon,self.dlat = geo[0],geo[3],geo[1],geo[5] # Clean band combobox, and load existing bands (Default band: 1) self.m_cmb_band.Clear() bands = [str(b) for b in range(1,self.NBand+1)] self.m_cmb_band.AppendItems(bands) self.m_cmb_band.SetValue('1') # Get selected band self.data = rasterIO.readrasterband(self.file_pointer, int(self.m_cmb_band.GetValue())) self.data = self.data.astype(np.float32) # Create figure with the colormap selected self.m_figure.clear() self.ax = self.m_figure.add_subplot(111) eval("self.ax.imshow(self.data, cmap = cm."+self.m_cmb_colormap.GetValue()+")") # Latitude and longitude range max_lat = self.lat0 + self.YSize*self.dlat max_lon = self.lon0 + self.XSize*self.dlon # Show and Log figure metadata sms = "\n+ Metadata \n " + proj_wkt +"\n" sms += " - Size = " + str(self.YSize) + "," + str(self.XSize) + "\n" sms += " - Delta latitude = " + str(self.dlat) + "\n - Delta longitude = " + str(self.dlon) + "\n" sms += " - Latitude limits: \n" sms += " from = "+ str(self.lat0) + "\n" sms += " to = "+ str(max_lat) + "\n" sms += " - Longitude limits: \n" sms += " from = "+ str(self.lon0) + "\n" sms += " to = "+ str(max_lon) + "\n" self.m_txt_log.AppendText(sms) self.m_txt_log.ShowPosition( self.m_txt_log.GetLastPosition()) # Set axes labels self.ax.set_xlabel('Col (Lon)') self.ax.set_ylabel('Row (Lat)') # Draw figure self.ax.grid(True) self.m_canvas.draw()
def load_band(self): file_count = self.ui.listWidget_Layers.count() if file_count < 1: sys.stderr.write( 'Error: No input files, open a raster file first!\n') else: if self.ui.comboBands.currentText() == 'Band #': sys.stderr.write('Select which band number to load.\n') else: band_num = int(self.ui.comboBands.currentText()) fname = self.ui.listWidget_Layers.currentItem().text() fname_Str = str(fname) basename = os.path.basename(fname_Str) basename = os.path.splitext(basename) basename = basename[0] cleaname_a = string.replace(basename, '.', '_') cleaname = string.replace(cleaname_a, '-', '_') newname = cleaname + '_' + str(band_num) rasterpointer = rasterIO.opengdalraster(fname_Str) global driver, XSize, YSize, proj, geotrans global bandname bandname = newname globals()[bandname] = rasterIO.readrasterband( rasterpointer, band_num) driver, XSize, YSize, proj, geotrans = rasterIO.readrastermeta( rasterpointer) self.ui.textEqEdit.insertPlainText(bandname + " ") sys.stdout.write("Loaded: ") sys.stdout.write(str(fname_Str)) sys.stdout.write(", band: ") sys.stdout.write(str(band_num)) sys.stdout.write("\n") self.ui.textPyout.insertPlainText('# open a file pointer\n') self.ui.textPyout.insertPlainText( 'rasterpointer = rasterIO.opengdalraster("%s")\n' % (fname_Str)) self.ui.textPyout.insertPlainText('# read a raster band\n') self.ui.textPyout.insertPlainText( '%s = rasterIO.readrasterband(rasterpointer, %i)\n' % (bandname, band_num)) self.ui.textPyout.insertPlainText( '# get file metadata: format, X, Y, projection, geo-parameters\n' ) self.ui.textPyout.insertPlainText( 'driver, XSize, YSize, proj, geotrans = rasterIO.readrastermeta(rasterpointer)\n\n' )
""" Created on Thu Jul 4 11:34:20 2013 @author: emiliano """ import rasterIO import numpy as np #from mayavi import mlab import matplotlib.pyplot as plt import matplotlib.cm as cm # ruta de la imagen filename_img = '2000073-et.img' file_pointer = rasterIO.opengdalraster(filename_img) driver, XSize, YSize, proj_wkt, geo_t_params = rasterIO.readrastermeta(file_pointer) # en data tengo la matriz que representa la imagen data = rasterIO.readrasterband(file_pointer, 1) data = data.astype(np.float32) # Podria recortarla #data = data[0:500, 1500:2000] #Algunos Otros mapas de color: Greys_r,Blues, hsv plt.imshow(data, cmap = cm.hot) del data plt.show() #mlab.figure(size=(400, 320), bgcolor=(0.16, 0.28, 0.46)) #mlab.surf(data, colormap='hot')#,warp_scale=0.5) #vmin=1200, vmax=1610)
def processfunction(file_list): # Create a loop for all files in current directory for file in file_list: # Check file type (in this case Geotiff) if file.endswith('.tif'): # Open a pointer to the file pointer = rasterIO.opengdalraster(file) # Read the raster metadata for the new output file driver, XSize, YSize, proj_wkt, geo_t_params = rasterIO.readrastermeta(pointer) # Read the first band to a matrix called band_1 band_1 = rasterIO.readrasterband(pointer, 1) # Read the second band to a matrix called band_2 band_2 =rasterIO.readrasterband(pointer, 2) # Perform the NDVI calculation and put the results into a new matrix new_ndvi_band = ((band_2 - band_1) / (band_2 + band_1)) # Get the input file filename without extension and create a new file name parts =string.split(file) newname = './'+parts[0]+'_ndvi.tif' # ./filename_ndvi.tif # Get the EPSG code from well known text projection epsg = rasterIO.wkt2epsg(proj_wkt) # Write the NDVI matrix to a new raster file rasterIO.writerasterband(new_ndvi_band, newname, XSize, YSize, geo_t_params, epsg) # loop will now go to next file in input list # Create a run function to accept jobs from queue def processRun(q, filename): q.put(processfunc(filename)) # Create the main function def main(arg=sys.argv): # Get a list fo files in the current directory (assumed to contain raster data) file_list = os.listdir(os.getcwd()) # Get the length of the file list len_flist = len(file_list) half_len = len_flist / 2 # Create a queue object q = Queue() # Create two processes (add more depending on processor availability) p1 = Process(target=processRun, args=(q, flist[:half_len])) p2 = Process(target=processRun, args=(q, flist[half_len:])) # Start processes p1.start() p2.start() # Standard Python script execution/exit handling if __name__=='__main__': sys.exit(main())
# Change to data directory os.chdir('/user/data/') # Get a list of files in current directory # Create a loop for all files in current directory for file in flist: # Check file type (in this case Geotiff) if file.endswith('.tif'): # Open a pointer to the file pointer = rasterIO.opengdalraster(file) # Read the raster metadata for the new output file driver, XSize, YSize, proj_wkt, geo_t_params = rasterIO.readrastermeta( pointer) # Read the first band to a matrix called band_1 band_1 = rasterIO.readrasterband(pointer, 1) # Read the second band to a matrix called band_2 band_2 = rasterIO.readrasterband(pointer, 2) # Perform the NDVI calculation and put the results into a new matrix new_ndvi_band = ((band_2 - band_1) / (band_2 + band_1)) # Get the input file filename without extension and create a new file name parts = string.split(file) newname = './' + parts[0] + '_ndvi.tif' # ./filename_ndvi.tif # Get the EPSG code from well known text projection
#Read a raster file # Import the rasterIO module import rasterIO # Open a gdal pointer to a file on disk file_pointer = rasterIO.opengdalraster( '/path/surface_temperature_kelvin.tif') # Get the spatial reference information from the image drive, XSize, YSize, proj_wkt, geo_t_params = rasterIO.readrastermeta(pointer) # Read a band from the file to a new matrix in memory, #the number indicates which band to read. kelvin_band = rasterIO.readrasterband(file_pointer, 1)