Esempio n. 1
0
    def new_layer_unselected_cb(self,*args):
        """ Create new layer of only selected shapes """

        unselected=self.pgugrid.get_unselected_row_indices()

        if len(unselected) == 0:
            gvutils.warning('No rows unselected- ignoring!')
            return

        newshps=gview.GvShapes(name='Unselected')
        src=self.shapes
        if src is None:
            gvutils.warning('No source layer found- ignoring!')
            return

        schema=src.get_schema()
        for item in schema:
            newshps.add_field(item[0],item[1],item[2],item[3])

        for idx in unselected:
            if src[idx] is not None:
                newshps.append(src[idx].copy())

        gview.undo_register(newshps)
        clayer=gview.GvShapesLayer(newshps)

        cview=self.app.new_view()
        cview.viewarea.add_layer(clayer)
        cview.viewarea.set_active_layer(clayer)
Esempio n. 2
0
 def save(self, widget, dlg, *args):
     import pickle
     import os
     filename = dlg.get_filename()
     path, ext = os.path.splitext(filename)
     if not (ext == ".leg"):
         gvutils.warning("filename extension changed to .leg")
     ext = ".leg"
     filename = path + ext
     dlg.hide()
     if os.path.exists( filename ):
         warning_pix = os.path.join(gview.home_dir, 'pics', 'warning.xpm' )
         win = gvutils._MessageBox( "Do you wish to overwrite the existing file?",
                                    ( 'Yes', 'No', ), warning_pix, modal=TRUE)
         win.set_title( 'File Exists' )
         win.show()
         gtk.mainloop()
         if win.ret == 'No':
             print 'not saving'
             return
     print 'saving'        
     file = open(filename, "w")
     d = self.classification.serialize()
     try:
         pickle.dump(d, file)
     except PicklingError:
         gvutils.error('An error occurred saving the classification:\n' + filename)
Esempio n. 3
0
    def reset_image(self, *args):
        lay = gview.app.sel_manager.get_active_layer()
        lay_name = lay.get_name()
        if (lay is None) or (gvutils.is_of_class(lay.__class__,
                                                 'GvRasterLayer') == 0):
            gvutils.warning(
                'Please select a raster layer using the layer dialog.\n')
            return
        layfname = lay.get_parent().get_name()[:-2]

        view = gview.app.sel_manager.get_active_view()
        viewwin = gview.app.sel_manager.get_active_view_window()

        row = gview.app.layerdlg.list_layers().index(view.active_layer())

        view.remove_layer(lay)
        viewwin.file_open_by_name(layfname)
        lay = gview.app.sel_manager.get_active_layer()
        lay.set_name(lay_name)

        if row != 0:
            gview.app.layerdlg.layerlist.swap_rows(0, row)
            view.swap_layers(0, row)

        if viewwin.laytoggle.active:
            viewwin.updateLayers()
Esempio n. 4
0
    def new_layer_unselected_cb(self, *args):
        """ Create new layer of only selected shapes """

        unselected = self.pgugrid.get_unselected_row_indices()

        if len(unselected) == 0:
            gvutils.warning('No rows unselected- ignoring!')
            return

        newshps = gview.GvShapes(name='Unselected')
        src = self.shapes
        if src is None:
            gvutils.warning('No source layer found- ignoring!')
            return

        schema = src.get_schema()
        for item in schema:
            newshps.add_field(item[0], item[1], item[2], item[3])

        for idx in unselected:
            if src[idx] is not None:
                newshps.append(src[idx].copy())

        gview.undo_register(newshps)
        clayer = gview.GvShapesLayer(newshps)

        cview = self.app.new_view()
        cview.viewarea.add_layer(clayer)
        cview.viewarea.set_active_layer(clayer)
Esempio n. 5
0
 def save(self, widget, dlg, *args):
     import pickle
     import os
     filename = dlg.get_filename()
     path, ext = os.path.splitext(filename)
     if not (ext == ".leg"):
         gvutils.warning("filename extension changed to .leg")
     ext = ".leg"
     filename = path + ext
     dlg.hide()
     if os.path.exists(filename):
         warning_pix = os.path.join(gview.home_dir, 'pics', 'warning.xpm')
         win = gvutils._MessageBox(
             "Do you wish to overwrite the existing file?", (
                 'Yes',
                 'No',
             ),
             warning_pix,
             modal=TRUE)
         win.set_title('File Exists')
         win.show()
         gtk.mainloop()
         if win.ret == 'No':
             print 'not saving'
             return
     print 'saving'
     file = open(filename, "w")
     d = self.classification.serialize()
     try:
         pickle.dump(d, file)
     except PicklingError:
         gvutils.error('An error occurred saving the classification:\n' +
                       filename)
Esempio n. 6
0
def layer_is_raster():
    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
    BCG_Dialog()
Esempio n. 7
0
    def set_subset_unselected_cb(self, *args):
        """ Set the grid subset to selected rows only """

        unselected = self.pgugrid.get_unselected_row_indices()

        if len(unselected) == 0:
            gvutils.warning('No rows unselected- ignoring!')
        else:
            self.pgugrid.set_subset(unselected)
Esempio n. 8
0
    def set_subset_unselected_cb(self,*args):
        """ Set the grid subset to selected rows only """

        unselected=self.pgugrid.get_unselected_row_indices()

        if len(unselected) == 0:
            gvutils.warning('No rows unselected- ignoring!')
        else:
            self.pgugrid.set_subset(unselected)
Esempio n. 9
0
 def format_help_cb(self,*args):
     opformat=self.format_list[self.format_menu.get_history()]
     driver=gdal.GetDriverByName(opformat)
     topic=driver.HelpTopic
     if topic is not None:
         # hash to indicate position in html isn't
         # recognized by mozilla.  Make sure that
         # frmt_various.html is brought up for
         # formats that share this file.
         ttopic=string.split(topic,"#")
         gvhtml.LaunchHTML(ttopic[0])
     else:
         gvutils.warning('No html help available for '+opformat+' format')
Esempio n. 10
0
 def format_help_cb(self, *args):
     opformat = self.format_list[self.format_menu.get_history()]
     driver = gdal.GetDriverByName(opformat)
     topic = driver.HelpTopic
     if topic is not None:
         # hash to indicate position in html isn't
         # recognized by mozilla.  Make sure that
         # frmt_various.html is brought up for
         # formats that share this file.
         ttopic = string.split(topic, "#")
         gvhtml.LaunchHTML(ttopic[0])
     else:
         gvutils.warning('No html help available for ' + opformat +
                         ' format')
    def apply(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

        lut = self.image_adjust(self.bright_adjustment)

        for isrc in range(layer.sources):
            (smin, smax) = layer.autoscale( isource=isrc, viewonly = 1 )

            layer.set_source(isrc, layer.get_data(isrc), smin, smax,
                            layer.get_const_value(isrc), lut,
                            layer.nodata_get(isrc)) 
Esempio n. 12
0
    def apply(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

        lut = self.image_adjust(self.bright_adjustment)

        for isrc in range(layer.sources):
            (smin, smax) = layer.autoscale(isource=isrc, viewonly=1)

            layer.set_source(isrc, layer.get_data(isrc), smin, smax,
                             layer.get_const_value(isrc), lut,
                             layer.nodata_get(isrc))
Esempio n. 13
0
    def add_input_bands(self,bands):
        if len(self.output_bands) > 0:
            keys=self.output_bands.keys()
            xsize,ysize=(self.output_bands[keys[0]][0].RasterXSize,
                         self.output_bands[keys[0]][0].RasterYSize)
        elif len(self.input_bands) > 0:
            keys=self.input_bands.keys()
            xsize,ysize=(self.input_bands[keys[0]][0].RasterXSize,
                         self.input_bands[keys[0]][0].RasterYSize)
        else:
            keys=bands.keys()
            xsize,ysize=(bands[keys[0]][0].RasterXSize,
                         bands[keys[0]][0].RasterYSize)

        # Only add bands that are of the same size
        invalid=0
        oldbands=[]
        for ckey in self.input_bands.keys():
            oldbands.append(self.input_bands[ckey][2])

        newbands=[]    
        for ckey in bands.keys():
            cxsize,cysize=(bands[ckey][0].RasterXSize,
                           bands[ckey][0].RasterYSize)
            if (cxsize == xsize) and (cysize == ysize):
                if ((bands[ckey][2] not in oldbands) and
                    (bands[ckey][2] not in newbands)):
                    self.input_bands[ckey]=bands[ckey]
                    newbands.append(self.input_bands[ckey][2])
            else:
                invalid=1

        if invalid != 0:
            txt='Bands for composed dataset must all\n'+\
                'be the same size.  Bands that are not\n'+\
                str(xsize)+' pixels x '+str(ysize)+' lines\n'+\
                'will be excluded from the input list.'
            gvutils.warning(txt)
        print 'Xsize: ',xsize,' Ysize: ',ysize        
        # clear old list in case some of the new keys replace
        # older ones
        self.source_list.select_all()
        sel=self.source_list.get_selection()
        self.source_list.remove_items(sel)
        self.source_list.append_items(self.input_bands.keys())
        for item in self.input_bands.keys():
            item.show()
Esempio n. 14
0
    def add_input_bands(self, bands):
        if len(self.output_bands) > 0:
            keys = self.output_bands.keys()
            xsize, ysize = (self.output_bands[keys[0]][0].RasterXSize,
                            self.output_bands[keys[0]][0].RasterYSize)
        elif len(self.input_bands) > 0:
            keys = self.input_bands.keys()
            xsize, ysize = (self.input_bands[keys[0]][0].RasterXSize,
                            self.input_bands[keys[0]][0].RasterYSize)
        else:
            keys = bands.keys()
            xsize, ysize = (bands[keys[0]][0].RasterXSize,
                            bands[keys[0]][0].RasterYSize)

        # Only add bands that are of the same size
        invalid = 0
        oldbands = []
        for ckey in self.input_bands.keys():
            oldbands.append(self.input_bands[ckey][2])

        newbands = []
        for ckey in bands.keys():
            cxsize, cysize = (bands[ckey][0].RasterXSize,
                              bands[ckey][0].RasterYSize)
            if (cxsize == xsize) and (cysize == ysize):
                if ((bands[ckey][2] not in oldbands)
                        and (bands[ckey][2] not in newbands)):
                    self.input_bands[ckey] = bands[ckey]
                    newbands.append(self.input_bands[ckey][2])
            else:
                invalid = 1

        if invalid != 0:
            txt='Bands for composed dataset must all\n'+\
                'be the same size.  Bands that are not\n'+\
                str(xsize)+' pixels x '+str(ysize)+' lines\n'+\
                'will be excluded from the input list.'
            gvutils.warning(txt)
        print 'Xsize: ', xsize, ' Ysize: ', ysize
        # clear old list in case some of the new keys replace
        # older ones
        self.source_list.select_all()
        sel = self.source_list.get_selection()
        self.source_list.remove_items(sel)
        self.source_list.append_items(self.input_bands.keys())
        for item in self.input_bands.keys():
            item.show()
Esempio n. 15
0
    def find_gnuplot( self ):
        import gview
        exe = gview.get_preference('gnuplot')
        if exe is not None:
            if os.path.isfile(exe):
                return exe
            else:
                gvutils.warning( 'Disregarding gnuplot preference "%s", executable not found.' % exe )

        exe = gvutils.FindExecutable( 'gnuplot' )
        if exe is None:
            exe = gvutils.FindExecutable( 'pgnuplot.exe' )
        if exe is None:
            exe = gvutils.FindExecutable( 'wgnupl32.exe' )
        if exe is None:
            exe = gvutils.FindExecutable( 'wgnuplot.exe' )

        return exe
Esempio n. 16
0
    def layer_update(self, *args):
        # Disconnect from the old layer
        if self.active == 0:
            return

        self.layer_teardown_cb()

        try:
            self.layer = self.app.sel_manager.get_active_layer()
            self.viewarea = self.app.sel_manager.get_active_view()
            self.shapes = self.layer.get_parent()

            # should skip to except here if layer is a raster
            shp_schema = self.shapes.get_schema()

        except:
            # Layer is None or a raster
            self.layer = None
            self.shapes = None
            self.viewarea = None
            self.pgugrid.set_source(None, expose=1)
            self.layer_teardown_id = None
            return

        try:
            # get display columns
            key_list, fmt_list = self.get_columns(self.shapes)

            self.pgugrid.set_source(self.layer, self.viewarea)
            self.pgugrid.define_columns(members=key_list, formats=fmt_list)

            self.layer_teardown_id = \
                self.layer.connect('teardown',self.layer_teardown_cb)
        except:
            # Layer is None or a raster, or couldn't be loaded
            self.layer = None
            self.shapes = None
            self.viewarea = None
            self.layer_teardown_id = None
            self.pgugrid.set_source(None, expose=1)
            gvutils.warning('Unable to load shapes into grid!')
            return
Esempio n. 17
0
    def layer_update(self,*args):
        # Disconnect from the old layer
        if self.active == 0:
            return

        self.layer_teardown_cb()

        try:
            self.layer = self.app.sel_manager.get_active_layer()
            self.viewarea = self.app.sel_manager.get_active_view()
            self.shapes = self.layer.get_parent()

            # should skip to except here if layer is a raster
            shp_schema = self.shapes.get_schema()

        except:
            # Layer is None or a raster
            self.layer = None
            self.shapes = None
            self.viewarea = None
            self.pgugrid.set_source(None,expose=1)
            self.layer_teardown_id=None
            return

        try:
            # get display columns
            key_list,fmt_list=self.get_columns(self.shapes)

            self.pgugrid.set_source(self.layer,self.viewarea)
            self.pgugrid.define_columns(members=key_list,formats=fmt_list)

            self.layer_teardown_id = \
                self.layer.connect('teardown',self.layer_teardown_cb)
        except:
            # Layer is None or a raster, or couldn't be loaded
            self.layer = None
            self.shapes = None
            self.viewarea = None
            self.layer_teardown_id=None
            self.pgugrid.set_source(None,expose=1)
            gvutils.warning('Unable to load shapes into grid!')
            return
Esempio n. 18
0
    def find_gnuplot(self):
        import gview
        exe = gview.get_preference('gnuplot')
        if exe is not None:
            if os.path.isfile(exe):
                return exe
            else:
                gvutils.warning(
                    'Disregarding gnuplot preference "%s", executable not found.'
                    % exe)

        exe = gvutils.FindExecutable('gnuplot')
        if exe is None:
            exe = gvutils.FindExecutable('pgnuplot.exe')
        if exe is None:
            exe = gvutils.FindExecutable('wgnupl32.exe')
        if exe is None:
            exe = gvutils.FindExecutable('wgnuplot.exe')

        return exe
Esempio n. 19
0
def LaunchHTML( page_name ):
    """Display indicated HTML page.

    If the passed name is not an absolute path name, nor has an http: prefix,
    it will be massaged to point into the GView html help tree."""

    if not os.path.isabs(page_name) and page_name[:5] != 'http:':
        page_name = os.path.abspath( \
            os.path.join(gview.home_dir,'html',page_name) )
        
    global html_browse_command

    if page_name[:5] != 'http:':
        page_name = 'file://'+page_name
    
    if html_browse_command == '':
        html_browse_command = GetBrowseCommand()

    if os.name == "nt" and html_browse_command == '':
        try:
            import webbrowser
            webbrowser.open(page_name)
        except:    
            _gv.gv_launch_url( page_name )
            
        return
    
    if html_browse_command == '' or html_browse_command is None:
        try:
            import webbrowser
            webbrowser.open(page_name)
        except:
            gvutils.warning( 'Unable to display HTML online help, browser not configured.' )
        return

    if string.find(html_browse_command,"%s") > -1:
        full_command = string.replace(html_browse_command,"%s",page_name)+" &"
    else:
        full_command = html_browse_command + ' ' + page_name + ' &'

    os.system( full_command )
Esempio n. 20
0
def LaunchHTML( page_name ):
    """Display indicated HTML page.

    If the passed name is not an absolute path name, nor has an http: prefix,
    it will be massaged to point into the GView html help tree."""

    if not os.path.isabs(page_name) and page_name[:5] != 'http:':
        page_name = os.path.abspath( \
            os.path.join(gview.home_dir,'html',page_name) )

    global html_browse_command

    if page_name[:5] != 'http:':
        page_name = 'file://'+page_name

    if html_browse_command == '':
        html_browse_command = GetBrowseCommand()

    if os.name == "nt" and html_browse_command == '':
        try:
            import webbrowser
            webbrowser.open(page_name)
        except:    
            _gv.gv_launch_url( page_name )

        return

    if html_browse_command == '' or html_browse_command is None:
        try:
            import webbrowser
            webbrowser.open(page_name)
        except:
            gvutils.warning( 'Unable to display HTML online help, browser not configured.' )
        return

    if "%s" in html_browse_command:
        full_command = html_browse_command.replace("%s",page_name) + " &"
    else:
        full_command = html_browse_command + ' ' + page_name + ' &'

    os.system( full_command )
Esempio n. 21
0
    def new_layer_selected(self, rows, name):
        """ Create new layer of only selected shapes """
        if not rows:
            warning('No rows selected- ignoring!')
            return

        newshps = gview.GvShapes(name=name)
        src = self.shapes
        if src is None:
            warning('No source layer found- ignoring!')
            return
        
        newshps.copy_fields(src.get_schema())

        for idx in rows:
            if src[idx] is not None:
                newshps.append(src[idx].copy())

        gview.undo_register(newshps)
        clayer = gview.GvShapesLayer(newshps)

        cview = self.app.new_view()
        cview.viewarea.add_layer(clayer)
        cview.viewarea.set_active_layer(clayer)
    def reset_image(self,*args):
        lay = gview.app.sel_manager.get_active_layer()
        lay_name = lay.get_name()
        if (lay is None) or (gvutils.is_of_class( lay.__class__, 'GvRasterLayer' ) == 0):
            gvutils.warning('Please select a raster layer using the layer dialog.\n')
            return
        layfname = lay.get_parent().get_name()[:-2]

        view = gview.app.sel_manager.get_active_view()
        viewwin = gview.app.sel_manager.get_active_view_window()

        row = gview.app.layerdlg.list_layers().index(view.active_layer())      

        view.remove_layer(lay)
        viewwin.file_open_by_name(layfname)
        lay = gview.app.sel_manager.get_active_layer()
        lay.set_name(lay_name)

        if row != 0:
            gview.app.layerdlg.layerlist.swap_rows(0,row)
            view.swap_layers(0,row)

        if viewwin.laytoggle.active:
            viewwin.updateLayers()
Esempio n. 23
0
    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()
Esempio n. 24
0
    def get_geocoding(self):
        # returns serialized geocoding information as a list
        gt = self.geocode_menu_list[self.geocode_menu.get_history()]
        serialtxt = []
        if gt == 'Default':
            if self.default_geotransform is not None:
                if self.default_prj != '':
                    serialtxt.append([
                        gdal.CXT_Element, 'SRS',
                        [gdal.CXT_Text, self.default_prj]
                    ])

                gtxt = vrtutils.serializeGeoTransform(
                    geotransform=self.default_geotransform)
                if gtxt is not None:
                    serialtxt.append(gtxt)

            elif self.default_gcps is not None:
                serialtxt.append(
                    vrtutils.serializeGCPs(
                        gcplist=self.default_gcps,
                        with_Z=1,
                        projection_attr_txt=self.default_prj))
            else:
                return []

        elif gt == 'GCPs':
            if len(self.gcplist) == 0:
                return []

            inprj, outprj = self.gcpprjbox.get_projections()
            if (outprj == '') or (outprj == inprj) or (inprj == ''):
                reproj = None
                if (outprj != '') and (inprj == ''):
                    gvutils.warning('Warning: output projection specified,\n' +
                                    'but no input projection.  Cannot\n' +
                                    'reproject!')
            else:
                reproj = outprj
            gcplistcopy = CopyGDALGCPs(self.gcplist)
            serialtxt.append(
                vrtutils.serializeGCPs(gcplist=gcplistcopy,
                                       with_Z=1,
                                       projection_attr_txt=inprj,
                                       reproj=reproj))
        else:
            inprj, outprj = self.geotransformprjbox.get_projections()
            gt = []
            try:
                for idx in range(6):
                    gt.append(float(self.geotransform_entries[idx].get_text()))
            except:
                gvutils.warning('Invalid Geotransform information- ' +
                                'ignoring!')
                return []

            if (outprj == '') or (outprj == inprj) or (inprj == ''):
                reproj = None
                if (outprj != '') and (inprj == ''):
                    gvutils.warning('Warning: output projection specified,\n' +
                                    'but no input projection.  Cannot\n' +
                                    'reproject!')

                if inprj != '':
                    serialtxt.append(
                        [gdal.CXT_Element, 'SRS', [gdal.CXT_Text, inprj]])

                gbase = vrtutils.serializeGeoTransform(geotransform=gt)
                if gbase is not None:
                    serialtxt.append(gbase)

            else:
                ds = gdal.OpenShared(self.default_fname)
                gcps = vrtutils.GeoTransformToGCPs(gt,
                                                   ds.RasterXSize,
                                                   ds.RasterYSize,
                                                   grid=2)
                serialtxt.append(
                    vrtutils.serializeGCPs(gcplist=gcps,
                                           with_Z=1,
                                           projection_attr_txt=inprj,
                                           reproj=outprj))

        return serialtxt
Esempio n. 25
0
    def get_geocoding(self):
        # returns serialized geocoding information as a list
        gt=self.geocode_menu_list[self.geocode_menu.get_history()]
        serialtxt=[]
        if gt == 'Default':
            if self.default_geotransform is not None:
                if self.default_prj != '':
                    serialtxt.append([gdal.CXT_Element,'SRS',[gdal.CXT_Text,
                                                       self.default_prj]])

                gtxt = vrtutils.serializeGeoTransform(
                               geotransform=self.default_geotransform)
                if gtxt is not None:
                    serialtxt.append(gtxt)

            elif self.default_gcps is not None:
                serialtxt.append(vrtutils.serializeGCPs(
                                 gcplist=self.default_gcps,
                              with_Z=1,projection_attr_txt=self.default_prj))
            else:
                return []

        elif gt == 'GCPs':
            if len(self.gcplist) == 0:
                return []

            inprj,outprj=self.gcpprjbox.get_projections()
            if (outprj == '') or (outprj == inprj) or (inprj == ''):
                reproj=None
                if (outprj != '') and (inprj == ''):
                    gvutils.warning('Warning: output projection specified,\n'+
                                    'but no input projection.  Cannot\n'+
                                    'reproject!')
            else:
                reproj=outprj
            gcplistcopy=CopyGDALGCPs(self.gcplist)    
            serialtxt.append(vrtutils.serializeGCPs(
                                             gcplist=gcplistcopy,with_Z=1,
                                             projection_attr_txt=inprj,
                                             reproj=reproj))
        else:
            inprj,outprj=self.geotransformprjbox.get_projections()
            gt=[]
            try:
                for idx in range(6):
                    gt.append(float(
                        self.geotransform_entries[idx].get_text()))
            except:
                gvutils.warning('Invalid Geotransform information- '+
                                'ignoring!')
                return []    

            if (outprj == '') or (outprj == inprj) or (inprj == ''):
                reproj=None
                if (outprj != '') and (inprj == ''):
                    gvutils.warning('Warning: output projection specified,\n'+
                                    'but no input projection.  Cannot\n'+
                                    'reproject!')

                if inprj != '':
                    serialtxt.append([gdal.CXT_Element,'SRS',
                                      [gdal.CXT_Text,inprj]])

                gbase=vrtutils.serializeGeoTransform(geotransform=gt)
                if gbase is not None:
                    serialtxt.append(gbase)

            else:
                ds=gdal.OpenShared(self.default_fname)
                gcps=vrtutils.GeoTransformToGCPs(gt,ds.RasterXSize,
                                                 ds.RasterYSize,grid=2)
                serialtxt.append(vrtutils.serializeGCPs(gcplist=gcps,with_Z=1,
                                                 projection_attr_txt=inprj,
                                                 reproj=outprj))

        return serialtxt
Esempio n. 26
0
    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()
Esempio n. 27
0
    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 layer_is_raster():
    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
    BCG_Dialog()
    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)
Esempio n. 30
0
    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 = gvutils.yesno('Confirmation', '%s exists.  Overwrite?' % opfile)
            if resp == 'No':
                return
        elif len(opfile) == 0:
            gvutils.error('No output filename entered!')
            return

        use_viewscale = 0

        rast = gdal.OpenShared(ipfile, gdal.GA_ReadOnly)
        if rast is None:
            if not ipfile:
                gvutils.error('Please specify an input file!')
            else:
                gvutils.error('Unable to open %s as a GDAL supported file!' % ipfile)
            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.startswith('<') 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\nto 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
                self.optentry.get_text()):
                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 = ipfile.split('\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 %s for overview creation!' % opfile)
                    return

##                progress = pgu.ProgressDialog('Building overviews...', cancel=True)
                if ovrs is 'Nearest':
                    outds.BuildOverviews("nearest")
                else:
                    outds.BuildOverviews("average_magphase")
##                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
        laststretch = 'none_lut'
        clayer = None
        if self.button_dict['Scale'].get_active():
            try:
                clayer = self.app.sel_manager.get_active_layer()
                dtype = rast.GetRasterBand(1).DataType
                if clayer.get_mode() == gview.RLM_COMPLEX or \
                    dtype in (gdal.GDT_CInt16,gdal.GDT_CInt32,gdal.GDT_CFloat32,gdal.GDT_CFloat64):
                    # This doesn't deal with complex yet...                        
                    gvutils.error('View scaling option is not yet supported for complex data!')
                    return
                if clayer.parent.get_dataset().GetDescription() != ipfile:
                    wtxt = 'Input file and active layer file names do not match- may '
                    wtxt += 'result in unexpected scaling!'
                    gvutils.warning(wtxt)
                if not gvutils.is_of_class(clayer.__class__,'GvRasterLayer'):
                    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
                    laststretch = clayer.get_property('last_stretch')
            except:
                gvutils.error('Unable to find active raster layer for scaling!')
                return

        # Get windowing options
        if self.button_dict['IP_window'].get_active():
            try:
                dic = self.frame_dict['IP_window'].entry_dict
                spix = int(dic['start_pix'].get_text())
                sline = int(dic['start_line'].get_text())
                npix = int(dic['num_pix'].get_text())
                nlines = int(dic['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: %s)! Aborting...' % rast.RasterXSize)
                    return
                if nlines+sline > rast.RasterYSize:
                    gvutils.error('Window is too large (last row in input: %s)! Aborting...' % rast.RasterYSize)
                    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 = self.optentry.get_text().strip()
        if optstr:
            # 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 = optstr.split(",")
                copts=[]
                for item in split1:
                    if len(item) > 2:
                        copts.append(item[1:len(item)-1])
            else:    
                copts = optstr.split(',')
        else:
            copts = []

        progress = pgu.ProgressDialog('Export to '+opfile, cancel=True)
        progress.SetDefaultMessage("translated")
        progress.show()
        progress.ProgressCB(0)

        if use_viewscale and laststretch != 'linear':
            gvutils.error('Sorry, not working yet...')
            progress.destroy()
            return
            outdataset = driver.Create(opfile, vrtdataset.RasterXSize, vrtdataset.RasterYSize,
                                       bands=vrtdataset.RasterCount, options=copts)
            outdataset.SetProjection(vrtdataset.GetProjection())
            outdataset.SetGeoTransform(vrtdataset.GetGeoTransform())
            lut = clayer.get_source_lut(0)
            prg = 1
            denom = vrtdataset.RasterCount * vrtdataset.RasterYSize
            for b in range(vrtdataset.RasterCount):
                band = vrtdataset.GetRasterBand(b+1)
                outband = outdataset.GetRasterBand(b+1)
                offset = float(b * vrtdataset.RasterYSize)
                for ln in range(vrtdataset.RasterYSize):
                    line = band.ReadRaster(0, ln, vrtdataset.RasterXSize, 1)
                    enhline = map(lambda x: lut[ord(x)], line)
                    buf = ''.join(enhline)
                    outband.WriteRaster(0, ln, vrtdataset.RasterXSize, 1, buf)
                    prg = progress.ProgressCB((float(ln) + offset)/denom, '')
                    if not prg:
                        print 'Cancelled!'
                        break
                if not prg:
                    outdataset = None
                    break
        else:
            outdataset = driver.CreateCopy(opfile, vrtdataset, options=copts)

        if outdataset is None:
            progress.destroy()
            gvutils.error('Unable to create output file '+opfile)
            return

        progress.ProgressCB(1, 'Done')
        ovrs = self._overview_list[self.overview_menu.get_history()]
        if ovrs is 'Nearest':
            progress.SetDefaultMessage("overviews built")
            outdataset.BuildOverviews("nearest")
        elif ovrs is 'Average':
            progress.SetDefaultMessage("overviews built")
            outdataset.BuildOverviews("average_magphase")

        progress.ProgressCB(1, 'Done')
        progress.destroy()
Esempio n. 31
0
    def prepare_default(self, count=5):
        """Prepare a default classification scheme.

        count -- the number of classes to create by default (the actual number
                 may differ if creating a discrete classification)

        If the layer is a GvShapesLayer and the classify property is not 
        numeric then the type will be changed to a discrete classication with
        a maximum of 32 discrete values

        """
        if not self.layers:
            return

        overall_min = None
        overall_max = None
        bUnique = 0
        unique_vals = []
        symbol = None
        name = None
        property_type = None

        for layer in self.layers:
            property = self.get_classify_property(layer)
            if property and self.is_shapes(layer):
                if layer.layer_type == gview.GVSHAPE_POINT:
                    symbol = "ogr-sym-0"
                if layer.parent.get_schema(property)[1] == "string":
                    self.set_type(CLASSIFY_DISCRETE)

            if self.get_type() == CLASSIFY_DISCRETE:
                vals = self.collect_unique(layer, property)
                keys = vals.keys()
                keys.sort()
                unique_vals.extend(keys)
                count = min(len(unique_vals), 80)
                if len(unique_vals) > 80:
                    msg = _("%d discrete values identified, but only the first 80 are being used")
                    warning(msg % len(unique_vals))
            else:
                this_min, this_max = self.collect_range(layer, property)
                if overall_min is None:
                    overall_min = this_min
                    overall_max = this_max
                elif this_min is not None:
                    if this_min < overall_min:
                        overall_min = this_min
                    if this_max > overall_max:
                        overall_max = this_max

        if count == 0:
            print "no values to classify on"
            return

        ctype = self.get_type()
        if overall_min is None and ctype != CLASSIFY_DISCRETE:
            print "overall_min still None in prepare_default()!"
            return
        elif ctype == CLASSIFY_DISCRETE:
            overall_min = 0
            overall_max = count

        epsilon = (overall_max - overall_min) * 0.002
        overall_min -= epsilon
        overall_max += epsilon

        # Below are calls to the classifiers that require the entire property field
        if ctype in (CLASSIFY_QUANTILE, CLASSIFY_NORM_SD):
            svalues = self.collect_values(layer, property)
            if ctype == CLASSIFY_QUANTILE:
                qminmax = self.quantile(svalues, count)
            elif ctype == CLASSIFY_NORM_SD:
                nsdminmax = self.nstddev(svalues)
                count = nsdminmax[2]

        input_incr = (overall_max - overall_min) / count
        color_incr = float(1.0 / (count + 1))

        for n in range(count):
            if ctype == CLASSIFY_EQUAL_INTERVAL:
                range_min = round(overall_min + (input_incr * n), 4)
                range_max = round(overall_min + (input_incr * (n + 1)), 4)
                name = None
            elif ctype == CLASSIFY_QUANTILE:
                range_min = round(qminmax[0][n], 4)
                range_max = round(qminmax[1][n], 4)
                name = None
            elif ctype == CLASSIFY_NORM_SD:
                range_min = round(nsdminmax[0][n], 4)
                range_max = round(nsdminmax[1][n], 4)
                name = nsdminmax[3][n]
            elif ctype == CLASSIFY_DISCRETE:
                try:
                    range_min = unique_vals[n].strip()
                    range_max = ""
                except:
                    range_min = unique_vals[n]
                    range_max = unique_vals[n]
                name = str(unique_vals[n])
            c = float(color_incr * (n + 1))
            self.set_class((c, c, c, 1.0), range_min, range_max, name=name, symbol=symbol)

        txt = _("Legend")
        if property:
            self.set_title("%s: %s" % (txt, property))
        else:
            self.set_title(txt)