예제 #1
0
    def block_size_changed(self, *args):
        if self.active == 0 or self.playing == 0:
            return
        mode = self.block_size_menu.get_history()
        defaults = [0.1, 0.1*self.ext[2], 0.1*self.ext[2]]
        try:
            xorres = abs(float(self.block_entry.get_text()))
        except:
            if mode == 0:
                msg = 'Relative block size must be a number, 0-1!'
            elif mode == 1:
                msg = 'Block size must be a number!'
            elif mode == 2:
                msg = 'Resolution must be a number!'
            gvutils.error(msg)
            xorres = defaults[mode]
            self.block_size_entry.set_text(str(xorres))

        if (mode == 0) and ((xorres < 0) or (xorres > 1)):
            msg = 'Relative block size must be a number, 0-1!'
            gvutils.error(msg)
            xorres = defaults[mode]
            self.block_size_entry.set_text(str(xorres))

        if mode < 2:
            self.tool.set_block_x_size(xorres, mode)
        else:
            self.tool.set_x_resolution(xorres)
예제 #2
0
파일: reproject.py 프로젝트: Onjrew/OpenEV
    def __init__(self,app=None):
        
	self.layer = gview.app.sel_manager.get_active_layer()
	if not layer_is_raster(self.layer):
	    gvutils.error("Please select a raster layer.");
	    return
	
	# Fetch projection record
	self.proj_full = ''
	self.proj_name = ''
	projection = self.layer.get_projection()

        self.sr = None
        if projection is not None and len(projection) > 0:
            self.sr = osr.SpatialReference()
            if self.sr.ImportFromWkt(projection) == 0:
                self.proj_full = self.sr.ExportToPrettyWkt(simplify = 1)
		if self.proj_full is None:
		    self.proj_full = ''
		self.proj_name = self.sr.GetAttrValue("PROJECTION")
		if self.proj_name is None:
		    self.proj_name = ''

	GtkWindow.__init__(self)
        self.set_title('Reproject')
        self.create_gui()
        self.show()
	self.app=app
예제 #3
0
파일: open_raw.py 프로젝트: lmarabi/tareeg
    def create_header(self,filename):
        fmt=self.format_list[self.format_menu.get_history()]
        dtype=self.type_list[self.type_menu.get_history()]
        dr=gdal.GetDriverByName(fmt)
        tlist=string.split(dr.GetMetadata()["DMD_CREATIONDATATYPES"])
        if dtype not in tlist:
            gvutils.error(fmt+' format does not support '+dtype+' data type!')
            return
        
        if fmt == 'PAux':
            self.create_paux_header(filename,dtype)
        else:
            fname,ext = os.path.splitext(filename)
            vrtname = fname+'.vrt'
                
            fname=pgufilesel.GetFileName(title="Select VRT Save Name",
                                         default_filename=vrtname)
            if fname is None:
                return
            if os.path.exists(fname):
	        resp = GtkExtra.message_box('Confirmation', \
		        fname + ' exists. Overwrite?', ('Yes','No'))
                if resp == 'No':
                    return
            lines=self.create_vrt_lines(filename)
            fh=open(fname,'w')
            fh.writelines(lines)
            fh.close()
예제 #4
0
    def changed_field(self,*args):
        """ User changed a field """
        cell=args[1]
        if cell[1] == 2:
            # width updated
            idx=str(cell[0]+1)
            self.shapes.set_property('_field_width_'+str(idx),
                      self.grid.get_cell_data_string(cell[0],cell[1]))
            if self.shapesgridtool is not None:
                self.shapesgridtool.refresh_columns()

        elif cell[1] == 3:
            # precision updated
            # width updated
            idx=str(cell[0]+1)
            if self.grid.get_cell_data_string(cell[0],1) == 'float':
                self.shapes.set_property('_field_precision_'+str(idx),
                     self.grid.get_cell_data_string(cell[0],cell[1]))
                if self.shapesgridtool is not None:
                    self.shapesgridtool.refresh_columns()

            else:
                if self.grid.get_cell_data_string(cell[0],cell[1]) != '0':
                    self.grid.set_cell_data_string(cell[0],cell[1],0)
                    gvutils.error('Precision can only be reset for float.')

        else:
            gvutils.error('Name and type of a field cannot be changed.')
예제 #5
0
    def block_size_changed(self, *args):
        if self.active == 0 or self.playing == 0:
            return
        mode = self.block_size_menu.get_history()
        defaults = [0.1, 0.1 * self.ext[2], 0.1 * self.ext[2]]
        try:
            xorres = abs(float(self.block_entry.get_text()))
        except:
            if mode == 0:
                msg = 'Relative block size must be a number, 0-1!'
            elif mode == 1:
                msg = 'Block size must be a number!'
            elif mode == 2:
                msg = 'Resolution must be a number!'
            gvutils.error(msg)
            xorres = defaults[mode]
            self.block_size_entry.set_text(str(xorres))

        if (mode == 0) and ((xorres < 0) or (xorres > 1)):
            msg = 'Relative block size must be a number, 0-1!'
            gvutils.error(msg)
            xorres = defaults[mode]
            self.block_size_entry.set_text(str(xorres))

        if mode < 2:
            self.tool.set_block_x_size(xorres, mode)
        else:
            self.tool.set_x_resolution(xorres)
예제 #6
0
파일: fusion.py 프로젝트: EvertS3/code
     def __init__(self,app=None):
         gtk.GtkWindow.__init__(self)
         self.set_title('Image Fusion')
         self.set_policy(FALSE, TRUE, TRUE)
         self.roichanged_id = None
         rgbdict,pandict = getLayersDict()
         if len(rgbdict) and len(pandict):
             self.rgbDict = rgbdict
             self.panDict = pandict
         else:
             self.close()
         self.nprv = 0
         self.tips = gtk.GtkTooltips()
         self.roichanged_id = gview.app.toolbar.roi_tool.connect('roi-changed',self.getROIinfo)
         gview.app.toolbar.roi_button.set_active(TRUE)
 
         gui_OK = self.createGUI()
         if gui_OK is FALSE:
             return None
         else:
             self.show_all()
 
         self.fus = self.initFusionObject()
         if self.fus is None:
             gvutils.error('Could not initialize Fusion')
             self.close()
         self.updateExtentEntries()
         self.setFilename()
예제 #7
0
파일: fusion.py 프로젝트: gfwei/code
        def __init__(self, app=None):
            gtk.GtkWindow.__init__(self)
            self.set_title('Image Fusion')
            self.set_policy(FALSE, TRUE, TRUE)
            self.roichanged_id = None
            rgbdict, pandict = getLayersDict()
            if len(rgbdict) and len(pandict):
                self.rgbDict = rgbdict
                self.panDict = pandict
            else:
                self.close()
            self.nprv = 0
            self.tips = gtk.GtkTooltips()
            self.roichanged_id = gview.app.toolbar.roi_tool.connect(
                'roi-changed', self.getROIinfo)
            gview.app.toolbar.roi_button.set_active(TRUE)

            gui_OK = self.createGUI()
            if gui_OK is FALSE:
                return None
            else:
                self.show_all()

            self.fus = self.initFusionObject()
            if self.fus is None:
                gvutils.error('Could not initialize Fusion')
                self.close()
            self.updateExtentEntries()
            self.setFilename()
예제 #8
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)
예제 #9
0
    def changed_field(self, *args):
        """ User changed a field """
        cell = args[1]
        if cell[1] == 2:
            # width updated
            idx = str(cell[0] + 1)
            self.shapes.set_property(
                '_field_width_' + str(idx),
                self.grid.get_cell_data_string(cell[0], cell[1]))
            if self.shapesgridtool is not None:
                self.shapesgridtool.refresh_columns()

        elif cell[1] == 3:
            # precision updated
            # width updated
            idx = str(cell[0] + 1)
            if self.grid.get_cell_data_string(cell[0], 1) == 'float':
                self.shapes.set_property(
                    '_field_precision_' + str(idx),
                    self.grid.get_cell_data_string(cell[0], cell[1]))
                if self.shapesgridtool is not None:
                    self.shapesgridtool.refresh_columns()

            else:
                if self.grid.get_cell_data_string(cell[0], cell[1]) != '0':
                    self.grid.set_cell_data_string(cell[0], cell[1], 0)
                    gvutils.error('Precision can only be reset for float.')

        else:
            gvutils.error('Name and type of a field cannot be changed.')
예제 #10
0
파일: fusion.py 프로젝트: midendian/openev2
        def __init__(self, app=None):
            gtk.Window.__init__(self)
            self.set_title("Image Fusion")
            self.set_resizable(False)

            self.app = app
            view = app.view_manager.get_active_view_window()
            self.nprv = 0

            self.rgbDict, self.panDict = getLayersDict(view)
            if not (self.rgbDict and self.panDict):
                gvutils.error("RGB and Pan images required")
                self.destroy()
                return None

            self.roichanged_id = app.toolbar.roi_tool.connect('roi-changed',self.getROIinfo)
            app.toolbar.roi_button.set_active(True)
    
            self.createGUI()
            self.show_all()
    
            self.fus = self.initFusionObject()
            if self.fus is None:
                gvutils.error("Could not initialize Fusion")
                self.close()
            self.updateExtentEntries()
            self.setFilename()
예제 #11
0
파일: compose.py 프로젝트: lmarabi/tareeg
        def src_load(_button, *args):
            fname = GtkExtra.file_sel_box(title="Select GDAL Dataset")
            if fname is None:
                return
            ds = gdal.OpenShared(fname)
            if ds is None:
                gvutils.error('Not a valid gdal dataset!')
                return

            dict = {}
            for i in range(1, ds.RasterCount + 1):
                curband = fname + '.band[' + str(i) + ']'
                dict[gtk.GtkListItem(curband)] = (ds, i, curband)

            if srctoggle.get_active() == gtk.TRUE:
                slist = vrtutils.GetSimilarFiles(fname)
                for nname in slist:
                    ds = gdal.OpenShared(nname)
                    if ds is None:
                        continue
                    for i in range(1, ds.RasterCount + 1):
                        curband = nname + '.band[' + str(i) + ']'
                        dict[gtk.GtkListItem(curband)] = (ds, i, curband)

            self.add_input_bands(dict)
예제 #12
0
    def create_header(self,filename):
        fmt=self.format_list[self.format_menu.get_history()]
        dtype=self.type_list[self.type_menu.get_history()]
        dr=gdal.GetDriverByName(fmt)
        tlist=dr.GetMetadata().split(["DMD_CREATIONDATATYPES"])
        if dtype not in tlist:
            gvutils.error(fmt+' format does not support '+dtype+' data type!')
            return

        if fmt == 'PAux':
            self.create_paux_header(filename,dtype)
        else:
            fname,ext = os.path.splitext(filename)
            vrtname = fname+'.vrt'

            fname=pgufilesel.GetFileName(title="Select VRT Save Name",
                                         default_filename=vrtname)
            if fname is None:
                return
            if os.path.exists(fname):
	        resp = GtkExtra.message_box('Confirmation', \
		        fname + ' exists. Overwrite?', ('Yes','No'))
                if resp == 'No':
                    return
            lines=self.create_vrt_lines(filename)
            fh=open(fname,'w')
            fh.writelines(lines)
            fh.close()
예제 #13
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)
예제 #14
0
        def src_load(_button,*args):

            fname=GtkExtra.file_sel_box(title="Select GDAL Dataset")
            if fname is None:
                return
            ds=gdal.OpenShared(fname)
            if ds is None:
                gvutils.error('Not a valid gdal dataset!')
                return

            dict={}
            for i in range(1,ds.RasterCount+1):
                curband=fname + '.band[' + str(i) + ']'
                dict[gtk.ListItem(curband)] = (ds,i,curband)

            if srctoggle.get_active() == True:
                slist=vrtutils.GetSimilarFiles(fname)
                for nname in slist:
                    ds = gdal.OpenShared(nname)
                    if ds is None:
                        continue
                    for i in range(1,ds.RasterCount+1):
                        curband=nname + '.band[' + str(i) + ']'
                        dict[gtk.ListItem(curband)] = (ds,i,curband)

            self.add_input_bands(dict)    
예제 #15
0
파일: reproject.py 프로젝트: lmarabi/tareeg
    def __init__(self, app=None):

        self.layer = gview.app.sel_manager.get_active_layer()
        if not layer_is_raster(self.layer):
            gvutils.error("Please select a raster layer.")
            return

        # Fetch projection record
        self.proj_full = ''
        self.proj_name = ''
        projection = self.layer.get_projection()

        self.sr = None
        if projection is not None and len(projection) > 0:
            self.sr = osr.SpatialReference()
            if self.sr.ImportFromWkt(projection) == 0:
                self.proj_full = self.sr.ExportToPrettyWkt(simplify=1)
                if self.proj_full is None:
                    self.proj_full = ''
                self.proj_name = self.sr.GetAttrValue("PROJECTION")
                if self.proj_name is None:
                    self.proj_name = ''

        GtkWindow.__init__(self)
        self.set_title('Reproject')
        self.create_gui()
        self.show()
        self.app = app
예제 #16
0
파일: gvprint.py 프로젝트: Onjrew/OpenEV
    def print_cb(self, *args):
        if self.resolution_adjustment.value >= 0.99 and self.resolution_adjustment.value <= 1.01:
            width = self.view.get_width()
            height = self.view.get_height()
        else:
            width = self.view.get_width() * self.resolution_adjustment.value
            height = self.view.get_height() * self.resolution_adjustment.value
            width = int(width + 0.5)
            height = int(height + 0.5)

        if width / self.paper_x > height / self.paper_y:
            pixels_per_inch = width / (self.paper_x * 0.9)
        else:
            pixels_per_inch = height / (self.paper_y * 0.9)

        pixels_per_inch = pixels_per_inch * self.scale_adjustment.value
        ulx = (self.paper_x - width / pixels_per_inch) / 2.0
        uly = (self.paper_y - height / pixels_per_inch) / 2.0
        lrx = self.paper_x - ulx
        lry = self.paper_y - uly

        try:
            os.unlink(self.file.get_text())
        except:
            pass

        err = 0
        if self.driver.get_history() == DR_POSTSCRIPT:
            filename = self.file.get_text()
            if self.device.get_history() == 1:
                filename = "|" + filename

            err = self.view.print_postscript_to_file(
                width, height, ulx, uly, lrx, lry, self.output.get_history(), filename
            )
        elif self.driver.get_history() == DR_TIFF:
            err = self.view.print_to_file(width, height, self.file.get_text(), "GTiff", self.output.get_history())
        elif self.driver.get_history() == DR_PNG:
            err = self.view.print_to_file(width, height, "_temp.tif", "GTiff", self.output.get_history())
            if err == 0:
                gdal.GetDriverByName("PNG").CreateCopy(self.file.get_text(), gdal.Open("_temp.tif"), TRUE)
            os.unlink("_temp.tif")
        elif self.driver.get_history() == DR_WINPRINT:
            self.view.print_to_windriver(width, height, ulx, uly, lrx, lry, self.output.get_history())
        elif self.driver.get_history() == DR_GIF:
            err = self.view.print_to_file(width, height, "_temp.tif", "GTiff", self.output.get_history())
            if err == 0:
                if self.output.get_history() == 1:
                    gdal.RGBFile2PCTFile("_temp.tif", "_temp2.tif")
                    os.unlink("_temp.tif")
                    os.rename("_temp2.tif", "_temp.tif")

                gdal.GetDriverByName("GIF").CreateCopy(self.file.get_text(), gdal.Open("_temp.tif"), TRUE)
            os.unlink("_temp.tif")

        if err != 0:
            gvutils.error("The request to print appears to have failed.")

        self.close()
예제 #17
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()
예제 #18
0
    def launch_dialog(self, *args):
        try:
            self.win = RCalculatorDialog()
        except:
            gvutils.error("Please select a raster layer.")
            return

        self.win.update_gui()
        self.win.show()
예제 #19
0
파일: calculator.py 프로젝트: Onjrew/OpenEV
    def launch_dialog(self,*args):
	try:
	    self.win = RCalculatorDialog()
	except:
	    gvutils.error("Please select a raster layer.")
	    return
    
	self.win.update_gui()
        self.win.show()
예제 #20
0
    def analyze_cb(self, *args):
        # Find the view and layer
        cview = self.app.view_manager.get_active_view_window().title
        clayer = self.app.sel_manager.get_active_layer()
        if (cview is None) or (clayer is None):
            # analysis only makes sense in the context of a view and layer
            gvutils.error('No View/Layer selected!')
            return

        text = self.basic_region_analysis(cview, clayer)
예제 #21
0
    def analyze_cb(self,*args):
        # Find the view and layer
        cview = self.app.view_manager.get_active_view_window().title
        clayer = self.app.sel_manager.get_active_layer()
        if (cview is None) or (clayer is None):
            # analysis only makes sense in the context of a view and layer
            gvutils.error('No View/Layer selected!')
            return

        text = self.basic_region_analysis(cview,clayer) 
예제 #22
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()
예제 #23
0
    def analyze_cb(self,*args):
        # Find the view and layer
        [cview, clayer] = self.app.layerdlg.get_selected_layer()
        if (cview is None) or (clayer is None):
            # analysis only makes sense in the context of a view and layer
            gvutils.error('No View/Layer selected!')
            return

        text = self.basic_pixel_analysis(cview,clayer)

        self.RP_ToolDlg.update_pixelinfo_text(text)
예제 #24
0
    def analyze_cb(self,*args):
        # Find the view and layer
        [cview, clayer] = self.app.layerdlg.get_selected_layer()
        if (cview is None) or (clayer is None):
            # analysis only makes sense in the context of a view and layer
            gvutils.error('No View/Layer selected!')
            return

        text = self.basic_pixel_analysis(cview,clayer)

        self.RP_ToolDlg.update_pixelinfo_text(text)
예제 #25
0
    def att_update_cb(self, *args):
        if self.text_contents == self.text.get_chars(0, -1):
            return

        if self.selected_shape is None:
            return

        shapes = self.layer.get_parent()
        shape = shapes[self.selected_shape]
        if shape is None:
            return

        shape = shape.copy()

        lines = string.split(self.text.get_chars(0, -1), '\n')
        for line in lines:
            tokens = string.split(line, ':', 1)
            if len(tokens) == 2:
                value = string.strip(tokens[1])
                shape.set_property(tokens[0], value)
                property_exists = 0
                for cprop in shapes.get_schema():
                    if cprop[0] == tokens[0]:
                        property_exists = 1
                if property_exists != 1:
                    ftype = self.new_field_types[
                        self.new_field_type_menu.get_history()]

                    response = \
                       GtkExtra.message_box('Confirmation',
                         'Create new ' + ftype + '-type property ' + tokens[0] + '?' ,
                                            ('Yes','No'))
                    if response == 'Yes':
                        try:
                            fwidth = int(self.new_field_width_entry.get_text())
                        except:
                            gvutils.error('Field width must be an integer!')
                            continue

                        if ftype == 'float':
                            try:
                                fprec = int(
                                    self.new_field_width_entry.get_text())
                            except:
                                gvutils.error(
                                    'Precision width must be an integer!')
                                continue
                        else:
                            fprec = 0

                        shapes.add_field(tokens[0], ftype, fwidth, fprec)

        shapes[self.selected_shape] = shape
        self.gui_update()
예제 #26
0
    def att_update_cb(self,*args):
        #if self.text_contents == self.text.get_chars(0,-1):
        #    return

        if self.selected_shape is None:
            return

        shapes = self.layer.get_parent()
        shape = shapes[self.selected_shape]
        if shape is None:
            return

        shape = shape.copy()

        lines = self.text_buff.get_text(self.text_buff.get_bounds()).split('\n')
        #lines = string.split(self.text.get_chars(0,-1),'\n')
        for line in lines:
            tokens = line.split(':',1)
            if len(tokens) == 2:
                value = tokens[1].strip()
                shape.set_property(tokens[0],value)
                property_exists=0
                for cprop in shapes.get_schema():
                    if cprop[0] == tokens[0]:
                        property_exists=1
                if property_exists != 1:
                    ftype = self.new_field_types[self.new_field_type_menu.get_history()]

                    response = \
                       gvutils._message_box('Confirmation',
                         'Create new ' + ftype + '-type property ' + tokens[0] + '?' ,
                                            ('Yes','No'))
                    if response == 'Yes':
                        try:
                            fwidth = int(self.new_field_width_entry.get_text())
                        except:
                            gvutils.error('Field width must be an integer!')
                            continue

                        if ftype == 'float':
                            try:
                                fprec = int(self.new_field_width_entry.get_text())
                            except:
                                gvutils.error('Precision width must be an integer!')
                                continue
                        else:
                            fprec = 0

                        shapes.add_field(tokens[0],ftype,fwidth,fprec)

        shapes[self.selected_shape] = shape
        self.gui_update()
예제 #27
0
 def load(self, widget, dlg, *args):
     import pickle
     filename = dlg.get_filename()
     dlg.hide()
     try:
         file = open(filename, "r")
         d = pickle.load(file)
         self.classification.deserialize(d)
         self.ramp = None
         self.reset_classification_list()
         self.title_txt.set_text(self.classification.get_title())
     except:
         gvutils.error('Error opening classification file:\n' + filename)
예제 #28
0
 def load(self, widget, dlg, *args):
     import pickle
     filename = dlg.get_filename()
     dlg.hide()
     try:
         file = open(filename, "r")
         d = pickle.load(file)
         self.classification.deserialize(d)
         self.ramp = None
         self.reset_classification_list()
         self.title_txt.set_text(self.classification.get_title())
     except:
         gvutils.error('Error opening classification file:\n' + filename)
예제 #29
0
파일: compose.py 프로젝트: lmarabi/tareeg
    def create_cb(self, *args):
        bands = self.input_frame.get_output_bands()
        if len(bands) == 0:
            gvutils.error('No output bands specified!')
            return

        vrtbase = [gdal.CXT_Element, 'VRTDataset']
        vrtbase.append([
            gdal.CXT_Attribute, 'rasterXSize',
            [gdal.CXT_Text, str(bands[0][0].RasterXSize)]
        ])
        vrtbase.append([
            gdal.CXT_Attribute, 'rasterYSize',
            [gdal.CXT_Text, str(bands[0][0].RasterYSize)]
        ])

        # Metadata is currently taken from first output band.
        # This may be updatable later.
        mbase = vrtutils.serializeMetadata(bands[0][0])
        if mbase is not None:
            vrtbase.append(mbase)

        gbase = self.geo_frame.get_geocoding()
        for item in gbase:
            vrtbase.append(item)

        outband = 1
        for item in bands:
            dict = {}
            dict['band'] = outband
            dict['SourceBand'] = item[1]
            dict['ColorInterp'] = 'Undefined'
            bbase = vrtutils.serializeBand(item[0], opt_dict=dict)
            vrtbase.append(bbase)
            outband = outband + 1

        vrtlines = gdal.SerializeXMLTree(vrtbase)

        vrtds = gdal.OpenShared(vrtlines)

        if args[1] == 'Save':
            fname = GtkExtra.file_sel_box(title="Save File")
            if fname is None:
                return
            driver = gdal.GetDriverByName('VRT')
            driver.CreateCopy(fname, vrtds)
        elif args[1] == 'New':
            self.app.new_view()
            self.app.open_gdal_dataset(vrtds)
        else:
            self.app.open_gdal_dataset(vrtds)
예제 #30
0
    def create_cb(self,*args):
        bands = self.input_frame.get_output_bands()
        if len(bands) == 0:
            gvutils.error('No output bands specified!')
            return

        vrtbase = [gdal.CXT_Element,'VRTDataset']
        vrtbase.append([gdal.CXT_Attribute,'rasterXSize',
                     [gdal.CXT_Text,str(bands[0][0].RasterXSize)]])
        vrtbase.append([gdal.CXT_Attribute,'rasterYSize',
                     [gdal.CXT_Text,str(bands[0][0].RasterYSize)]])

        # Metadata is currently taken from first output band.
        # This may be updatable later.
        mbase = vrtutils.serializeMetadata(bands[0][0])
        if mbase is not None:
            vrtbase.append(mbase)

        gbase = self.geo_frame.get_geocoding()
        for item in gbase:
            vrtbase.append(item)

        outband = 1
        for item in bands:
            dict={}
            dict['band']=outband
            dict['SourceBand'] = item[1]
            dict['ColorInterp'] = 'Undefined'
            bbase = vrtutils.serializeBand(item[0],opt_dict=dict)
            vrtbase.append(bbase)
            outband=outband+1

        vrtlines = gdal.SerializeXMLTree(vrtbase)

        vrtds = gdal.OpenShared(vrtlines)

        if args[1] == 'Save':
            chooser = gtk.FileChooserDialog(title="Save File", parent=self, 
                    action=gtk.FILE_CHOOSER_ACTION_SAVE, buttons=None, backend=None)
            fname = chooser.get_filename()
            print fname
            if fname is None:
                return
            driver = gdal.GetDriverByName('VRT')
            driver.CreateCopy(fname,vrtds)
        elif args[1] == 'New':
            self.app.new_view()
            self.app.open_gdal_dataset(vrtds) 
        else:
            self.app.open_gdal_dataset(vrtds)
예제 #31
0
    def load(self, filename, cwd):
        import pickle
        self.cwd = cwd

        try:
            file = open(filename, 'r')
            d = pickle.load(file)
            self.cls.deserialize(d)
            self.ramp = None
            self.reset_cls_list()
            self.title_txt.set_text(self.cls.get_title())
        except:
            msg = _("Error opening classification file:")
            error('%s\n%s' % (msg, filename))
예제 #32
0
    def load_gcps_cb(self,*args):
        """ Load gcps from a text file """
        self.clear_gcps()
        info=getgcpfile()
        if info is None:
            # user pressed cancel
            return
        if ((info[2] is None) or (info[3] is None) or
            (info[4] is None) or (info[5] is None)):
            gvutils.error('Invalid column info for GCP text file!')
            return

        try:
            fh=open(info[0],'r')
            flines=fh.readlines()
        except:
            gvutils.error('Unable to read GCP text file!')
            return

        idx=0
        for cline in flines:
            if string.strip(info[1]) == '':
                # whitespace delimited
                sline=string.split(cline)
            else:
                sline=string.split(cline,info[1])
            try:
                gcp=gdal.GCP()
                gcp.GCPPixel=float(string.strip(sline[info[2]-1]))
                gcp.GCPLine=float(string.strip(sline[info[3]-1]))
                gcp.GCPX=float(string.strip(sline[info[4]-1]))
                gcp.GCPY=float(string.strip(sline[info[5]-1]))
                if info[6] is not None:
                    gcp.GCPZ=float(string.strip(sline[info[6]-1]))
                if info[7] is not None:
                    gcp.Id=string.strip(sline[info[7]-1])
                if info[8] is not None:
                    gcp.Info=string.strip(sline[info[8]-1])
                self.gcplist.append(gcp)
            except:
                # first line might have column names, so
                # ignore errors.  otherwise, report invalid
                # lines
                if idx != 0:
                    print 'Warning: invalid line '+str(idx)+' in GCP file!'

            idx=idx+1

        self.gcpgrid.refresh()
예제 #33
0
파일: compose.py 프로젝트: lmarabi/tareeg
    def load_gcps_cb(self, *args):
        """ Load gcps from a text file """
        self.clear_gcps()
        info = getgcpfile()
        if info is None:
            # user pressed cancel
            return
        if ((info[2] is None) or (info[3] is None) or (info[4] is None)
                or (info[5] is None)):
            gvutils.error('Invalid column info for GCP text file!')
            return

        try:
            fh = open(info[0], 'r')
            flines = fh.readlines()
        except:
            gvutils.error('Unable to read GCP text file!')
            return

        idx = 0
        for cline in flines:
            if string.strip(info[1]) == '':
                # whitespace delimited
                sline = string.split(cline)
            else:
                sline = string.split(cline, info[1])
            try:
                gcp = gdal.GCP()
                gcp.GCPPixel = float(string.strip(sline[info[2] - 1]))
                gcp.GCPLine = float(string.strip(sline[info[3] - 1]))
                gcp.GCPX = float(string.strip(sline[info[4] - 1]))
                gcp.GCPY = float(string.strip(sline[info[5] - 1]))
                if info[6] is not None:
                    gcp.GCPZ = float(string.strip(sline[info[6] - 1]))
                if info[7] is not None:
                    gcp.Id = string.strip(sline[info[7] - 1])
                if info[8] is not None:
                    gcp.Info = string.strip(sline[info[8] - 1])
                self.gcplist.append(gcp)
            except:
                # first line might have column names, so
                # ignore errors.  otherwise, report invalid
                # lines
                if idx != 0:
                    print 'Warning: invalid line ' + str(idx) + ' in GCP file!'

            idx = idx + 1

        self.gcpgrid.refresh()
예제 #34
0
    def get_cur_rlayer(self):

        rlayer = gview.app.sel_manager.get_active_layer()

        if rlayer is None:
            gvutils.error( 'Please select a raster layer.' )
            return None

        # This will only work for a real GvRasterLayer
        try:
            nd = rlayer.get_nodata(0)
            return rlayer

        except:
            gvutils.error( 'Please select a raster layer.' )
            return None
예제 #35
0
    def get_cur_rlayer(self):

        rlayer = gview.app.sel_manager.get_active_layer()

        if rlayer is None:
            gvutils.error('Please select a raster layer.')
            return None

        # This will only work for a real GvRasterLayer
        try:
            nd = rlayer.get_nodata(0)
            return rlayer

        except:
            gvutils.error('Please select a raster layer.')
            return None
예제 #36
0
파일: fft.py 프로젝트: lmarabi/tareeg
    def execute_cb(self, *args):
        layer = gview.app.sel_manager.get_active_layer()
        if not layer_is_raster(layer):
            gvutils.error("Please select a raster layer.")
            return
        ds = layer.get_parent().get_dataset()
        data = gdalnumeric.DatasetReadAsArray(ds)

        if self.switch_forward.get_active():
            data_tr = FFT.fft2d(data)
        else:
            data_tr = FFT.inverse_fft2d(data)

        array_name = gdalnumeric.GetArrayFilename(data_tr)
        if self.switch_new_view.get_active():
            gview.app.new_view()
        gview.app.file_open_by_name(array_name)
예제 #37
0
    def overlap_changed(self,*args):
        if self.active == 0:
            return
        txt = self.overlap_entry.get_text()
        try:
            val = float(txt)
        except:
            gvutils.error('Overlap must be a number, 0 <= overlap < 1!')
            val = 0.1
            self.overlap_entry.set_text('0.1')

        if (val < 0) or (val >= 1):
            gvutils.error('Overlap must be a number, 0 <= overlap < 1!')
            val = 0.1
            self.overlap_entry.set_text('0.1')

        self.tool.set_overlap(val)
예제 #38
0
    def overlap_changed(self, *args):
        if self.active == 0:
            return
        txt = self.overlap_entry.get_text()
        try:
            val = float(txt)
        except:
            gvutils.error('Overlap must be a number, 0 <= overlap < 1!')
            val = 0.1
            self.overlap_entry.set_text('0.1')

        if (val < 0) or (val >= 1):
            gvutils.error('Overlap must be a number, 0 <= overlap < 1!')
            val = 0.1
            self.overlap_entry.set_text('0.1')

        self.tool.set_overlap(val)
예제 #39
0
파일: fft.py 프로젝트: midendian/openev2
    def execute_cb( self, *args ):
	layer = gview.app.sel_manager.get_active_layer()
	if not layer_is_raster(layer):
	    gvutils.error("Please select a raster layer.");
	    return
	ds = layer.get_parent().get_dataset()
	data = gdalnumeric.DatasetReadAsArray(ds)

	if self.switch_forward.get_active():
	    data_tr = FFT.fft2d(data)
	else:
	    data_tr = FFT.inverse_fft2d(data)

	array_name = gdalnumeric.GetArrayFilename(data_tr)
	if self.switch_new_view.get_active():
	    gview.app.new_view()
	gview.app.file_open_by_name(array_name)
예제 #40
0
파일: compose.py 프로젝트: lmarabi/tareeg
def editprjinfo(wktinit=''):
    win = editprjwin("Projection (Well Known Text string)", wktinit)
    win.show()
    gtk.mainloop()
    prj = win.ret
    if prj is None:
        return

    if len(prj) == 0:
        return ''

    sr = osr.SpatialReference()
    val = sr.ImportFromWkt(prj)
    if val != 0:
        gvutils.error('Invalid projection information entered!')
        return ''

    return prj
예제 #41
0
def editprjinfo(wktinit=''):
    win=editprjwin("Projection (Well Known Text string)",wktinit)
    win.show()
    gtk.mainloop()
    prj=win.ret
    if prj is None:
        return

    if len(prj) == 0:
        return ''

    sr=osr.SpatialReference()
    val=sr.ImportFromWkt(prj)
    if val != 0:
        gvutils.error('Invalid projection information entered!')
        return ''

    return prj
예제 #42
0
    def import_cb(self, *args):
	# Check if the parameters valid
	filename = self.open_entry.get_text()
	if filename is '':
	    gvutils.error('You should select a raw file to load!')
	    return

	if not os.path.isfile(filename):
	    gvutils.error('Unable to load '+ filename)
	    return

        if args[1] == 'Save':
            self.create_header(filename)
        else:
            lines=self.create_vrt_lines(filename)
            vrtds=gdal.OpenShared(lines)
            if args[1] == 'New':
                self.app.new_view()
            self.app.open_gdal_dataset(vrtds)
예제 #43
0
파일: open_raw.py 프로젝트: lmarabi/tareeg
    def import_cb(self, *args):
	# Check if the parameters valid
	filename = self.open_entry.get_text()
	if filename is '':
	    gvutils.error('You should select a raw file to load!')
	    return
        
	if not os.path.isfile(filename):
	    gvutils.error('Unable to load '+ filename)
	    return

        if args[1] == 'Save':
            self.create_header(filename)
        else:
            lines=self.create_vrt_lines(filename)
            vrtds=gdal.OpenShared(lines)
            if args[1] == 'New':
                self.app.new_view()
            self.app.open_gdal_dataset(vrtds)
예제 #44
0
파일: isodata.py 프로젝트: Onjrew/OpenEV
    def __init__(self,app=None):
	GtkWindow.__init__(self)
	self.set_title('ISODATA Classification')
	self.set_policy(FALSE, TRUE, TRUE)
	self.text_pos = 0
	self.tooltips = GtkTooltips()
	
        try:
    	    gdal_dataset = gview.app.sel_manager.get_active_layer().get_data().get_dataset()
        except:
	    gvutils.error("Active Layer is not a raster layer")
    	    return None 
	    		
	self.band_list_to_classify = []    		
		   	
	gui_OK = self.create_gui()
	if gui_OK is FALSE:
	    return None
	else:
	    GtkWindow.show_all(self)
예제 #45
0
파일: isodata.py 프로젝트: lmarabi/tareeg
    def __init__(self, app=None):
        GtkWindow.__init__(self)
        self.set_title('ISODATA Classification')
        self.set_policy(FALSE, TRUE, TRUE)
        self.text_pos = 0
        self.tooltips = GtkTooltips()

        try:
            gdal_dataset = gview.app.sel_manager.get_active_layer().get_data(
            ).get_dataset()
        except:
            gvutils.error("Active Layer is not a raster layer")
            return None

        self.band_list_to_classify = []

        gui_OK = self.create_gui()
        if gui_OK is FALSE:
            return None
        else:
            GtkWindow.show_all(self)
예제 #46
0
    def copy_gcps_cb(self,*args):
        """ Copy gcps from an existing gdal dataset. """
        fname=GtkExtra.file_sel_box(title="Select GDAL Dataset")
        if fname is None:
            return

        try:
            fh=gdal.OpenShared(fname)
        except:
            gvutils.error('Unable to open '+fname+' as a GDAL dataset!')
            return

        gcps=fh.GetGCPs()
        prj=fh.GetGCPProjection()
        self.clear_gcps()
        for gcp in gcps:
            ngcp=CopyGDALGCP(gcp)
            self.gcplist.append(ngcp)
        self.gcpgrid.refresh()

        self.gcpprjbox.set_input_projection(prj)
예제 #47
0
파일: compose.py 프로젝트: lmarabi/tareeg
    def copy_gcps_cb(self, *args):
        """ Copy gcps from an existing gdal dataset. """
        fname = GtkExtra.file_sel_box(title="Select GDAL Dataset")
        if fname is None:
            return

        try:
            fh = gdal.OpenShared(fname)
        except:
            gvutils.error('Unable to open ' + fname + ' as a GDAL dataset!')
            return

        gcps = fh.GetGCPs()
        prj = fh.GetGCPProjection()
        self.clear_gcps()
        for gcp in gcps:
            ngcp = CopyGDALGCP(gcp)
            self.gcplist.append(ngcp)
        self.gcpgrid.refresh()

        self.gcpprjbox.set_input_projection(prj)
예제 #48
0
    def save(self, filename, cwd):
        import pickle
        self.cwd = cwd

        path, ext = os.path.splitext(filename)
        if ext != '.leg':
            ext = '.leg'
        filename = path + ext

        if os.path.exists(filename):
            ret = yesno(title=_("File exists"), text=_("Do you wish to overwrite the existing file?"))
            if ret == 'No':
                return

        file = open(filename, 'w')
        d = self.cls.serialize()
        try:
            pickle.dump(d, file)
        except PicklingError:
            msg = _("An error occurred saving the classification:")
            error('%s\n%s' % (msg, filename))
예제 #49
0
    def add_field(self, *args):
        """ Add field """
        sch = self.shapes.get_schema()
        name = self.new_field_name_entry.get_text()

        for item in sch:
            if item[0].lower() == name.lower():
                error(_("cm_editgrid56811109949513") % name)
                return

        ftype = self.ftype

        try:
            fwidth = int(self.new_field_width_entry.get_text())
        except:
            error(_("cm_editgrid56821109949513"))
            return

        if ftype == 'float':
            try:
                fprec = int(self.new_field_precision_entry.get_text())
            except:
                error(_("cm_editgrid56831109949513"))
                return
        else:
            fprec = 0

        self.shapes.add_field(name.upper(), ftype, fwidth, fprec)
        self.fill_grid()
        if self.shapesgridtool is not None:
            self.shapesgridtool.grid.add_column(name.upper(), ftype, fwidth)
예제 #50
0
    def compute(self, *args):
        def get_band(name):
            layer = self.dict_of_bands[name][1]
            b_num = self.dict_of_bands[name][2]
            band = layer.get_parent().get_dataset().GetRasterBand(b_num + 1)
            return band

        def create_new_layer(pview, player, w, h):
            """Creates new raster layer like <player> with width = w
	    and height = h"""

            gview.app.view_manager.set_active_view(pview)
            pview.viewarea.set_active_layer(player)
            target_ds = player.get_parent().get_dataset()
            rl_mode_value = player.get_mode()
            new_layer = gview.GvRasterLayer( \
     gview.GvRaster(dataset = target_ds,real=1), \
     rl_mode = rl_mode_value)
            pview.viewarea.list_layers().append(new_layer)
            return new_layer

#  extract computing parameters

        b1_name = self.list_of_bands[self.s1_list.get_history()]
        b2_name = self.list_of_bands[self.s2_list.get_history()]
        if b1_name <> None:
            if self.switch_new_view.get_active():
                gview.app.new_view()
            op_index = self.operation.get_history()
            type_index = self.types.get_history()

            a = float(self.a_const.get_text())
            b = float(self.b_const.get_text())
            c = float(self.c_const.get_text())
            b1 = get_band(b1_name)
            b2 = get_band(b2_name)

            type = \
         gdal.GetDataTypeByName(self.types_list[self.types.get_history()])
            self.numtype = gdalnumeric.GDALTypeCodeToNumericTypeCode(type)
            if self.numtype == None:
                gvutils.error("Error! Type " + self.numtype +
                              " is not supported!")
                return FALSE

            proto_ds = self.dict_of_bands[b1_name][1].get_parent().get_dataset(
            )
            op_func = self.operations_dict[self.op][1]
            self.out_buf = Numeric.zeros((b1.YSize, b1.XSize), self.numtype)
            try:
                op_func(s1=b1, s2=b2, a=a, b=b, c=c)
            except:
                gvutils.error("Try to change coefficients.")
                return FALSE
            res_ds = gdalnumeric.OpenArray(self.out_buf, proto_ds)
            gview.app.open_gdal_dataset(res_ds)
            self.close()
        else:
            gvutils.error("Source1 and Source2 have to differ!")
            return FALSE
예제 #51
0
파일: fusion.py 프로젝트: gfwei/code
        def compute(self, bt, id):
            progress = pguprogress.PGUProgressDialog('Merging images',
                                                     cancel=TRUE)
            self.updateFusionInfo()
            fu = self.fus  # for clarity...

            # uncomment to time
            # t0 = time.clock()
            if id == 'pview':
                self.nprv += 1
                fu.reuse = 1
                fu.outfile = 'preview' + str(self.nprv)
            else:
                fu.reuse = 0

            panDS, outDS = fu.prepareDatasets()
            if panDS is None or fu.rgbds is None or outDS is None:
                gvutils.error("Could not open necessary files.")
                progress.destroy()
                return FALSE

            progress.SetDefaultMessage("merged")
            result = fu.fuseBands(panDS, outDS, progress)
            # uncomment to time
            # print time.clock() - t0

            if result:
                if id == 'pview':
                    gview.app.open_gdal_dataset(outDS)
                else:
                    outDS = None
                    del outDS
                    gview.app.open_gdal_dataset(gdal.Open(fu.outfile))
            else:
                outDS = None
                del outDS
                if not fu.reuse:
                    os.remove(outfile)
                gvutils.error("Error merging images.")
                return FALSE
예제 #52
0
    def add_field(self, *args):
        """ Add field """
        import string

        sch = self.shapes.get_schema()
        name = self.new_field_name_entry.get_text()

        for item in sch:
            if string.lower(item[0]) == string.lower(name):
                gvutils.error('Field ' + name + ' already present!')
                return

        ftype = self.new_field_types[self.new_field_type_menu.get_history()]

        try:
            fwidth = int(self.new_field_width_entry.get_text())
        except:
            gvutils.error('Field width must be an integer!')
            return

        if ftype == 'float':
            try:
                fprec = int(self.new_field_precision_entry.get_text())
            except:
                gvutils.error('Precision width must be an integer!')
                return
        else:
            fprec = 0

        self.shapes.add_field(name, ftype, fwidth, fprec)
        self.fill_grid()
        if self.shapesgridtool is not None:
            self.shapesgridtool.refresh_columns()
예제 #53
0
    def add_field(self,*args):
        """ Add field """

        sch=self.shapes.get_schema()
        name=self.new_field_name_entry.get_text()

        for item in sch:
            if item[0].lower() == name.lower():
                gvutils.error('Field '+name+' already present!')
                return


        ftype = self.new_field_types[self.new_field_type_menu.get_history()]


        try:
            fwidth = int(self.new_field_width_entry.get_text())
        except:
            gvutils.error('Field width must be an integer!')
            return

        if ftype == 'float':
            try:
                fprec = int(self.new_field_precision_entry.get_text())
            except:
                gvutils.error('Precision width must be an integer!')
                return
        else:
            fprec = 0

        self.shapes.add_field(name,ftype,fwidth,fprec)
        self.fill_grid()
        if self.shapesgridtool is not None:
            self.shapesgridtool.refresh_columns()
예제 #54
0
파일: fusion.py 프로젝트: EvertS3/code
        def compute(self,bt,id):
            progress = pguprogress.PGUProgressDialog('Merging images',cancel=TRUE)
            self.updateFusionInfo()
            fu = self.fus # for clarity...
    
            # uncomment to time
            # t0 = time.clock()
            if id == 'pview':
                self.nprv+=1
                fu.reuse = 1
                fu.outfile = 'preview'+str(self.nprv)
            else:
                fu.reuse = 0

            panDS,outDS = fu.prepareDatasets()
            if panDS is None or fu.rgbds is None or outDS is None:
                gvutils.error("Could not open necessary files.")
                progress.destroy()
                return FALSE

            progress.SetDefaultMessage("merged")
            result = fu.fuseBands(panDS,outDS,progress)
            # uncomment to time
            # print time.clock() - t0
    
            if result:
                if id == 'pview':
                    gview.app.open_gdal_dataset(outDS)
                else:
                    outDS = None
                    del outDS
                    gview.app.open_gdal_dataset(gdal.Open(fu.outfile))
            else:
                outDS = None
                del outDS
                if not fu.reuse:
                    os.remove(outfile)
                gvutils.error("Error merging images.")
                return FALSE
예제 #55
0
파일: calculator.py 프로젝트: Onjrew/OpenEV
    def compute(self,*args):
        def get_band(name):
	    layer = self.dict_of_bands[name][1]
	    b_num = self.dict_of_bands[name][2]
	    band = layer.get_parent().get_dataset().GetRasterBand(b_num+1)
	    return band	    

	def create_new_layer(pview,player,w,h):
	    """Creates new raster layer like <player> with width = w
	    and height = h"""
        
	    gview.app.view_manager.set_active_view(pview)
	    pview.viewarea.set_active_layer(player)	
    	    target_ds = player.get_parent().get_dataset()
	    rl_mode_value = player.get_mode()
    	    new_layer = gview.GvRasterLayer( \
		gview.GvRaster(dataset = target_ds,real=1), \
		rl_mode = rl_mode_value)
	    pview.viewarea.list_layers().append(new_layer)
	    return new_layer
	
	
	#  extract computing parameters
	b1_name = self.list_of_bands[self.s1_list.get_history()]
	b2_name = self.list_of_bands[self.s2_list.get_history()]
	if b1_name <> None:
	    if self.switch_new_view.get_active():
		gview.app.new_view()
	    op_index = self.operation.get_history()
	    type_index = self.types.get_history()
	
	    a = float(self.a_const.get_text())
	    b = float(self.b_const.get_text())
	    c = float(self.c_const.get_text())
	    b1 = get_band(b1_name)
	    b2 = get_band(b2_name)

	    type = \
		gdal.GetDataTypeByName(self.types_list[self.types.get_history()])
	    self.numtype = gdalnumeric.GDALTypeCodeToNumericTypeCode(type)
	    if self.numtype == None:
		gvutils.error("Error! Type " + self.numtype + " is not supported!")
		return FALSE 
	    
	    proto_ds = self.dict_of_bands[b1_name][1].get_parent().get_dataset()
	    op_func = self.operations_dict[self.op][1]
	    self.out_buf = Numeric.zeros((b1.YSize, b1.XSize), self.numtype)
	    try:
		op_func(s1=b1,s2=b2,a=a,b=b,c=c)
	    except:
		gvutils.error("Try to change coefficients.")
		return FALSE
	    res_ds = gdalnumeric.OpenArray(self.out_buf,proto_ds)
	    gview.app.open_gdal_dataset(res_ds)
	    self.close()
	else:
	    gvutils.error("Source1 and Source2 have to differ!")
	    return FALSE
예제 #56
0
파일: compose.py 프로젝트: lmarabi/tareeg
def getprjinfo():
    fname = GtkExtra.file_sel_box(title="Select GDAL Dataset or WKT text file")
    if fname is None:
        return None
    try:
        fh = gdal.OpenShared(fname)
        prj = fh.GetProjection()
        if prj == '':
            prj = fh.GetGCPProjection()
    except:
        fh = open(fname, 'r')
        prj = string.strip(fh.readline())
        # prj files from shapes seem to have
        # an extra character at the end
        if prj[-1:] == '\x00':
            prj = prj[:-1]

    sr = osr.SpatialReference()
    val = sr.ImportFromWkt(prj)
    if val != 0:
        gvutils.error('Invalid projection information in ' + fname + '!')
        return None

    return prj
예제 #57
0
파일: compose.py 프로젝트: lmarabi/tareeg
    def view_output_cb(self, *args):
        prj = gview.app.sel_manager.get_active_view().get_projection()
        if prj is None:
            gvutils.error('Current view does not contain projection info!')
            self.outprj = ''
            return

        if len(prj) == 0:
            gvutils.error('Current view does not contain projection info!')
            self.outprj = ''
            return

        sr = osr.SpatialReference()
        val = sr.ImportFromWkt(prj)
        if val == 0:
            self.outprj = prj
        else:
            gvutils.error('Current view contains invalid projection info!')
            self.outprj = ''
예제 #58
0
    def analyze_cb(self,*args):
        # Find the view and layer
        cview = self.app.view_manager.get_active_view_window().title
        clayer = self.app.sel_manager.get_active_layer()
        if (cview is None) or (clayer is None):
            # analysis only makes sense in the context of a view and layer
            gvutils.error('No View/Layer selected!')
            return

        text = self.basic_region_analysis(cview,clayer) 

        self.RP_ToolDlg.update_regioninfo_text(text)
        if (self.RP_ToolDlg.button_dict['Log To File'].get_active() == gtk.TRUE):
            log_filename = self.RP_ToolDlg.entry_dict['log_file'].get_text()
            if (len(log_filename) < 2):
                gvutils.error('Log file not set!')
            else:
                try:
                    logfile = open(log_filename,'a')
                    logfile.writelines(text + '\n\n')
                    logfile.close()
                except:
                    err_txt = 'Unable to create or append to ' + log_filename + '.'
                    gvutils.error(err_txt)
예제 #59
0
    def compute(self, *args):
        import re
        ex_exp = self.expression

        type = gdal.GetDataTypeByName(
            self.types_list[self.types.get_history()])
        numtype = gdalnumeric.GDALTypeCodeToNumericTypeCode(type)
        if numtype == None:
            gvutils.error("Error! Type " + numtype + " is not supported!")
            return FALSE

        fun_names_dict = {}
        fun_names_dict["max"] = ("maximum", 2)
        fun_names_dict["min"] = ("minimum", 2)
        fun_names_dict["asin"] = ("arcsin", 1)
        fun_names_dict["acos"] = ("arccos", 1)
        fun_names_dict["atan"] = ("arctan", 1)
        fun_names_dict["AND"] = ("bitwise_and", 2)
        fun_names_dict["OR"] = ("bitwise_or", 2)
        fun_names_dict["XOR"] = ("bitwise_xor", 2)
        fun_names_dict["inv"] = ("invert", 1)
        fun_names_dict["LShift"] = ("left_shift", 2)
        fun_names_dict["RShift"] = ("right_shift", 1)
        fun_names_dict['NDVI'] = ("self.NDVI", 2)

        sh_names_list = fun_names_dict.keys()
        for item in sh_names_list:
            ex_exp = re.sub(item, fun_names_dict[item][0], ex_exp)

        test_exp = ex_exp
        test_array = Numeric.zeros((1, 5), numtype)
        for i in range(len(self.list_of_bands)):
            patt_i = "%" + str(i + 1)
            repl_i = "sb[" + str(i) + "]"
            ex_exp = re.sub(patt_i, repl_i, ex_exp)
            test_exp = re.sub(patt_i, "test_array", test_exp)
        ex_exp = "rb=" + ex_exp
        test_exp = "test_res=" + test_exp

        try:
            exec test_exp
        except:
            gvutils.error("Illegal expression!")
            return FALSE

        if self.switch_new_view.get_active():
            gview.app.new_view()

        b1_name = self.list_of_bands[self.s1_list.get_history()]
        band_list = []
        for i in range(len(self.list_of_bands)):
            band_list.append(self.get_band(self.list_of_bands[i]))
        b1 = self.get_band(b1_name)
        proto_ds = self.dict_of_bands[b1_name][1].get_parent().get_dataset()
        self.out_buf = Numeric.zeros((b1.YSize, b1.XSize), numtype)

        sb = range(len(self.list_of_bands))
        for y in range(b1.YSize):
            for i in range(len(self.list_of_bands)):
                sb[i] = \
                    gdalnumeric.BandReadAsArray(band_list[i],0,y,b1.XSize,1)[0]
            try:
                exec ex_exp
            except:
                gvutils.error("ZeroDivide?")
                return FALSE
            self.out_buf[y, 0:] = clip_result(numtype, rb).astype(numtype)

        res_ds = gdalnumeric.OpenArray(self.out_buf, proto_ds)
        gview.app.open_gdal_dataset(res_ds)
예제 #60
0
    def setup_playing(self, *args):
        if self.view is not None:
            self.tool.deactivate(self.view)

        for view in self.app.view_manager.view_list:
            if view.title == self.viewtitle:
                self.app.view_manager.set_active_view(view)
                self.view = view.viewarea
                self.tool.activate(self.view)
                self.tool.register_view(self.second_view, 0, 1,
                                        self.trail_menu.get_history())
                self.tool.set_trail_color(self.second_view,
                                          self.trail_color.current_color[0],
                                          self.trail_color.current_color[1],
                                          self.trail_color.current_color[2],
                                          self.trail_color.current_color[3])

        # update the secondary view with a background raster
        plyr = self.view.active_layer()
        rst = None
        ds = None
        try:
            rst = plyr.get_parent()
            ds = rst.get_dataset()
        except:
            llist = self.view.list_layers()
            llist.reverse()
            for plyr in llist:
                try:
                    rst = plyr.get_parent()
                    ds = rst.get_dataset()
                    break
                except:
                    pass

        if ds is None:
            gvutils.error('Error- no raster to pan over in active view!')
            return

        dtype = gdal.GetDataTypeName(ds.GetRasterBand(1).DataType)

        xsize = ds.RasterXSize
        ysize = ds.RasterYSize
        while (xsize > 512) and (ysize > 512):
            xsize = xsize / 2
            ysize = ysize / 2

        srcrect = [0, 0, ds.RasterXSize, ds.RasterYSize]
        dstrect = [0, 0, xsize, ysize]

        vrt = vrtutils.VRTDatasetConstructor(xsize, ysize)

        fname = ds.GetDescription()

        lyrs = self.second_view.list_layers()
        for lyr in lyrs:
            self.second_view.remove_layer(lyr)

        gcps = ds.GetGCPs()
        if len(gcps) > 0:
            vrt.SetGCPs(gcps, ds.GetGCPProjection(), None, srcrect, dstrect)
        else:
            gt = ds.GetGeoTransform()
            if gt != (0.0, 1.0, 0.0, 0.0, 0.0, 1.0):
                vrt.SetSRS(ds.GetProjection())
            vrt.SetGeoTransform(gt, srcrect, dstrect, 1)

        for idx in range(0, plyr.sources):
            rst = plyr.get_data(idx)
            if rst is not None:
                cmin = plyr.min_get(idx)
                cmax = plyr.max_get(idx)
                srcdiff = cmax - cmin
                if abs(srcdiff) > 0.0:
                    ratio = 255 / srcdiff
                else:
                    ratio = 1.0
                offset = -cmin * ratio

                vrt.AddSimpleBand(fname,
                                  rst.get_band_number(),
                                  dtype,
                                  srcrect,
                                  dstrect,
                                  ScaleOffset=offset,
                                  ScaleRatio=ratio)

        ds2 = gview.manager.get_dataset(vrt.GetVRTString())
        raster = gview.manager.get_dataset_raster(ds2, 1)
        options = []
        if (ds2.RasterCount == 1):
            raster_layer = gview.GvRasterLayer(raster,
                                               options,
                                               rl_mode=gview.RLM_AUTO)
        else:
            raster_layer = gview.GvRasterLayer(raster,
                                               options,
                                               rl_mode=gview.RLM_RGBA)

            if (raster_layer.get_mode() == gview.RLM_RGBA):

                green_raster = gview.manager.get_dataset_raster(ds2, 2)
                raster_layer.set_source(1, green_raster)
                if (ds2.RasterCount > 2):
                    blue_raster = \
                              gview.manager.get_dataset_raster( ds2, 3 )
                    raster_layer.set_source(2, blue_raster)

                if (ds2.RasterCount > 3):
                    band = ds2.GetRasterBand(4)
                    if (band.GetRasterColorInterpretation() ==
                            gdal.GCI_AlphaBand):
                        raster_layer.blend_mode_set(gview.RL_BLEND_FILTER)
                        alpha_raster = \
                              gview.manager.get_dataset_raster( ds2, 4 )
                        raster_layer.set_source(3, alpha_raster)

        self.second_view.add_layer(raster_layer)

        self.active = 1
        xmin, ymin, xmax, ymax = self.view.get_extents()
        xwidth = xmax - xmin
        ywidth = ymax - ymin
        self.ext = (xmin, ymin, xwidth, ywidth)
        self.tool.set_extents((xmin, ymin, xwidth, ywidth))
        self.playing = 1
        self.tool.set_speed(self.speed)
        self.block_size_changed()
        self.overlap_changed()
        self.tool.play()