1

I have shapefile that intersects with a raster but do not fully overlap :

enter image description here

I would like to clip the raster with this shapefile but every time I try I get this error message:

ValueError: Input shapes do not overlap raster.

I have tried two methods to clip the raster: once with rasterio:

#get coordinates of shapefile
def getFeatures(gdf):
      """Function to parse features from GeoDataFrame in such a manner that rasterio wants them"""
       import json
       return [json.loads(gdf.to_json())['features'][0]['geometry']]

coords = getFeatures(plots)

out_img, out_transform = mask(img,coords, crop=True)

and once with earthpy:

crop=es.crop_image(img,plots)

both give me the same errors.

This is how I read the shape and the image:

#load shapefile
poly = geopandas.read_file(r'very\nice\path\and\polygon.shp')


#determine projection for shape and change it into the image projection
poly.crs = {'init' :'epsg:4326'}
poly=poly.to_crs({'init': 'epsg:32721'})

#Load image
img=rasterio.open(r'what\a\wonderful\path\image.tif')

after this I used the methods that demonstrated.

How can I clip the raster with the polygon even if they are not the overlap 100%?

Edit:

I have tried this:

out_image, out_meta = es.crop_image(img, plots.geometry)

and also the same with rasterio as was suggested here but for some reason it clips only for the extent of the shape but not to the actual shape:

enter image description here

1 Answer 1

1

You can simplify the solution (without a function like def getFeatures(gdf))

import rasterio 
out_image, out_transform = rasterio.mask.mask(img, poly.geometry, crop=True)

enter image description hereenter image description here

Same with EarthPy

  out_image, out_meta = es.crop_image(img, poly.geometry)
2
  • thank you for your answer, I have tried it but the results I get is clip to the polygon extent and not to the actual shape like in your image , do you have any idea why would it occur?
    – ReutKeller
    Jun 18, 2020 at 10:36
  • The result is a clip of the original raster (coloured) to the polygon extent (grey raster)
    – gene
    Jun 18, 2020 at 13:37

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.