Friday, 7 October 2016

clip - Rasterizing shapefile with rasterio and gdal gives all cells 0 values




I am trying to rasterize my shapefile (20 polygons) with rasterio and fiona and turn the new raster into a mask for clipping.


I need to rasterize my all polygons in my shapefile and turn on mask and clip my raster tif with mask how can I do it ?


This is my first script, but that it give just value 0 all mask black.



import rasterio as rio 
import fiona
import rasterio
import rasterio.mask

with fiona.open("C:/.../poly.shp", "r") as shapefile:
shapes = [feature["geometry"] for feature in shapefile]

with rasterio.open("D:/.../MODIS_EVI_2006.tif") as src:
out_image, out_transform = rasterio.mask.mask(src, shapes, crop=True)

out_meta = src.meta.copy()

out_meta.update({"driver": "GTiff",
"height": out_image.shape[1],
"width": out_image.shape[2],
"transform": out_transform})

with rasterio.open("mask2006.tif", "w", **out_meta) as dest:
dest.write(out_image)


I'm also trying with gdal.RasterizeLayer and I had the same result.


from osgeo import gdal
from osgeo import ogr
from osgeo import gdalconst

ndsm = 'D:/../MODIS_EVI_2000.tif'
shp = 'C:/Doy2000/Pivos/1996poly.shp'
data = gdal.Open(ndsm, gdalconst.GA_ReadOnly)
geo_transform = data.GetGeoTransform()
#source_layer = data.GetLayer()

x_min = geo_transform[0]
y_max = geo_transform[3]
x_max = x_min + geo_transform[1] * data.RasterXSize
y_min = y_max + geo_transform[3] * data.RasterYSize
x_res = data.RasterXSize
y_res = data.RasterYSize
mb_v = ogr.Open(shp)
mb_l = mb_v.GetLayer()
pixel_width = geo_transform[1]
output = 'C:/Doy2000/Pivos/my2000.tif'

target_ds = gdal.GetDriverByName('GTiff').Create(output, x_res, y_res, 1, gdal.GDT_Byte)
target_ds.SetGeoTransform((x_min, pixel_width, 0, y_min, 0, pixel_width))
band = target_ds.GetRasterBand(1)
NoData_value = -999999
band.SetNoDataValue(NoData_value)
band.FlushCache()
gdal.RasterizeLayer(target_ds, [1], mb_l, options=["ATTRIBUTE=hedgerow"])

target_ds = None


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...