Ejemplo n.º 1
0
    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()
Ejemplo n.º 2
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()
Ejemplo n.º 3
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()