3

How can I get every pixel separated? When I calc unique values, if two pixels have the same value, it converts in one row in the final shape. I need every single pixel converted into one unique geometry.

Any ideas?

My code is:

def geojsonizer(ndvi_path, downloads_path, ndvi_date, UHC_name):
    entry_date = datetime.today().strftime('%Y%m%d')
    # Read input band with Rasterio
    with rasterio.open(ndvi_path) as raster_ndvi:
        crs = raster_ndvi.crs
        huso = str(crs).replace(':', '')
        src_band = raster_ndvi.read(1)
        # Keep track of unique pixel values in the input band
        unique_values = np.unique(src_band)
        # Polygonize with Rasterio. `shapes()` returns an iterable
        # of (geom, value) as tuples
        shapes = list(rasterio.features.shapes(src_band, transform=raster_ndvi.transform))
    
    geojson_schema = {
        'geometry': 'MultiPolygon',
        'properties': {'name': 'str', 'pixel_id': 'int', 'ndvi_value': 'float', 'ndvi_date': 'str',
                       'entry_date': 'str'}
    }
    with fiona.open(downloads_path + '\\' + UHC_name + '_' + huso + '_ndvi.geojson', 'w', driver='GeoJSON',
                    schema=geojson_schema, crs=crs) as geojson:
        for pixel_value in unique_values:
            if pixel_value != 999 and pixel_value != 0:
                polygons = [shape(geom) for geom, value in shapes
                            if value == pixel_value]
                multipolygon = MultiPolygon(polygons)
                pixel_centroid = (str(multipolygon.centroid).strip('POINT ()')).replace(" ", "")
                geojson.write({
                    'geometry': mapping(multipolygon),
                    'properties': {'name': 'nombre_finca',
                                   'pixel_id': pixel_centroid,
                                   'ndvi_value': float(pixel_value),
                                   'ndvi_date': str(ndvi_date),
                                   'entry_date': entry_date,
                                   }})
2
  • 1
    This sounds like an X-Y problem, why do you want to convert your raster to geojson?
    – Ian Turton
    Commented Feb 5, 2020 at 16:39
  • np.unique delete all duplicated values of the raster. It works for all the area out of my AOI, but fails when two of my pixels have the same value. In this case, merge the two same value pixels in one multipolygon entry of the final geojson.
    – Alex_rdq
    Commented Feb 5, 2020 at 16:56

1 Answer 1

1

Having the size of the image and the number of pixels you should be able to create a grid in a loop (Substitute the hardcoded values of x/y min/max and width/height [number of pixels] for values read from your raster):


import numpy as np
from shapely.geometry import shape
import geopandas as gpd

xmin, ymin, xmax, ymax = -532000, -868000,  484000, 16000
width = 4000
height = 4000
rows = np.ceil((ymax - ymin) / height) + 1
cols = np.ceil((xmax - xmin) / width) + 1
# start grid cell envelope
x_min_corn = xmin
x_max_corn = xmin + width
y_max_corn = ymax
y_min_corn = ymax - height
# create grid cells
countcols = 0
grid_polygons = []
sp_id = 0
while countcols < cols:
    # reset envelope for rows
    y_max_ring = y_max_corn
    y_min_ring = y_min_corn
    countrows = 0

    while countrows < rows:
        polygon = {
            "type": "Polygon",
            "coordinates": (
                (
                    (x_min_corn, y_max_ring),
                    (x_max_corn, y_max_ring),
                    (x_max_corn, y_min_ring),
                    (x_min_corn, y_min_ring),
                    (x_min_corn, y_max_ring),
                ),
            ),
        }

        grid_polygons.append(shape(polygon))
        sp_id += 1
        # new envelope for next poly
        y_max_ring = y_max_ring - height
        y_min_ring = y_min_ring - height
        countrows += 1
    # new envelope for next poly
    x_min_corn = x_min_corn + width
    x_max_corn = x_max_corn + width

    countcols += 1

gdf = gpd.GeoDataFrame(geometry=grid_polygons)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.