Reputation: 11
I am trying to clip the raster file with geojson file. both files have same coordinates system and overlap. here is my code and i am getting the error ( TypeError: can't multiply sequence by non-int of type 'Affine')
shape_geojson=path of jeojson
input_file= path of geotiff filesenter code here
with open(shape_geojson) as data_file:
geoms= json.load(data_file)
geoms = [{'type': 'Polygon', 'coordinates': [[[372187.1496072686, 5068258.904150674, 0.0],
[373626.0661280414, 5068286.477440579, 0.0], [373548.73687596567, 5069922.161341429, 0.0],
[372152.12599016255, 5069847.257662993, 0.0], [372187.1496072686, 5068258.904150674, 0.0]]]}]
for file in os.listdir(input_file):
with rio.open(os.path.join(input_file, file)) as src:
out_image, out_transform = rio.mask.mask(src, geoms, 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})
Error
TypeError: can't multiply sequence by non-int of type 'Affine'
Upvotes: 1
Views: 781
Reputation: 328
Rob's answer got me close, but my coords were nested.
Ended up having to do this:
def is_mappable_of_floats(x):
try:
float(x[0])
return True
except:
return False
def coords_3d_to_2d(coords):
_coords = []
for coord in coords:
if is_mappable_of_floats(coord):
_coords.append((coord[0], coord[1]))
else:
_coords.append(coords_3d_to_2d(coord))
return _coords
geoms = [
{
"type": g["type"],
"coordinates": coords_3d_to_2d(g["coordinates"]),
}
for g in geoms
]
Upvotes: 0
Reputation: 31156
Very unusually your polygons are defined in 3D coordinates. Change them to 2D and the error goes away. Provide the URL of your raster and a full MWE can be shown.
geoms2d = [
{
"type": g["type"],
"coordinates": [[xyz[0:2] for xyz in p] for p in g["coordinates"]],
}
for g in geoms
]
out_image, out_transform = rasterio.mask.mask(src, geoms2d, crop=True)
Upvotes: 1