Python osgeo.gdal.GDT_UInt16() Examples

The following are code examples for showing how to use osgeo.gdal.GDT_UInt16(). 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: lidar   Author: giswqs   File: slicing.py    MIT License 9 votes vote down vote up
def polygonize(img,shp_path):
    # mapping between gdal type and ogr field type
    type_mapping = {gdal.GDT_Byte: ogr.OFTInteger,
                    gdal.GDT_UInt16: ogr.OFTInteger,
                    gdal.GDT_Int16: ogr.OFTInteger,
                    gdal.GDT_UInt32: ogr.OFTInteger,
                    gdal.GDT_Int32: ogr.OFTInteger,
                    gdal.GDT_Float32: ogr.OFTReal,
                    gdal.GDT_Float64: ogr.OFTReal,
                    gdal.GDT_CInt16: ogr.OFTInteger,
                    gdal.GDT_CInt32: ogr.OFTInteger,
                    gdal.GDT_CFloat32: ogr.OFTReal,
                    gdal.GDT_CFloat64: ogr.OFTReal}

    ds = gdal.Open(img)
    prj = ds.GetProjection()
    srcband = ds.GetRasterBand(1)
    dst_layername = "Shape"
    drv = ogr.GetDriverByName("ESRI Shapefile")
    dst_ds = drv.CreateDataSource(shp_path)
    srs = osr.SpatialReference(wkt=prj)

    dst_layer = dst_ds.CreateLayer(dst_layername, srs=srs)
    raster_field = ogr.FieldDefn('id', type_mapping[srcband.DataType])
    dst_layer.CreateField(raster_field)
    gdal.Polygonize(srcband, srcband, dst_layer, 0, [], callback=None)
    del img, ds, srcband, dst_ds, dst_layer


# convert images in a selected folder to shapefiles 
Example 2
Project: lidar   Author: giswqs   File: slicing.py    MIT License 6 votes vote down vote up
def writeRaster(arr, out_path, template):
    no_data = 0
    # First of all, gather some information from the template file
    data = gdal.Open(template)
    [cols, rows] = arr.shape
    trans = data.GetGeoTransform()
    proj = data.GetProjection()
    # nodatav = 0 #data.GetNoDataValue()
    # Create the file, using the information from the template file
    outdriver = gdal.GetDriverByName("GTiff")
    # http://www.gdal.org/gdal_8h.html
    # GDT_Byte = 1, GDT_UInt16 = 2, GDT_UInt32 = 4, GDT_Int32 = 5, GDT_Float32 = 6,
    outdata   = outdriver.Create(str(out_path), rows, cols, 1, gdal.GDT_UInt32)
    # Write the array to the file, which is the original array in this example
    outdata.GetRasterBand(1).WriteArray(arr)
    # Set a no data value if required
    outdata.GetRasterBand(1).SetNoDataValue(no_data)
    # Georeference the image
    outdata.SetGeoTransform(trans)
    # Write projection information
    outdata.SetProjection(proj)
    return arr


# raster to vector 
Example 3
Project: lidar   Author: giswqs   File: filling.py    MIT License 6 votes vote down vote up
def polygonize(img,shp_path):
    # mapping between gdal type and ogr field type
    type_mapping = {gdal.GDT_Byte: ogr.OFTInteger,
                    gdal.GDT_UInt16: ogr.OFTInteger,
                    gdal.GDT_Int16: ogr.OFTInteger,
                    gdal.GDT_UInt32: ogr.OFTInteger,
                    gdal.GDT_Int32: ogr.OFTInteger,
                    gdal.GDT_Float32: ogr.OFTReal,
                    gdal.GDT_Float64: ogr.OFTReal,
                    gdal.GDT_CInt16: ogr.OFTInteger,
                    gdal.GDT_CInt32: ogr.OFTInteger,
                    gdal.GDT_CFloat32: ogr.OFTReal,
                    gdal.GDT_CFloat64: ogr.OFTReal}

    ds = gdal.Open(img)
    prj = ds.GetProjection()
    srcband = ds.GetRasterBand(1)

    dst_layername = "Shape"
    drv = ogr.GetDriverByName("ESRI Shapefile")
    dst_ds = drv.CreateDataSource(shp_path)
    srs = osr.SpatialReference(wkt=prj)

    dst_layer = dst_ds.CreateLayer(dst_layername, srs=srs)
    # raster_field = ogr.FieldDefn('id', type_mapping[srcband.DataType])
    raster_field = ogr.FieldDefn('id', type_mapping[gdal.GDT_Int32])
    dst_layer.CreateField(raster_field)
    gdal.Polygonize(srcband, srcband, dst_layer, 0, [], callback=None)
    del img, ds, srcband, dst_ds, dst_layer


# extract sinks from dem 
Example 4
Project: surfclass   Author: Kortforsyningen   File: rasterio.py    MIT License 6 votes vote down vote up
def gdaltype_to_creationoptions(gdaltype):
    """Gets GDAL creation options suitable for a GDAL datatype.

    Args:
        gdaltype (int): GDAL datatype value. For instance `osgeo.gdal.GDT_Byte`

    Raises:
        NotImplementedError: If given GDAL data type is not supported.

    Returns:
        list of str: List of GDAL creation options.

    """
    if gdaltype in [
        gdal.GDT_Byte,
        gdal.GDT_Int16,
        gdal.GDT_Int32,
        gdal.GDT_UInt16,
        gdal.GDT_UInt32,
    ]:
        return gdal_int_options
    if gdaltype in [gdal.GDT_Float32, gdal.GDT_Float64]:
        return gdal_float_options
    raise NotImplementedError() 
Example 5
Project: surfclass   Author: Kortforsyningen   File: test_cli_prepare.py    MIT License 6 votes vote down vote up
def test_cli_prepare_lidargrid(cli_runner, las_filepath, tmp_path):
    args = f"prepare lidargrid --srs epsg:25832 -b 727000 6171000 728000 6172000 -r 10 -d Z -d Intensity {las_filepath} {tmp_path}"

    result = cli_runner.invoke(cli, args.split(" "), catch_exceptions=False)
    assert result.exit_code == 0

    outfile = tmp_path / "Z.tif"
    ds = gdal.Open(str(outfile))
    assert ds.GetGeoTransform() == (727000, 10, 0, 6172000, 0, -10)
    assert ds.RasterXSize == 100
    assert ds.RasterYSize == 100
    band = ds.GetRasterBand(1)
    assert band.DataType == gdal.GDT_Float64
    ds = None

    outfile = tmp_path / "Intensity.tif"
    ds = gdal.Open(str(outfile))
    assert ds.GetGeoTransform() == (727000, 10, 0, 6172000, 0, -10)
    assert ds.RasterXSize == 100
    assert ds.RasterYSize == 100
    band = ds.GetRasterBand(1)
    assert band.DataType == gdal.GDT_UInt16
    ds = None 
Example 6
Project: surfclass   Author: Kortforsyningen   File: test_cli_prepare.py    MIT License 6 votes vote down vote up
def test_cli_prepare_lidargrid_multiple_lidarfiles(cli_runner, las_filepath, tmp_path):
    args = f"prepare lidargrid --srs epsg:25832 -b 727000 6171000 728000 6172000 -r 10 -d Z -d Intensity {las_filepath} {las_filepath} {tmp_path}"

    result = cli_runner.invoke(cli, args.split(" "), catch_exceptions=False)
    assert result.exit_code == 0

    outfile = tmp_path / "Z.tif"
    ds = gdal.Open(str(outfile))
    assert ds.GetGeoTransform() == (727000, 10, 0, 6172000, 0, -10)
    assert ds.RasterXSize == 100
    assert ds.RasterYSize == 100
    band = ds.GetRasterBand(1)
    assert band.DataType == gdal.GDT_Float64
    ds = None

    outfile = tmp_path / "Intensity.tif"
    ds = gdal.Open(str(outfile))
    assert ds.GetGeoTransform() == (727000, 10, 0, 6172000, 0, -10)
    assert ds.RasterXSize == 100
    assert ds.RasterYSize == 100
    band = ds.GetRasterBand(1)
    assert band.DataType == gdal.GDT_UInt16
    ds = None 
Example 7
Project: radiometric_normalization   Author: planetlabs   File: gimage.py    Apache License 2.0 5 votes vote down vote up
def create_ds(file_name, xsize, ysize, band_count, compress=True):
    options = ['PHOTOMETRIC=RGB']
    if compress:
        options.append('COMPRESS=DEFLATE')
        options.append('PREDICTOR=2')

    datatype = gdal.GDT_UInt16
    gdal_ds = gdal.GetDriverByName('GTIFF').Create(
        file_name, xsize, ysize, band_count, datatype,
        options=options)
    return gdal_ds 
Example 8
Project: radiometric_normalization   Author: planetlabs   File: gimage_tests.py    Apache License 2.0 5 votes vote down vote up
def setUp(self):
        self.band = numpy.array([[0, 1], [2, 3]], dtype=numpy.uint16)
        self.mask = numpy.array([[0, 1], [0, 1]], dtype=numpy.bool)
        self.metadata = {'geotransform': (-1.0, 2.0, 0.0, 1.0, 0.0, -1.0)}

        self.test_photometric_alpha_image = 'test_photometric_alpha_image.tif'
        test_ds = gdal.GetDriverByName('GTiff').Create(
            self.test_photometric_alpha_image, 2, 2, 4, gdal.GDT_UInt16,
            options=['PHOTOMETRIC=RGB', 'ALPHA=YES'])
        gdal_array.BandWriteArray(test_ds.GetRasterBand(1), self.band)
        gdal_array.BandWriteArray(test_ds.GetRasterBand(2), self.band)
        gdal_array.BandWriteArray(test_ds.GetRasterBand(3), self.band)
        gdal_array.BandWriteArray(test_ds.GetRasterBand(4), self.mask)
        test_ds.SetGeoTransform(self.metadata['geotransform']) 
Example 9
Project: radiometric_normalization   Author: planetlabs   File: gimage_tests.py    Apache License 2.0 5 votes vote down vote up
def test__save_to_ds(self):
        output_file = 'test_save_to_ds.tif'

        test_band = numpy.array([[0, 1], [2, 3]], dtype=numpy.uint16)
        test_gimage = gimage.GImage([test_band], self.mask, self.metadata)
        output_ds = gdal.GetDriverByName('GTiff').Create(
            output_file, 2, 2, 2, gdal.GDT_UInt16,
            options=['ALPHA=YES'])
        gimage._save_to_ds(test_gimage, output_ds, nodata=3)

        # Required for gdal to write to file
        output_ds = None

        test_ds = gdal.Open(output_file)

        saved_number_of_bands = test_ds.RasterCount
        self.assertEquals(saved_number_of_bands, 2)

        saved_band = test_ds.GetRasterBand(1).ReadAsArray()
        numpy.testing.assert_array_equal(saved_band, self.band)

        saved_nodata = test_ds.GetRasterBand(1).GetNoDataValue()
        self.assertEqual(saved_nodata, 3)

        saved_alpha = test_ds.GetRasterBand(2).ReadAsArray()
        numpy.testing.assert_array_equal(saved_alpha, self.mask * 255)

        os.unlink(output_file) 
Example 10
Project: buzzard   Author: airware   File: _gdal_gdt_conv.py    Apache License 2.0 5 votes vote down vote up
def _str_of_gdt(gdt):
    return {
        gdal.GDT_Byte: 'GDT_Byte',
        gdal.GDT_Int16: 'GDT_Int16',
        gdal.GDT_Int32: 'GDT_Int32',
        gdal.GDT_UInt16: 'GDT_UInt16',
        gdal.GDT_UInt32: 'GDT_UInt32',
        gdal.GDT_Float32: 'GDT_Float32',
        gdal.GDT_Float64: 'GDT_Float64',
        gdal.GDT_CFloat32: 'GDT_CFloat32',
        gdal.GDT_CFloat64: 'GDT_CFloat64',
        gdal.GDT_CInt16: 'GDT_CInt16',
        gdal.GDT_CInt32: 'GDT_CInt32',
    }[gdt] 
Example 11
Project: coded   Author: bullocke   File: classify.py    MIT License 5 votes vote down vote up
def create_mask_from_vector(vector_data_path, cols, rows, geo_transform, 
			    projection, target_value=1,
                            output_fname='', dataset_format='MEM'):

    """
    Rasterize the given vector (wrapper for gdal.RasterizeLayer). 
    Return a gdal.Dataset.
    :param vector_data_path: Path to a shapefile
    :param cols: Number of columns of the result
    :param rows: Number of rows of the result
    :param geo_transform: Returned value of gdal.Dataset.GetGeoTransform 
	(coefficients for transforming between pixel/line (P,L) raster space,
	 and projection coordinates (Xp,Yp) space.
    :param projection: Projection definition string (Returned by 
	gdal.Dataset.GetProjectionRef)
    :param target_value: Pixel value for the pixels. Must be a valid 
	gdal.GDT_UInt16 value.
    :param output_fname: If the dataset_format is GeoTIFF, this is the output 
	file name
    :param dataset_format: The gdal.Dataset driver name. [default: MEM]
    """

    driver = ogr.GetDriverByName('ESRI Shapefile')
    data_source = driver.Open(vector_data_path, 0)
    if data_source is None:
        report_and_exit("File read failed: %s", vector_data_path)
    layer = data_source.GetLayer(0)
    driver = gdal.GetDriverByName(dataset_format)
    target_ds = driver.Create(output_fname, cols, rows, 1, gdal.GDT_UInt16)
    target_ds.SetGeoTransform(geo_transform)
    target_ds.SetProjection(projection)
    gdal.RasterizeLayer(target_ds, [1], layer, burn_values=[target_value])
    return target_ds 
Example 12
Project: PyGeoC   Author: lreis2415   File: raster.py    MIT License 5 votes vote down vote up
def raster_reclassify(srcfile, v_dict, dstfile, gdaltype=GDT_Float32):
        """Reclassify raster by given classifier dict.

        Args:
            srcfile: source raster file.
            v_dict: classifier dict.
            dstfile: destination file path.
            gdaltype (:obj:`pygeoc.raster.GDALDataType`): GDT_Float32 as default.
        """
        src_r = RasterUtilClass.read_raster(srcfile)
        src_data = src_r.data
        dst_data = numpy.copy(src_data)
        if gdaltype == GDT_Float32 and src_r.dataType != GDT_Float32:
            gdaltype = src_r.dataType
        no_data = src_r.noDataValue
        new_no_data = DEFAULT_NODATA
        if gdaltype in [GDT_Unknown, GDT_Byte, GDT_UInt16, GDT_UInt32]:
            new_no_data = 0
        if not MathClass.floatequal(new_no_data, src_r.noDataValue):
            if src_r.noDataValue not in v_dict:
                v_dict[src_r.noDataValue] = new_no_data
                no_data = new_no_data

        for (k, v) in iteritems(v_dict):
            dst_data[src_data == k] = v
        RasterUtilClass.write_gtiff_file(dstfile, src_r.nRows, src_r.nCols, dst_data,
                                         src_r.geotrans, src_r.srs, no_data, gdaltype) 
Example 13
Project: geobricks_qgis_plugin_trmm   Author: geobricks   File: conversions.py    GNU General Public License v2.0 5 votes vote down vote up
def UInt16(dataset_or_band):
    return ConvertedDataset(dataset_or_band, gdal.GDT_UInt16) 
Example 14
Project: dfc2019   Author: pubgeo   File: update_msi.py    MIT License 5 votes vote down vote up
def update_msi(input_file_name, output_file_name):
    img = tifffile.imread(input_file_name)
    rows, cols, bands = img.shape
    driver = gdal.GetDriverByName("GTiff")
    output_data = driver.Create(output_file_name, rows, cols, bands, gdal.GDT_UInt16)
    for band in range(0, bands):
        output_band = output_data.GetRasterBand(band + 1)
        output_band.WriteArray(img[:, :, band])
    output_data.FlushCache()
    output_data = None


# main 
Example 15
Project: digital-elevation-model   Author: HeZhang1994   File: pyDEM_function.py    MIT License 5 votes vote down vote up
def write_dem(d_path, d_array, d_row, d_col, d_band, d_gt, d_proj, d_type=gdal.GDT_UInt16, d_frmt='GTiff'):
    '''Write data to a new DEM.

    Parameters:
        d_path <str> -- The path for saving new DEM.
        d_array <numpy.ndarray> -- The data array.
        d_row <int> -- The height of new DEM.
        d_col <int> -- The width of new DEM.
        d_band <int> -- The band number of new DEM.
        d_gt <tuple> -- The 6 GeoTransform parameters of new DEM.
        d_proj <str> -- The GCS/PCS information of new DEM.
        d_type <str> -- The data type of new DEM. Default is gdal.GDT_UInt16.
        d_frmt <str> -- The data format of new DEM. Default is 'GTiff'.

    Return:
        0 <int> -- If writing to new DEM is completed.
    '''
    if len(d_array.shape) == 3:
        d_band, d_row, d_col = d_array.shape
    elif len(d_array.shape) == 2:
        d_array = np.array([d_array])
    else:
        d_band, (d_row, d_col) = 1, d_array.shape

    driver = gdal.GetDriverByName(d_frmt)
    data = driver.Create(d_path, d_col, d_row, d_band, d_type)  # (col, row)
    if(data is not None):
        data.SetGeoTransform(d_gt)
        data.SetProjection(d_proj)
    for i in range(d_band):
        data.GetRasterBand(i + 1).WriteArray(d_array[i])
    del data

    return 0 
Example 16
Project: HistoricalMap   Author: nkarasiak   File: function_dataraster.py    GNU General Public License v2.0 4 votes vote down vote up
def open_data_band(filename):
    """!@brief The function open and load the image given its name. 
    The function open and load the image given its name. 
    The type of the data is checked from the file and the scipy array is initialized accordingly.
        Input:
            filename: the name of the file
        Output:
            data : the opened data with gdal.Open() method
            im : empty table with right dimension (array)
    
    """
    data = gdal.Open(filename,gdal.GA_ReadOnly)
    if data is None:
        print 'Impossible to open '+filename
        exit()
    nc = data.RasterXSize
    nl = data.RasterYSize
#    d  = data.RasterCount
    
    # Get the type of the data
    gdal_dt = data.GetRasterBand(1).DataType
    if gdal_dt == gdal.GDT_Byte:
        dt = 'uint8'
    elif gdal_dt == gdal.GDT_Int16:
        dt = 'int16'
    elif gdal_dt == gdal.GDT_UInt16:
        dt = 'uint16'
    elif gdal_dt == gdal.GDT_Int32:
        dt = 'int32'
    elif gdal_dt == gdal.GDT_UInt32:
        dt = 'uint32'
    elif gdal_dt == gdal.GDT_Float32:
        dt = 'float32'
    elif gdal_dt == gdal.GDT_Float64:
        dt = 'float64'
    elif gdal_dt == gdal.GDT_CInt16 or gdal_dt == gdal.GDT_CInt32 or gdal_dt == gdal.GDT_CFloat32 or gdal_dt == gdal.GDT_CFloat64 :
        dt = 'complex64'
    else:
        print 'Data type unkown'
        exit()
    
    # Initialize the array
    im = sp.empty((nl,nc),dtype=dt) 
    return data,im 
Example 17
Project: HistoricalMap   Author: nkarasiak   File: function_dataraster.py    GNU General Public License v2.0 4 votes vote down vote up
def create_empty_tiff(outname,im,d,GeoTransform,Projection):
    '''!@brief Write an empty image on the hard drive.
    
    Input: 
        outname: the name of the file to be written
        im: the image cube
        GeoTransform: the geotransform information 
        Projection: the projection information
    Output:
        Nothing --
    '''
    nl = im.shape[0]
    nc = im.shape[1]

    driver = gdal.GetDriverByName('GTiff')
    dt = im.dtype.name
    # Get the data type
    if dt == 'bool' or dt == 'uint8':
        gdal_dt=gdal.GDT_Byte
    elif dt == 'int8' or dt == 'int16':
        gdal_dt=gdal.GDT_Int16
    elif dt == 'uint16':
        gdal_dt=gdal.GDT_UInt16
    elif dt == 'int32':
        gdal_dt=gdal.GDT_Int32
    elif dt == 'uint32':
        gdal_dt=gdal.GDT_UInt32
    elif dt == 'int64' or dt == 'uint64' or dt == 'float16' or dt == 'float32':
        gdal_dt=gdal.GDT_Float32
    elif dt == 'float64':
        gdal_dt=gdal.GDT_Float64
    elif dt == 'complex64':
        gdal_dt=gdal.GDT_CFloat64
    else:
        print 'Data type non-suported'
        exit()
    
    dst_ds = driver.Create(outname,nc,nl, d, gdal_dt)
    dst_ds.SetGeoTransform(GeoTransform)
    dst_ds.SetProjection(Projection)
    
    return dst_ds
    
    '''
    Old function that cannot manage to write on each band outside the script
    '''
#    if d==1:
#        out = dst_ds.GetRasterBand(1)
#        out.WriteArray(im)
#        out.FlushCache()
#    else:
#        for i in range(d):
#            out = dst_ds.GetRasterBand(i+1)
#            out.WriteArray(im[:,:,i])
#            out.FlushCache()
#    dst_ds = None