-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclip-rast
executable file
·56 lines (41 loc) · 1.02 KB
/
clip-rast
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#!/usr/bin/env python3
# Author: Daniel Rode
# Created: 14 Nov 2024
# Updated: -
# Description: Clip a given raster file to a polygon.
import sys
from sys import exit
from pathlib import Path
import pyogrio
import rasterio
import rasterio.mask
HELP_TEXT = "Usage: clip-rast RAST GEOM OUT_RAST"
# Parse command line arguments
args = sys.argv[1:]
try:
rast_path = Path(args[0])
shape_path = Path(args[1])
out_path = Path(args[2])
except IndexError:
print(HELP_TEXT)
exit(1)
# Import polygon data
shapes = pyogrio.read_dataframe(shape_path)["geometry"]
shapes = shapes.head(10)
# Import region of raster data within polygons
with rasterio.open(rast_path) as f:
rast, rast_transform = rasterio.mask.mask(f, shapes, crop=True)
rast_meta = f.meta
# Save clipped raster to file
rast_meta.update({
"driver": "GTiff",
"height": rast.shape[1],
"width": rast.shape[2],
"transform": rast_transform,
})
with rasterio.open(out_path, "w", **rast_meta) as f:
f.write(rast)
"""
TODO
- is any reprojection necessary?
"""