def polygonize_pmap(pmap_ds: gdal.Dataset, pmap_threshold=131, layer_name='unknown.gpkg', path_out=None) -> gdal.Dataset: pmap_bin_img = (pmap_ds.ReadAsArray() > pmap_threshold).astype(np.uint8) pmap_bin_ds = add_ref_to_img(pmap_bin_img, pmap_ds) # srs = osr.SpatialReference() srs.ImportFromWkt(pmap_ds.GetProjectionRef()) # if path_out is None: ds_out = ogr.GetDriverByName('MEMORY').CreateDataSource('wrk') # ds_out = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource(f'/vsimem/{layer_name}.shp') else: drv = ogr.GetDriverByName('GPKG') if os.path.isfile(path_out): drv.DeleteDataSource(path_out) ds_out = drv.CreateDataSource(path_out) layer_name = os.path.splitext(os.path.basename(path_out))[0] ds_layer = ds_out.CreateLayer(layer_name, geom_type=ogr.wkbPolygon, srs=srs) fd = ogr.FieldDefn('DN', ogr.OFTInteger) ds_layer.CreateField(fd) dst_field = 0 # path_pmap = '/home/ar/data/uiip/quarry_data_test/s2_u8_t3_msk.tif' ds_band = pmap_bin_ds.GetRasterBand(1) gdal.Polygonize(ds_band, ds_band, ds_layer, dst_field, [], callback=gdal.TermProgress) return ds_out
def load_from_dataset(self, image_dataset: gdal.Dataset) -> Image: geo_transform = self._load_geotransform(image_dataset) projection = image_dataset.GetProjection() pixels = image_dataset.ReadAsArray() if pixels.ndim > 2: pixels = pixels.transpose(1, 2, 0) return Image(pixels, geo_transform, projection)
def load_from_dataset_and_clip(self, image_dataset: gdal.Dataset, extent: GeoPolygon) -> Image: geo_transform = self._load_geotransform(image_dataset) pixel_polygon = extent.to_pixel(geo_transform) bounds = [int(bound) for bound in pixel_polygon.polygon.bounds] pixels = image_dataset.ReadAsArray(bounds[0], bounds[1], bounds[2] - bounds[0], bounds[3] - bounds[1]) subset_geo_transform = geo_transform.subset(x=bounds[0], y=bounds[1]) pixel_polygon = extent.to_pixel(subset_geo_transform) if pixels.ndim > 2: pixels = pixels.transpose(1, 2, 0) return Image(pixels, subset_geo_transform, image_dataset.GetProjection())\ .clip_with(pixel_polygon, mask_value=0)
def gdal_to_json(ds: gdal.Dataset): gt = ds.GetGeoTransform(can_return_null=True) xsize = ds.RasterXSize ysize = ds.RasterYSize srs = get_srs(ds) srs = srs.ExportToProj4() minx = gt[0] + gt[1] * 0 + gt[2] * 0 miny = gt[3] + gt[4] * 0 + gt[5] * 0 maxx = gt[0] + gt[1] * xsize + gt[2] * ysize maxy = gt[3] + gt[4] * xsize + gt[5] * ysize bbox = miny, minx, maxy, maxx band_list = range(1, ds.RasterCount + 1) data = [ ds.ReadAsArray(band_list=[bnd]).ravel().tolist() for bnd in band_list ] ndv = [ds.GetRasterBand(i).GetNoDataValue() for i in band_list] result = dict(bbox=bbox, gt=gt, srs=srs, size=(xsize, ysize), data=data, ndv=ndv) return result