Re: Using rasterio to mask/crop a raster results in AttributeError


Yves Moisan
 

Hi,


You have a len = 1 list the only element of which is a string.  That's what the error message tells you, essentially.  Get rid of the quotes and you'l have a one-item list the which is your dict :


 var2 = [{ "type": "Polygon", "coordinates": [ [ [ 0.906372070312503, 52.320232076097348 ], [ 0.823974609375, 52.108192097463231 ], [ 1.170043945312496, 52.141916831668233 ], [ 1.170043945312496, 52.313516199748072 ], [ 0.906372070312503, 52.320232076097348 ] ] ] }]
>>> type(var2)
<class 'list'>
>>> type(var2[0])
<class 'dict'>

Cheers,

I'm trying to use rasterio to mask a raster. According to the mask documentation, I need to load a raster file in 'r' mode, which I have done like so:

file = rasterio.open('/data/corine2018_100m/test.tif')
print(file)
<open DatasetReader name='/data/corine2018_100m/test.tif' mode='r'>

I also need a shapes which is an iterable GeoJSON-like object. I have GeoJSON serialised a Polygon object from a Django PolygonField() and added it to a list (my interpretation of the documentation's 'iterable object'):

obj = newJob.objects.create(job_loc="SRID=4326;POLYGON ((0.9063720703125029 52.32023207609735, 0.8239746093749998 52.10819209746323, 1.170043945312496 52.14191683166823, 1.170043945312496 52.31351619974807, 0.9063720703125029 52.32023207609735))")

poly = [obj.job_loc.geojson]
print(poly)
['{ "type": "Polygon", "coordinates": [ [ [ 0.906372070312503, 52.320232076097348 ], [ 0.823974609375, 52.108192097463231 ], [ 1.170043945312496, 52.141916831668233 ], [ 1.170043945312496, 52.313516199748072 ], [ 0.906372070312503, 52.320232076097348 ] ] ] }']

print(type(poly))
<class 'list'>

I then attempt the mask with:

masked_band, masked_transform = rasterio.mask.mask(file, poly, crop=True)

However, I get the error:

AttributeError: 'str' object has no attribute 'get'

I have tried following this (i.e. adding my JSON to a list) but I still get the error. Can someone help me mask this raster?


Join main@rasterio.groups.io to automatically receive all group messages.