forked from JavierLopatin/Python-Remote-Sensing-Scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
clip.py
executable file
·53 lines (40 loc) · 1.32 KB
/
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Clipping a raster image with a shapefile
Usage: python clip.py -r raster.tif -s shapefile.shp
Created on Tue Oct 23 16:32:37 2018
@author: Javier Lopatin | [email protected]
"""
import rasterio
import rasterio.mask
import fiona
import argparse
# create the arguments for the algorithm
parser = argparse.ArgumentParser()
# set arguments
parser.add_argument('-r', '--inputRaster', help='Input raster', type=str, required=True)
parser.add_argument('-s', '--inputshape', help='Input shapefile', type=str, required=True)
parser.add_argument('--version', action='version', version='%(prog)s 1.0')
args = vars(parser.parse_args())
# set argument
raster = args["inputRaster"]
shp = args["inputshape"]
# load shapefile shapes
with fiona.open(shp, "r") as shapefile:
features = [feature["geometry"] for feature in shapefile]
# open and crop raster
print("Clipping raster...")
with rasterio.open(raster) as src:
img, transform = rasterio.mask.mask(src, features, crop=True)
meta = src.meta.copy()
meta.update({"driver": "GTiff",
"height": img.shape[1],
"width": img.shape[2],
"transform": transform})
# output name
output = raster[:-4] + "_mask.tif"
# save
with rasterio.open(output, 'w', **meta) as dst:
dst.write(img)
print("Done!")