def setup(numwin, fname=None): plines = gview.GvPolylines() plines.set_name("Some lines") gview.undo_register(plines) areas = gview.GvAreas() areas.set_name("Some areas") gview.undo_register(areas) if fname: raster = gview.GvRaster(fname,sample=gview.SMAverage) raster.set_name(fname) else: raster = None toolbar = Toolbar() ldlg = layerdlg.LayerDlg() ldlg.connect('destroy', gtk.mainquit) ldlg.show() for i in range(numwin): name = 'View %d' % (i+1) view = create_view(name, plines, areas, raster) toolbar.add_view(view) ldlg.add_view(name, view)
def create_new_layer(pview, player, w, h): """Creates new raster layer like <player> with width = w and height = h""" gview.app.view_manager.set_active_view(pview) pview.viewarea.set_active_layer(player) target_ds = player.get_parent().get_dataset() rl_mode_value = player.get_mode() new_layer = gview.GvRasterLayer( \ gview.GvRaster(dataset = target_ds,real=1), \ rl_mode = rl_mode_value) pview.viewarea.list_layers().append(new_layer) return new_layer
def get_classification(raster_filename, num_of_classes=10, class_type=1, band_num=1): """ gets the classification for the automatic classification routine inputs: 1)raster path string 2)number of classes 3)classification type, Choices of classifiers are between: CLASSIFY_DISCRETE = 0 CLASSIFY_EQUAL_INTERVAL = 1 CLASSIFY_QUANTILE = 2 CLASSIFY_NORM_SD = 3 4)band number to process outputs: list of classes interacts with:automatic_classification """ ds = gdal.Open(raster_filename) # Get the single band # band = ds.GetRasterBand(band_num) # Create a gview raster object from band raster = gview.GvRaster(None, ds) # Define gview layer from raster # Needed to pass to GvClassification layer = gview.GvRasterLayer(raster) classification = GvClassification(layer) # classification.set_classify_property(layer,str(class_type)) classification.set_type(class_type) # use default classification with number of classes # defined at input classification.prepare_default(num_of_classes) # list for holding the classes cls = [] # cycle through the classes and add them to the cls list for cls_in in range(num_of_classes): cls.append(classification.get_range(cls_in)) return cls
def plot3d(data=None, xvec=None, yvec=None, xaxis=None, yaxis=None, zaxis=None, xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None, title=None, cmds=None, terminal='openev', output=None, plottype="parametric", wintitle=None): """plot3d(data [,xvec=xaxis_values] [,yvec=yaxis_values] [, xaxis=text] [,yaxis=text] [,zaxis=text] [,title=text] [, xmin=n, xmax=n] [, ymin=n, ymax=n] [, zmin=n, zmax=n] [, cmds=cmd_list] [,terminal={"openev","gnuplot","rasterlayer"}] [, output=ps_filename] [,plottype = {"parametric","contour"}] [, wintitle=text]) data -- data array to plot, should be 2-D set of Z values. Size of data should be length(x) x length(y), if x and y are present.' xvec -- 1-D Vector of values for axis of first dimension of data. yvec -- 1-D Vector of values for axis of second dimension of data. """ ########################################################################### # Print usage() message if no options given. if data is None: print 'Usage: plot3d(data [,xvec=xaxis_values] [,yvec=yaxis_values] ' print ' [, xaxis=text] [,yaxis=text] [,zaxis=text] [,title=text] ' print ' [, xmin=n, xmax=n] [, ymin=n, ymax=n] [, zmin=n, zmax=n] ' print ' [, cmds=cmd_list] [,terminal={"openev","gnuplot,"rasterlayer"}]' print ' [, output=ps_filename] [,plottype = {"parametric","contour"}]' print '' print ' data -- data array to plot, should be 2-D set of Z values.' print ' Size of data should be length(x) x length(y), if x' print ' and y are present.' print ' xvec -- 1-D Vector of values for axis of first dimension of data.' print ' yvec -- 1-D Vector of values for axis of second dimension of data.' print '' return ########################################################################### # Work out the shape of the data. A 1-D array is assumed to be Y # values. An Nx2 array is assumed to be (X,Y) values. All others are # currently invalid. try: dshape = Numeric.shape(data) except: raise ValueError, "data argument to plot() does not appear to be a NumPy array" ########################################################################## # Make sure xvec, yvec are valid indices for x/y axis and revert to # default if not. if xvec is None: xvec = Numeric.arange(dshape[0]) else: try: xshape = Numeric.shape(xvec) if (len(xvec) != dshape[0]): print 'Incorrect length for xvec- reverting to default.' xvec = Numeric.arange(dshape[0]) elif (len(xshape) > 1): print 'xvec should be 1-D- reverting to default.' xvec = Numeric.arange(dshape[0]) except: print 'xvec appears not to be a NumPy array- reverting to default.' xvec = Numeric.arange(dshape[0]) if yvec is None: yvec = Numeric.arange(dshape[1]) else: try: yshape = Numeric.shape(yvec) if (len(yvec) != dshape[1]): print 'Incorrect length for yvec- reverting to default.' yvec = Numeric.arange(dshape[1]) elif (len(yshape) > 1): print 'yvec should be 1-D- reverting to default.' yvec = Numeric.arange(dshape[1]) except: print 'yvec appears not to be a NumPy array- reverting to default.' yvec = Numeric.arange(dshape[1]) ########################################################################### # Setup Plot Options. g = llplot() g.batch = 1 if plottype == "contour": g.add_cmd('set nosurface') g.add_cmd('set contour') g.add_cmd('set view 0,0') g.add_cmd('set data style lines') g.add_cmd('set cntrparam levels 15') else: # g.add_cmd('set parametric') g.add_cmd('set data style lines') g.add_cmd('set hidden3d') if xaxis is not None: g.add_cmd('set xlabel "%s"' % xaxis) if yaxis is not None: g.add_cmd('set ylabel "%s"' % yaxis) if title is not None: g.add_cmd('set title "%s"' % title) if xmin is not None and xmax is not None: g.add_cmd('set xrange [%s:%s]' % (str(xmin), str(xmax))) if ymin is not None and ymax is not None: g.add_cmd('set yrange [%s:%s]' % (str(ymin), str(ymax))) if plottype != "contour": if zaxis is not None: g.add_cmd('set zlabel "%s"' % zaxis) if plottype != "contour": if zmin is not None and zmax is not None: g.add_cmd('set zrange [%s:%s]' % (str(zmin), str(zmax))) if cmds is not None: for cmd in cmds: g.add_cmd(cmd) ########################################################################### # Attach the data. # # Note that we emit the x and y values with each data point. It would # be nice to rewrite this to use binary format eventually. tup_data = [] for x_i in range(len(xvec)): for y_i in range(len(yvec)): tup_data.append((xvec[x_i], yvec[y_i], data[x_i][y_i])) g.set_data(tup_data, dimension=3, xlen=len(xvec)) ########################################################################### # Generate output. if terminal == 'gnuplot': g.batch = 0 g.plot_current() raw_input('Please press return to continue...\n') elif terminal == 'postscript': if (os.name == 'nt'): output = string.join(string.split(output, '\\'), '/') g.add_cmd('set terminal postscript color 10') g.add_cmd("set output '%s'" % output) g.plot_current() else: import gdal import gdalnumeric import time import gview temp_file = gvutils.tempnam() g.add_cmd('set terminal pbm color') g.add_cmd("set output '%s'" % temp_file) g.plot_current() image = gdalnumeric.LoadFile(temp_file) image_ds = gdalnumeric.OpenArray(image) try: os.unlink(temp_file) except: pass rlayer = gview.GvRasterLayer(gview.GvRaster(dataset=image_ds, real=1), rl_mode=gview.RLM_RGBA) rlayer.set_source(1, gview.GvRaster(dataset=image_ds, real=2)) rlayer.set_source(2, gview.GvRaster(dataset=image_ds, real=3)) if terminal == 'rasterlayer': return rlayer graphwin = GvGraphWindow(rlayer) if wintitle is not None: graphwin.set_title(wintitle)
def plot(data=None, xaxis=None, yaxis=None, xmin=None, xmax=None, ymin=None, ymax=None, title=None, cmds=None, terminal='openev', output=None, wintitle=None, datastyle=None, multiplot=False, multilabels=(), multiopts=()): """plot(data [, xaxis=text] [,yaxis=text] [,title=text] [, xmin=n] [, xmax=n] [, ymin=n] [, ymax=n] [, cmds=cmd_list] [,terminal={"openev","gnuplot"}] [, wintitle=text] [, datastyle=text] [, multiplot = {True,False}] [, multilabels = list] [, multiopts = list] data -- data array to plot, should be 1-D set of Y data or 2-D array with pairs of (x,y) values. or 3-D array with pairs of (x,y,z) values ' or 2-D array with tuples of (x,y1,y2,...,yN) values.' """ ########################################################################### # Print usage() message if no options given. if data is None: print 'Usage: plot(data [, xaxis=text] [,yaxis=text] [,title=text] ' print ' [, xmin=n] [, xmax=n] [, ymin=n] [, ymax=n] ' print ' [, cmds=cmd_list] ' print ' [,terminal={"openev","gnuplot"}]' print ' [,wintitle=text] [, datastyle=text] ' print ' [, multiplot = {True,False}]' print ' [, multilabels = list] [, multiopts = list] )' print '' print ' data -- data array to plot, should be 1-D set of Y data' print ' or 2-D array with pairs of (x,y) values.' print ' or 3-D array with pairs of (x,y,z) values ' print ' or 2-D array with tuples of (x,y1,y2,...,yN) values.' print ' for the last multiplot must be true, multilables is' print ' a list of text labels for the graphs, and multiopts' print ' is a list of gnuplot options to be added to the' print ' individual graphs' print '' return ########################################################################### # Work out the shape of the data. A 1-D array is assumed to be Y # values. An Nx2 array is assumed to be (X,Y) values. A 3-D array is # assumed to be (X,Y,Z) values. If multiplot is True we need # a Nxk array, with K at least 2 try: dshape = Numeric.shape(data) except: raise ValueError, "data argument to plot() does not appear to be a NumPy array" dim = len(dshape) ########################################################################### # Reformat the list into a uniform Nx2 format. if multiplot == False: if dim == 1: dim = 2 list = [] for i in range(len(data)): list.append((i, data[i])) data = list elif dim == 2 and dshape[1] == 2 and dshape[0] > 1: pass else: raise ValueError, "data argument dimension or shape is not supported." else: #error checking for multiplot needs work if dim > 1: pass else: raise ValueError, "multiplot dimension too small" ########################################################################### # Setup Plot Options. g = llplot() if datastyle is not None: cmd = 'set data style ' + str(datastyle) g.add_cmd(cmd) else: g.add_cmd('set data style linespoints') if xaxis is not None: g.add_cmd('set xlabel "%s"' % xaxis) if yaxis is not None: g.add_cmd('set ylabel "%s"' % yaxis) if title is not None: g.add_cmd('set title "%s"' % title) if xmin is not None and xmax is not None: g.add_cmd('set xrange [%s:%s]' % (str(xmin), str(xmax))) if ymin is not None and ymax is not None: g.add_cmd('set yrange [%s:%s]' % (str(ymin), str(ymax))) if cmds is not None: for cmd in cmds: g.add_cmd(cmd) g.set_data(data, '', dim, 1, multiplot, multilabels, multiopts) ########################################################################### # Generate output. if terminal == 'gnuplot': g.batch = 0 g.plot_current() raw_input('Please press return to continue...\n') return elif terminal == 'postscript': g.batch = 1 #if (os.name == 'nt'): # output = string.join(string.split(output,'\\'),'/') g.add_cmd('set terminal postscript color 10') g.add_cmd("set output '%s'" % output) g.plot_current() return elif terminal == 'pbm': g.batch = 1 g.add_cmd('set terminal pbm color') g.add_cmd("set output '%s'" % output) g.plot_current() return elif terminal == 'xpm': import gdal import time g.batch = 1 out_temp = gvutils.tempnam(extension='png') g.add_cmd('set terminal png') g.add_cmd("set output '%s'" % out_temp) g.plot_current() pngDS = gdal.Open(out_temp) if pngDS is None: return None xpmDriver = gdal.GetDriverByName('XPM') if xpmDriver is None: return None xpmDriver.CreateCopy(output, pngDS, 0) pngDS = None os.unlink(out_temp) return else: import gdal import gdalnumeric import time import gview g.batch = 1 temp_file = gvutils.tempnam() # make sure the file has been created create_temp = open(temp_file, 'w') create_temp.close() g.add_cmd('set terminal pbm color') g.add_cmd("set output '%s'" % temp_file) g.plot_current() time.sleep(1) image = gdalnumeric.LoadFile(temp_file) image_ds = gdalnumeric.OpenArray(image) try: os.unlink(temp_file) except: pass rlayer = gview.GvRasterLayer(gview.GvRaster(dataset=image_ds, real=1), rl_mode=gview.RLM_RGBA) rlayer.set_source(1, gview.GvRaster(dataset=image_ds, real=2)) rlayer.set_source(2, gview.GvRaster(dataset=image_ds, real=3)) if terminal == 'rasterlayer': return rlayer graphwin = GvGraphWindow(rlayer) if wintitle is not None: graphwin.set_title(wintitle)
def update_roi_view(self,*args): # Shouldn't get here if inactive anyway, but just in case... if (self.RP_ToolDlg.is_active() == gtk.FALSE): return # Update view based on new frame values line = int(float(self.RP_ToolDlg.entry_dict['start_line'].get_text())) pix = int(float(self.RP_ToolDlg.entry_dict['start_pix'].get_text())) sl = int(float(self.RP_ToolDlg.entry_dict['num_lines'].get_text())) sp = int(float(self.RP_ToolDlg.entry_dict['num_pix'].get_text())) # Find the view and layer cview = self.app.view_manager.get_active_view_window().title clayer = self.app.sel_manager.get_active_layer() if (cview is None) or (clayer is None): # Target can only be extracted if a view/layer is selected return if (sl == 0 or sp == 0): print "Trying to extract region with zero lines or zero pixels!" return try: filename = clayer.get_parent().get_dataset().GetDescription() except: gvutils.error('Unable to determine filename!') return try: target_data = gdalnumeric.LoadFile(filename,pix,line,sp,sl) target_ds = gdalnumeric.OpenArray(target_data) rl_mode_value = clayer.get_mode() except: gvutils.error('Unable to extract data and/or display mode info!') return if self.target_view_window is not None: # Need to delete old layer in target window and put in new one if self.target_view_layer is not None: self.target_view_window.viewarea.remove_layer(self.target_view_layer) # Create new layer self.target_view_data = target_data self.target_view_ds = target_ds self.target_view_layer = \ gview.GvRasterLayer(gview.GvRaster(dataset = self.target_view_ds,real=1), rl_mode = rl_mode_value) if ((rl_mode_value == gview.RLM_RGBA) and (self.target_view_ds.RasterCount > 2)): green_raster = gview.GvRaster(dataset = self.target_view_ds,real=2) blue_raster = gview.GvRaster(dataset = self.target_view_ds,real=3) self.target_view_layer.set_source(1,green_raster) self.target_view_layer.set_source(2,blue_raster) if self.target_view_ds.RasterCount > 3: band = self.target_view_ds.GetRasterBand(4) if band.GetRasterColorInterpretation() == gdal.GCI_AlphaBand: self.target_view_layer.blend_mode_set( gview.RL_BLEND_FILTER ) alpha_raster = gview.GvRaster(dataset = self.target_view_ds,real=4) self.target_view_layer.set_source(3,alpha_raster) self.target_view_layer.set_name(filename) refresh_old_window = 0 # redraw roi first time if self.target_view_window is None: # Need to create a window to display the current target in import gvviewwindow self.target_view_window = gvviewwindow.GvViewWindow(self.app, title=self.target_view_title,show_menu = 0, show_icons=0, show_tracker=1,show_scrollbars=1) self.target_view_window.connect('destroy',self.close_target_view_cb) refresh_old_window = 1 self.target_view_window.viewarea.add_layer(self.target_view_layer) self.target_view_window.show() # The roi must be redrawn on the overview if a new window was created # (it will have disappeared) # HACK!!! if refresh_old_window == 1: view_list = self.app.view_manager.get_views() for item in view_list: if (item.title == cview): self.app.view_manager.set_active_view(item) item.viewarea.set_active_layer(clayer) self.app.toolbar.roi_tool.append((pix,line,sp,sl))