def open_subarea_cb(self, *args): self.vrt_options = vrtutils.VRTCreationOptions(len(self.band_list)) if self.geocoding == 1: # get data from pixel-frame and transform lat/long # to proj and to pixels g_east = float(self.frame_dict['geodetic'][1][0].get_text()) g_west = float(self.frame_dict['geodetic'][1][1].get_text()) g_north = float(self.frame_dict['geodetic'][1][2].get_text()) g_south = float(self.frame_dict['geodetic'][1][3].get_text()) (east, north) = LatLongToGeocoord(g_east, g_north, self.input_rast) (west, south) = LatLongToGeocoord(g_west, g_south, self.input_rast) proj_rect = (east, north, west, south) (sline,spix,nlines,npix) = \ ProjRectToPixelRect(proj_rect, self.geotransform) elif self.geocoding == 2: # get data from pixel-frame and translate proj to pixels east = float(self.frame_dict['geocoord'][1][1].get_text()) west = float(self.frame_dict['geocoord'][1][3].get_text()) north = float(self.frame_dict['geocoord'][1][0].get_text()) south = float(self.frame_dict['geocoord'][1][2].get_text()) proj_rect = (east, north, west, south) (sline,spix,nlines,npix) = \ ProjRectToPixelRect(proj_rect,self.geotransform) else: # get data from pixel-frame spix = int(self.frame_dict['pixcoord'][1][1].get_text()) sline = int(self.frame_dict['pixcoord'][1][0].get_text()) npix = int(self.frame_dict['pixcoord'][1][3].get_text()) nlines = int(self.frame_dict['pixcoord'][1][2].get_text()) if spix < 0: spix = 0 elif spix > self.pixsubarea[3]: gvutils.error("Source Area does not cover required Rectangle") return if sline < 0: sline = 0 elif sline > self.pixsubarea[2]: gvutils.error("Source Area does not cover required Rectangle") return if spix + npix > self.pixsubarea[3]: npix = self.pixsubarea[3] - spix if sline + nlines > self.pixsubarea[2]: nlines = self.pixsubarea[2] - sline self.vrt_options.set_src_window((spix, sline, npix, nlines), self.band_num_list) self.vrt_options.set_dst_window((0, 0, npix, nlines)) vrt_tree = vrtutils.serializeDataset(self.input_rast, self.vrt_options, self.band_num_list) vrt_lines = gdal.SerializeXMLTree(vrt_tree) vrtdataset = gdal.Open(vrt_lines) gview.app.open_gdal_dataset(vrtdataset) self.close()
def minixml_4(): xml = """<?xml encoding="utf-8"?>\n<foo />\n""" got_xml = gdal.SerializeXMLTree(gdal.ParseXMLString(xml)) if xml != got_xml: gdaltest.post_reason('serialize xml tree failed.') print(got_xml) return 'fail' return 'success'
def minixml_2(): tree = [0,'TestDoc',[2,'style',[1,'123']],[0,'sub1'],[0,'sub2',[1,'abc']]] doc_target = '<TestDoc style="123">\n <sub1 />\n <sub2>abc</sub2>\n</TestDoc>\n' doc_got = gdal.SerializeXMLTree( tree ) if doc_got != doc_target: gdaltest.post_reason( 'serialize xml tree failed.' ) print(doc_got) return 'fail' return 'success'
def create_cb(self, *args): bands = self.input_frame.get_output_bands() if len(bands) == 0: gvutils.error('No output bands specified!') return vrtbase = [gdal.CXT_Element, 'VRTDataset'] vrtbase.append([ gdal.CXT_Attribute, 'rasterXSize', [gdal.CXT_Text, str(bands[0][0].RasterXSize)] ]) vrtbase.append([ gdal.CXT_Attribute, 'rasterYSize', [gdal.CXT_Text, str(bands[0][0].RasterYSize)] ]) # Metadata is currently taken from first output band. # This may be updatable later. mbase = vrtutils.serializeMetadata(bands[0][0]) if mbase is not None: vrtbase.append(mbase) gbase = self.geo_frame.get_geocoding() for item in gbase: vrtbase.append(item) outband = 1 for item in bands: dict = {} dict['band'] = outband dict['SourceBand'] = item[1] dict['ColorInterp'] = 'Undefined' bbase = vrtutils.serializeBand(item[0], opt_dict=dict) vrtbase.append(bbase) outband = outband + 1 vrtlines = gdal.SerializeXMLTree(vrtbase) vrtds = gdal.OpenShared(vrtlines) if args[1] == 'Save': fname = GtkExtra.file_sel_box(title="Save File") if fname is None: return driver = gdal.GetDriverByName('VRT') driver.CreateCopy(fname, vrtds) elif args[1] == 'New': self.app.new_view() self.app.open_gdal_dataset(vrtds) else: self.app.open_gdal_dataset(vrtds)
def export_cb(self, *args): ipfile = self.frame_dict['Files'].get('Input') opfile = self.frame_dict['Files'].get('Output') if os.path.isfile(opfile): resp = GtkExtra.message_box('Confirmation', opfile + ' exists. Overwrite?', ('Yes', 'No')) if resp == 'No': return elif len(opfile) == 0: gvutils.error('No output filename entered!') return use_viewscale = 0 rast = gdal.OpenShared(ipfile, gdalconst.GA_ReadOnly) if rast is None: if len(ipfile) == 0: gvutils.error('Please specify an input file!') else: gvutils.error('Unable to open ' + ipfile + ' as a GDAL supported file!') return # Catch the case where the input file consists of in-memory VRT lines # and the output format is also VRT. In this case, the new VRT would # no longer be valid once openev was exited because the input file # is not on disk (filename looks something like '<VRTDataset....'). # If the user is just exporting the file as-is, simply copying the # original lines to disk will suffice. However, if they want to # window or scale, we'd need more complicated manipulations. For now, # give an error message in that case. opformat = self.format_list[self.format_menu.get_history()] if (ipfile[0] == '<') and (opformat == 'VRT'): if self.res_list[self.res_menu.get_history()] != 'Full': msg='Only full output resolution is currently\n'+\ 'supported for export of in-memory VRTs\n'+\ 'to on-disk VRTs.' gvutils.error(msg) return if ((self.button_dict['Mode'].get_active()) and ((self.button_dict['IP_window'].get_active()) or (self.button_dict['Scale'].get_active()) or (len(self.optentry.get_text()) > 0))): msg='Scaling, windowing, and advanced creation\n'+\ 'options are not yet supported for export of \n'+\ 'in-memory VRTs to on-disk VRTs' gvutils.error(msg) return linelist = string.split(ipfile, '\n') newlinelist = [] for item in linelist: newlinelist.append(item + '\n') fh = open(opfile, 'w') fh.writelines(newlinelist) fh.close() ovrs = self._overview_list[self.overview_menu.get_history()] if ovrs != 'None': outds = gdal.OpenShared(opfile) if outds is None: gvutils.error('Error opening ' + opfile + ' for overview creation!') return progress = pguprogress.PGUProgressDialog( 'Building overviews...', cancel=gtk.TRUE) if ovrs is 'Nearest': outds.BuildOverviews("nearest", callback=progress.ProgressCB) else: outds.BuildOverviews("average_magphase", callback=progress.ProgressCB) progress.destroy() return vrt_opts = vrtutils.VRTCreationOptions(rast.RasterCount) if self._geocode_list[self.geocoding_menu.get_history()] == 'GCP': vrt_opts.set_geopref('gcps') elif self._geocode_list[ self.geocoding_menu.get_history()] == 'Geotransform': vrt_opts.set_geopref('geotransform') band_list = None # Scale the output file according to the current view's # min/max if self.button_dict['Scale'].get_active(): try: clayer = self.app.sel_manager.get_active_layer() if clayer.get_parent().get_dataset().GetDescription( ) != ipfile: wtxt = 'Input file and active layer file names do not match- may ' wtxt = wtxt + 'result in unexpected scaling!' gvutils.warning(wtxt) if gvutils.is_of_class(clayer.__class__, 'GvRasterLayer') == 0: gvutils.warning( 'Active layer is not a raster- view scaling ignored!') else: src_count = clayer.sources band_list = [] RGBAlist = ['Red', 'Green', 'Blue', 'Alpha'] for src in range(src_count): # layer sources are numbered 0...3; band sources are numbered 1,2,... src_bandnum = clayer.get_data(src).get_band_number() band_list.append(src_bandnum) vrt_opts.set_scaling( (clayer.min_get(src), clayer.max_get(src), 0, 255), (src_bandnum, )) vrt_opts.set_datatype(gdal.GDT_Byte, (src_bandnum, )) if src_count == 3: vrt_opts.set_color_interp(RGBAlist[src], (src_bandnum, )) # src_count is three even when there is an alpha channel # for rgb/rgba case if src_count == 3: try: src = 3 src_bandnum = clayer.get_data( src).get_band_number() band_list.append(src_bandnum) vrt_opts.set_scaling((clayer.min_get(src), clayer.max_get(src), 0, 255), (src_bandnum, )) vrt_opts.set_datatype(gdal.GDT_Byte, (src_bandnum, )) vrt_opts.set_color_interp(RGBAlist[src], (src_bandnum, )) except: pass use_viewscale = 1 if clayer.get_mode() == gview.RLM_COMPLEX: # This doesn't deal with complex yet... gvutils.error( 'View scaling option is not yet supported for complex data!' ) return elif rast._band[0].DataType == gdal.GDT_CInt16: # This doesn't deal with complex yet... gvutils.error( 'View scaling option is not yet supported for complex data!' ) return elif rast._band[0].DataType == gdal.GDT_CInt32: # This doesn't deal with complex yet... gvutils.error( 'View scaling option is not yet supported for complex data!' ) return elif rast._band[0].DataType == gdal.GDT_CFloat32: # This doesn't deal with complex yet... gvutils.error( 'View scaling option is not yet supported for complex data!' ) return elif rast._band[0].DataType == gdal.GDT_CFloat64: # This doesn't deal with complex yet... gvutils.error( 'View scaling option is not yet supported for complex data!' ) return except: gvutils.error( 'Unable to find active raster layer for scaling!') return # Get windowing options if self.button_dict['IP_window'].get_active(): try: spix = int(self.frame_dict['IP_window']. entry_dict['start_pix'].get_text()) sline = int(self.frame_dict['IP_window']. entry_dict['start_line'].get_text()) npix = int(self.frame_dict['IP_window'].entry_dict['num_pix']. get_text()) nlines = int(self.frame_dict['IP_window']. entry_dict['num_lines'].get_text()) if (spix < 0) or (sline < 0): gvutils.error( 'Negative start pixel and/or line! Aborting...') return if (npix + spix > rast.RasterXSize): gvutils.error( 'Window is too large (last column in input: ' + str(rast.RasterXSize) + ')! Aborting...') return if (nlines + sline > rast.RasterYSize): gvutils.error('Window is too large (last row in input: ' + str(rast.RasterYSize) + ')! Aborting...') return except: gvutils.error('Error retrieving window options! Aborting...') return else: spix = 0 sline = 0 npix = rast.RasterXSize nlines = rast.RasterYSize vrt_opts.set_src_window((spix, sline, npix, nlines)) if self.res_list[self.res_menu.get_history()] != 'Full': ovrlevel = int(self.res_list[self.res_menu.get_history()][2]) else: ovrlevel = 1 vrt_opts.set_dst_window((0, 0, npix / ovrlevel, nlines / ovrlevel)) vrt_tree = vrtutils.serializeDataset(rast, vrt_opts, band_list) vrt_lines = gdal.SerializeXMLTree(vrt_tree) vrtdataset = gdal.Open(vrt_lines) driver = gdal.GetDriverByName(opformat) # Parse creation options: optstr = string.strip(self.optentry.get_text()) if len(optstr) > 0: # should be able to deal with several # types of entries, eg. # 'TILED=YES','TFW=YES' # and # TILED=YES,TFW=YES if optstr[0] in ["'", '"']: split1 = string.split(optstr, ",") copts = [] for item in split1: if len(item) > 2: copts.append(item[1:len(item) - 1]) else: copts = string.split(optstr, ',') else: copts = [] progress = pguprogress.PGUProgressDialog('Export to ' + opfile, cancel=gtk.TRUE) progress.SetDefaultMessage("translated") outdataset = driver.CreateCopy(opfile, vrtdataset, options=copts, callback=progress.ProgressCB) if outdataset is None: progress.destroy() gvutils.error('Unable to create output file ' + opfile) return ovrs = self._overview_list[self.overview_menu.get_history()] if ovrs is 'Nearest': progress.SetDefaultMessage("overviews built") outdataset.BuildOverviews("nearest", callback=progress.ProgressCB) elif ovrs is 'Average': progress.SetDefaultMessage("overviews built") outdataset.BuildOverviews("average_magphase", callback=progress.ProgressCB) progress.destroy()
def GetVRTLines(self): """ Return lines suitable for writing to a vrt file. """ return gdal.SerializeXMLTree(self.base)