Python osgeo.gdal.UseExceptions() Examples

The following are code examples for showing how to use osgeo.gdal.UseExceptions(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyIntertidalDEM   Author: jamal919   File: core.py    Apache License 2.0 6 votes vote down vote up
def read(self, fname, band=1):
        '''
        Read band data from a file.

        arguments:
            fname: string, file location
            band: integer, band number

        Raise an exception if data can not be read.

        '''

        gdal.UseExceptions()
        try:
            dset = gdal.Open(fname, gdal.GA_ReadOnly)
            self.geotransform = dset.GetGeoTransform()
            self.projection = dset.GetProjectionRef()
            self.data = dset.GetRasterBand(band).ReadAsArray().astype(np.float)
        except:
            raise Exception('Band: read error!') 
Example 2
Project: geobricks_qgis_plugin_trmm   Author: geobricks   File: gdal_dataset.py    GNU General Public License v2.0 6 votes vote down vote up
def __init__(self,cols,rows,bands,datatype,srs='',gt=[],nodata=[]):
        use_exceptions=gdal.GetUseExceptions()
        gdal.UseExceptions()

        #print cols,rows,bands,datatype,srs,gt,nodata
        if Env.tempdir == '/vsimem':
            #Test to see if enough memory
            tmpdriver=gdal.GetDriverByName('MEM')
            tmpds=tmpdriver.Create('',cols,rows,bands,datatype)
            tmpds=None
            del tmpds

            self._filedescriptor=-1
            self._filename='/vsimem/%s.tif'%tempfile._RandomNameSequence().next()

        else:
            self._filedescriptor,self._filename=tempfile.mkstemp(suffix='.tif')

        NewDataset.__init__(self,self._filename,'GTIFF',
                            cols,rows,bands,datatype,srs,gt,
                            options=Env.tempoptions) 
Example 3
Project: buzzard   Author: airware   File: tools.py    Apache License 2.0 5 votes vote down vote up
def make_tif2(path, reso=(1., -1.), rsize=(10, 10), tl=(0., 10.),
              proj=SRS[0]['wkt'], channel_count=1, dtype=gdal.GDT_Float32,
              nodata=-32000, nodata_border_size=(0, 0, 0, 0)):
    """Create a tiff files"""
    reso = np.asarray(reso)
    fp = buzz.Footprint(tl=tl, rsize=rsize, size=np.abs(reso * rsize))
    x, y = fp.meshgrid_raster
    a = x + y
    if nodata_border_size != 0:
        l, r, t, b = nodata_border_size
        if t != 0:
            a[None:t, None:None] = nodata
        if b != 0:
            a[-b:None, None:None] = nodata
        if l != 0:
            a[None:None, None:l] = nodata
        if r != 0:
            a[None:None, -r:None] = nodata

    LOGGER.info('TIFF ARRAY:%s\n', a)
    gdal.UseExceptions()
    driver = gdal.GetDriverByName('GTiff')
    dataset = driver.Create(path, int(rsize[0]), int(rsize[1]), channel_count, dtype)
    dataset.SetGeoTransform(fp.gt)
    dataset.SetProjection(proj)
    for i in range(channel_count):
        dataset.GetRasterBand(i + 1).WriteArray(a)
        dataset.GetRasterBand(i + 1).SetNoDataValue(nodata)
    dataset.FlushCache() 
Example 4
Project: geobricks_qgis_plugin_trmm   Author: geobricks   File: gdal_dataset.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self,filepath_or_dataset=None,*args):
        gdal.UseExceptions()

        fp=filepath_or_dataset

        if type(fp) is gdal.Dataset:
            self._dataset = fp
        elif fp is not None:
            if os.path.exists(fp):
                self._dataset = gdal.Open(os.path.abspath(fp),*args)
            else:
                self._dataset = gdal.Open(fp,*args)

        #Issue 8
        self._gt=self.GetGeoTransform()
        if self._gt[5] > 0: #positive NS pixel res.
            tmp_ds = gdal.AutoCreateWarpedVRT(self._dataset)
            tmp_fn = '/vsimem/%s.vrt'%tempfile._RandomNameSequence().next()
            self._dataset = gdal.GetDriverByName('VRT').CreateCopy(tmp_fn,tmp_ds)
            self._gt = self.GetGeoTransform()

        self._x_size=self.RasterXSize
        self._y_size=self.RasterYSize
        self._nbands=self.RasterCount
        self._bands=range(self.RasterCount)
        self._data_type=self.GetRasterBand(1).DataType
        self._srs=self.GetProjectionRef()
        self._block_size=self.GetRasterBand(1).GetBlockSize()
        self._nodata=[b.GetNoDataValue() for b in self]
        
        self.extent=self.__get_extent__() 
Example 5
Project: geobricks_qgis_plugin_trmm   Author: geobricks   File: gdal_dataset.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self,filename,outformat='GTIFF',
                 cols=None,rows=None,bands=None,datatype=None,
                 srs='',gt=[],nodata=[],options=[],prototype_ds=None):
        use_exceptions=gdal.GetUseExceptions()
        gdal.UseExceptions()

        if prototype_ds is not None:
            if cols is None:cols=prototype_ds._x_size
            if rows is None:rows=prototype_ds._y_size
            if bands is None:bands=prototype_ds._nbands
            if datatype is None:datatype=prototype_ds._data_type
            if not srs:srs=prototype_ds._srs
            if not gt:gt=prototype_ds._gt
            if nodata==[]:nodata=prototype_ds._nodata
        else:
            if cols is None:raise TypeError('Expected "cols" or "prototype_ds", got None')
            if rows is None:raise TypeError('Expected "rows" or "prototype_ds", got None')
            if bands is None:raise TypeError('Expected "bands" or "prototype_ds", got None')
            if datatype is None:raise TypeError('Expected "datatype" or "prototype_ds", got None')
            if not gt:gt=(0.0, 1.0, 0.0, 0.0, 0.0, 1.0)

        self._filename=filename
        self._driver=gdal.GetDriverByName(outformat)
        self._dataset=self._driver.Create (self._filename,cols,rows,bands,datatype,options)

        if not use_exceptions:gdal.DontUseExceptions()
        self._dataset.SetGeoTransform(gt)
        self._dataset.SetProjection(srs)
        for i,val in enumerate(nodata[:bands]):
            try:self._dataset.GetRasterBand(i+1).SetNoDataValue(val)
            except TypeError:pass
        Dataset.__init__(self) 
Example 6
Project: geobricks_qgis_plugin_trmm   Author: geobricks   File: gdal_dataset.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self,dataset_or_band, wkt_srs, snap_ds=None, snap_cellsize=None):

        use_exceptions=gdal.GetUseExceptions()
        gdal.UseExceptions()

        self._simple_fn='/vsimem/%s.vrt'%tempfile._RandomNameSequence().next()
        self._warped_fn='/vsimem/%s.vrt'%tempfile._RandomNameSequence().next()

        try:                   #Is it a Band
            orig_ds=dataset_or_band.dataset._dataset
        except AttributeError: #No, it's a Dataset
            orig_ds=dataset_or_band._dataset

        try: #Generate a warped VRT
            warped_ds=gdal.AutoCreateWarpedVRT(orig_ds,orig_ds.GetProjection(),wkt_srs, Env.resampling)
            #AutoCreateWarpedVRT doesn't create a vsimem filename and we need one
            warped_ds=gdal.GetDriverByName('VRT').CreateCopy(self._warped_fn,warped_ds)

        except Exception as e:
            raise RuntimeError('Unable to project on the fly. '+e.message)

        #Disable the following check as this will allow us to use a WarpedDataset to
        #resample Datasets and creating an AutoCreateWarpedVRT where input srs==output srs
        #will allways fail the test below...
        #if warped_ds.GetGeoTransform()==orig_ds.GetGeoTransform():
        #    raise RuntimeError('Unable to project on the fly. Make sure all input datasets have projections set.')

        if snap_ds:warped_ds=self._modify_vrt(warped_ds, orig_ds, snap_ds, snap_cellsize)
        self._dataset=self._create_simple_VRT(warped_ds,dataset_or_band)

        if not use_exceptions:gdal.DontUseExceptions()
        Dataset.__init__(self) 
Example 7
Project: geobricks_qgis_plugin_trmm   Author: geobricks   File: gdal_dataset.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self,array,extent=[],srs='',gt=[],nodata=[],prototype_ds=None):
        use_exceptions=gdal.GetUseExceptions()
        gdal.UseExceptions()

        #datatype=gdal_array.NumericTypeCodeToGDALTypeCode(array.dtype.type)
        #Work around numexpr issue #112 - http://code.google.com/p/numexpr/issues/detail?id=112
        #until http://trac.osgeo.org/gdal/ticket/5223 is implemented.
        datatype=gdal_array.NumericTypeCodeToGDALTypeCode(array.view(str(array.dtype)).dtype.type)

        if array.ndim==2:
            rows,cols=array.shape
            bands=1
        else:
            rows,cols,bands=array.shape

        if prototype_ds:
            if not gt:gt=prototype_ds._gt
            if not srs:srs=prototype_ds._srs
            if not nodata:nodata=prototype_ds._nodata

        if extent:
            xmin,ymin,xmax,ymax=extent
            px,py=(xmax-xmin)/cols,(ymax-ymin)/rows
            gt=[xmin,px,0,ymax,0,-py]

        TemporaryDataset.__init__(self,cols,rows,bands,datatype,srs,gt,nodata)
        self.write_data(array,0,0) 
Example 8
Project: dsarsim   Author: adamoferro   File: image.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self,size=(0,0),ps=(0,0),value=None,nodatav=-9999):
        
        gdal.UseExceptions()
        
        self.matrix_type=numpy.float32
        self.file_type=gdal.GDT_Float32

        self.image=None
        self.size=size
        self.pixel_size=ps
        self.nodatav=nodatav

        if value is not None:
            self.empty(value) 
Example 9
Project: geoTriMesh   Author: flatpolar   File: mesh2.py    Apache License 2.0 5 votes vote down vote up
def __init__(self):
        gdal.UseExceptions()
        pass 
Example 10
Project: geoTriMesh   Author: flatpolar   File: mesh.py    Apache License 2.0 5 votes vote down vote up
def __init__(self):
        gdal.UseExceptions()
        pass 
Example 11
Project: mapit-za   Author: Code4SA   File: views.py    MIT License 4 votes vote down vote up
def convert_address(request, format='json'):
    address = request.GET.get('address')
    if not address:
        raise ViewException(format, 'No address was provided.', 400)

    converter = AddressConverter()
    locations = converter.resolve_address(address, partial=bool(request.GET.get('partial')))

    # this is a copy from mapit.views.areas.areas_by_point
    # because it's hard to reuse their code :(

    if PYGDAL:
        from osgeo import gdal
        gdal.UseExceptions()

    # we find areas for every lat/long coord we got back
    areas = []
    type = request.GET.get('type', '')
    for coords in locations:
        location = Point(float(coords['lng']), float(coords['lat']), srid=4326)
        try:
            location.transform(settings.MAPIT_AREA_SRID, clone=True)
        except:
            raise ViewException(format, _('Point outside the area geometry'), 400)

        args = query_args(request, format)
        if type:
            args = dict(("area__%s" % k, v) for k, v in args.items())
            # So this is odd. It doesn't matter if you specify types, PostGIS will
            # do the contains test on all the geometries matching the bounding-box
            # index, even if it could be much quicker to filter some out first
            # (ie. the EUR ones).
            coords['areas'] = []
            args['polygon__bbcontains'] = location
            shapes = Geometry.objects.filter(**args).defer('polygon')
            for shape in shapes:
                try:
                    area = Area.objects.get(polygons__id=shape.id, polygons__polygon__contains=location)
                    coords['areas'].append(str(area.id))
                    areas.append(area)
                except:
                    pass
        else:
            geoms = list(Geometry.objects.filter(polygon__contains=location).defer('polygon'))
            args['polygons__in'] = geoms
            matches = Area.objects.filter(**args).all()
            coords['areas'] = [str(m.id) for m in matches]
            areas.extend(matches)

    areas = add_codes(areas)
    if format == 'html':
        return output_html(request, _("Areas matching the address '{0}'").format(address), areas, indent_areas=True)

    # hack to include the geocoded addresses in the results
    data = iterdict(chain(
        ((area.id, area.as_dict()) for area in areas),
        [("addresses", locations)]))
    return output_json(data)