-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuav_plot_clip.py
executable file
·114 lines (81 loc) · 2.71 KB
/
uav_plot_clip.py
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#!/usr/bin/env python3
"""
Author : Emmanuel Gonzalez
Date : 2020-12-17
Purpose: UAV plotclip
"""
import argparse
import os
import sys
import numpy as np
import rasterio
import rasterio.mask
import geopandas as gpd
import multiprocessing
# --------------------------------------------------
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Rock the Casbah',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('tif',
nargs='+',
metavar='str',
help='A positional argument')
parser.add_argument('-g',
'--geojson',
help='GeoJSON of plot boundaries',
metavar='str',
type=str,
required=True)
parser.add_argument('-c',
'--cpu',
help='CPUs for multiprocessing',
metavar='cpu',
type=int,
required=True)
return parser.parse_args()
# --------------------------------------------------
def open_geojson(geojson_path):
shp = gpd.read_file(geojson_path)
geom_dict = {}
cnt = 0
for i, row in shp.iterrows():
cnt += 1
geom = row['geometry']
plot_num = row['ID']
geom_dict[cnt] = {
'geometry': geom,
'plot': plot_num
}
return geom_dict
# --------------------------------------------------
def process_image(image):
args = get_args()
f_name = os.path.splitext(os.path.basename(image))[-2]
geom_dict = open_geojson(args.geojson)
src = rasterio.open(image)
array = src.read(1)
for k, v in geom_dict.items():
geom = v['geometry']
plot = v['plot']
out_dir = os.path.join(f_name, str(int(plot)))
if not os.path.isdir(out_dir):
os.makedirs(out_dir)
out_image, out_transform = rasterio.mask.mask(src, geom, crop=True, nodata=np.nan, filled=False)
out_meta = src.meta
out_meta.update({"driver": "GTiff",
"height": out_image.shape[1],
"width": out_image.shape[2],
"transform": out_transform})
with rasterio.open(f'{out_dir}/{plot}_plotclip.tif', "w", **out_meta) as dest:
dest.write(out_image)
# --------------------------------------------------
def main():
"""Process images here"""
args = get_args()
with multiprocessing.Pool(args.cpu) as p:
p.map(process_image, args.tif)
# --------------------------------------------------
if __name__ == '__main__':
main()