Example #1
0
def raster_pixel_to_polygon(src_tif_path,
                            dst_shp_path,
                            all_bands_as_feature=False,
                            crs=None,
                            return_gdf=False):
    """
    crs should be dict type 'epsg:<epsg_code>', e.g. 'epsg:4326'
    """
    rows, cols, bands, geo_transform, projection, dtype_gdal, no_data_value, metadata = tgp.get_raster_info(
        src_tif_path)
    X = tgp.get_raster_data(src_tif_path)
    idxs = np.where(np.ones_like(X[:, :, 0], dtype=bool))
    rows = []

    for row_idx, col_idx in zip(*idxs):
        row = {}
        npidx = (row_idx, col_idx)
        row['geometry'] = Polygon(
            tgp.npidxs_to_coord_polygons([npidx], geo_transform)[0])
        if all_bands_as_feature:
            for i in range(X.shape[2]):
                row['band' + str(i + 1)] = X[row_idx, col_idx, i]
        rows.append(row)
    df_shp = gpd.GeoDataFrame(rows, geometry='geometry')
    if crs:
        df_shp.crs = crs
    if return_gdf:
        return df_shp
    else:
        df_shp.to_file(dst_shp_path)
Example #2
0
def tif_composition(ref_tif_path,
                    src_tif_paths,
                    dst_tif_path,
                    dst_tif_dtype_gdal=None):
    """
    ref_tif_path: should be used to create the canvas with final coordinate system, geo_transform and projection, 
    src_tif_paths: should be in list type with elements with full path of tif images.
    dst_tif_path: output file path
    """
    # get geo info
    rows, cols, bands, geo_transform, projection, dtype_gdal, no_data_value, metadata = tgp.get_raster_info(
        ref_tif_path)
    if dst_tif_dtype_gdal:
        dtype_gdal = dst_tif_dtype_gdal

    # cal bands count
    bands_for_each_tif = [
        tgp.get_raster_info(tif_path)[2] for tif_path in src_tif_paths
    ]
    bands = sum(bands_for_each_tif)

    # bands compositions: create new tif
    dst_ds = gdal.GetDriverByName('GTiff').Create(dst_tif_path, cols, rows,
                                                  bands, dtype_gdal)
    dst_ds.SetGeoTransform(geo_transform)
    dst_ds.SetProjection(projection)

    # bands compositions: write bands
    band_num = 1
    for tif_path, bands_for_the_tif in zip(src_tif_paths, bands_for_each_tif):
        nparr = tgp.get_raster_data(tif_path)
        for band_num_for_the_tif in range(bands_for_the_tif):
            band = dst_ds.GetRasterBand(band_num)
            band.WriteArray(nparr[:, :, band_num_for_the_tif], 0, 0)
            band.FlushCache()
            if no_data_value:
                band.SetNoDataValue(no_data_value)
            band_num += 1
    dst_ds = None