def create_view(name, plines, areas, raster): win = gtk.GtkWindow() win.set_title(name) win.set_policy(gtk.TRUE, gtk.TRUE, gtk.FALSE) shell = gtk.GtkVBox() win.add(shell) view = gview.GvViewArea() view.size(512,512) shell.pack_start(view, expand=gtk.TRUE) if raster: raster_layer = gview.GvRasterLayer(raster) view.add_layer(raster_layer) view.add_layer(gview.GvPqueryLayer()) view.add_layer(gview.GvAreaLayer(areas)) view.add_layer(gview.GvLineLayer(plines)) statusbar = gtk.GtkHBox() shell.pack_start(statusbar, expand=gtk.FALSE) label = gtk.GtkLabel() statusbar.pack_start(label, expand=gtk.FALSE, padding=3) tracker = gview.GvTrackTool(label) tracker.activate(view) view.connect('key-press-event', testmain_button_press) win.show_all() view.grab_focus() win.connect('delete-event', gtk.mainquit) gtk.quit_add_destroy(1, win) return 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 setup_playing(self, *args): if self.view is not None: self.tool.deactivate(self.view) for view in self.app.view_manager.view_list: if view.title == self.viewtitle: self.app.view_manager.set_active_view(view) self.view = view.viewarea self.tool.activate(self.view) self.tool.register_view(self.second_view, 0, 1, self.trail_menu.get_history()) self.tool.set_trail_color(self.second_view, self.trail_color.current_color[0], self.trail_color.current_color[1], self.trail_color.current_color[2], self.trail_color.current_color[3]) # update the secondary view with a background raster plyr = self.view.active_layer() rst = None ds = None try: rst = plyr.get_parent() ds = rst.get_dataset() except: llist = self.view.list_layers() llist.reverse() for plyr in llist: try: rst = plyr.get_parent() ds = rst.get_dataset() break except: pass if ds is None: gvutils.error('Error- no raster to pan over in active view!') return dtype = gdal.GetDataTypeName(ds.GetRasterBand(1).DataType) xsize = ds.RasterXSize ysize = ds.RasterYSize while (xsize > 512) and (ysize > 512): xsize = xsize / 2 ysize = ysize / 2 srcrect = [0, 0, ds.RasterXSize, ds.RasterYSize] dstrect = [0, 0, xsize, ysize] vrt = vrtutils.VRTDatasetConstructor(xsize, ysize) fname = ds.GetDescription() lyrs = self.second_view.list_layers() for lyr in lyrs: self.second_view.remove_layer(lyr) gcps = ds.GetGCPs() if len(gcps) > 0: vrt.SetGCPs(gcps, ds.GetGCPProjection(), None, srcrect, dstrect) else: gt = ds.GetGeoTransform() if gt != (0.0, 1.0, 0.0, 0.0, 0.0, 1.0): vrt.SetSRS(ds.GetProjection()) vrt.SetGeoTransform(gt, srcrect, dstrect, 1) for idx in range(0, plyr.sources): rst = plyr.get_data(idx) if rst is not None: cmin = plyr.min_get(idx) cmax = plyr.max_get(idx) srcdiff = cmax - cmin if abs(srcdiff) > 0.0: ratio = 255 / srcdiff else: ratio = 1.0 offset = -cmin * ratio vrt.AddSimpleBand(fname, rst.get_band_number(), dtype, srcrect, dstrect, ScaleOffset=offset, ScaleRatio=ratio) ds2 = gview.manager.get_dataset(vrt.GetVRTString()) raster = gview.manager.get_dataset_raster(ds2, 1) options = [] if (ds2.RasterCount == 1): raster_layer = gview.GvRasterLayer(raster, options, rl_mode=gview.RLM_AUTO) else: raster_layer = gview.GvRasterLayer(raster, options, rl_mode=gview.RLM_RGBA) if (raster_layer.get_mode() == gview.RLM_RGBA): green_raster = gview.manager.get_dataset_raster(ds2, 2) raster_layer.set_source(1, green_raster) if (ds2.RasterCount > 2): blue_raster = \ gview.manager.get_dataset_raster( ds2, 3 ) raster_layer.set_source(2, blue_raster) if (ds2.RasterCount > 3): band = ds2.GetRasterBand(4) if (band.GetRasterColorInterpretation() == gdal.GCI_AlphaBand): raster_layer.blend_mode_set(gview.RL_BLEND_FILTER) alpha_raster = \ gview.manager.get_dataset_raster( ds2, 4 ) raster_layer.set_source(3, alpha_raster) self.second_view.add_layer(raster_layer) self.active = 1 xmin, ymin, xmax, ymax = self.view.get_extents() xwidth = xmax - xmin ywidth = ymax - ymin self.ext = (xmin, ymin, xwidth, ywidth) self.tool.set_extents((xmin, ymin, xwidth, ywidth)) self.playing = 1 self.tool.set_speed(self.speed) self.block_size_changed() self.overlap_changed() self.tool.play()
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 load_active(self, *args): layer = gview.app.sel_manager.get_active_layer() if (layer is None) or (gvutils.is_of_class(layer.__class__, 'GvRasterLayer') == 0): gvutils.warning( 'Please select a raster layer using the layer dialog.\n') return layer_ds = layer.get_parent().get_name()[:-2] ds = gdal.OpenShared(layer_ds) gview.manager.add_dataset(ds) if ds.RasterCount == 3: rlayer1 = gview.manager.get_dataset_raster(ds, 1) rlayer2 = gview.manager.get_dataset_raster(ds, 2) rlayer3 = gview.manager.get_dataset_raster(ds, 3) raster = gview.GvRasterLayer(rlayer1) ras_copy = gview.GvRasterLayer(rlayer1) raster.set_source(1, rlayer2) raster.set_source(2, rlayer3) ras_copy.set_source(1, rlayer2) ras_copy.set_source(2, rlayer3) else: rlayer = gview.manager.get_dataset_raster(ds, 1) raster = gview.GvRasterLayer(rlayer) ras_copy = gview.GvRasterLayer(rlayer) raster.set_name('RASTER') ras_copy.set_name('RASTER') oldras1 = self.viewarea1.get_named_layer('RASTER') oldras2 = self.viewarea2.get_named_layer('RASTER') if oldras1 is not None: self.viewarea1.remove_layer(oldras1) self.viewarea2.remove_layer(oldras2) #check for lut: lut_name = os.path.splitext(layer_ds)[0] + '.lut' if os.path.isfile(lut_name): lut_file = open(lut_name, 'rb') lut = '' lut = lut_file.read() #print 'loading:', len(lut) if lut: for isrc in range(raster.sources): #(smin, smax) = raster_layer.autoscale( isource=isrc, viewonly = 1 ) #print (smin,smax) raster.set_source(isrc, raster.get_data(isrc), 0, 255, raster.get_const_value(isrc), lut, raster.nodata_get(isrc)) ras_copy.set_source(isrc, ras_copy.get_data(isrc), 0, 255, ras_copy.get_const_value(isrc), lut, ras_copy.nodata_get(isrc)) lut_file.close() #check for bcg: bcg_name = os.path.splitext(layer_ds)[0] + '.bcg' if os.path.isfile(bcg_name): bcg_file = open(bcg_name, 'r') bcg = '' bcg = bcg_file.readline() bcg = bcg.replace('\n', '') bcg_file.close() values = bcg.split(',') self.bright_adjustment.set_value(float(values[0])) self.contrast_adjustment.set_value(float(values[1])) self.gamma_adjustment.set_value(float(values[2])) self.viewarea1.add_layer(raster) self.viewarea1.set_active_layer(raster) self.viewarea2.add_layer(ras_copy) self.viewarea2.set_active_layer(ras_copy)
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))