-
Notifications
You must be signed in to change notification settings - Fork 26
/
ExtractValues.py
executable file
·159 lines (137 loc) · 4.93 KB
/
ExtractValues.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
#! /usr/bin/env python
#######################################################################################################
#
# ExtractValues.py
#
# A python script to extract raster values using a shapefile and parralel proessing.
# Results are stored in a CSV file
#
# Author: Javier Lopatin
# Email: javierlopatin@gmail.com
# Date: 09/08/2016
# Version: 1.0
#
# Info: Several statistics are allowed when applied to polygon shapefiles, including:
# - min
# - max
# - mean [default]
# - count
# - sum
# - std
# - median
# - majority
# - minority
# - unique
# - range
# - nodata
# - percentile
#
# Usage:
#
# python ExtractValues.py -r <Imput raster> -s <Imput shapefile>
# -i <Imput function> -s <Shapefile ID> -p <If shp are points>
#
# Examples for polygon shapefile: python ExtractValues.py -r raster.tif -s shape.shp -i ID
# python ExtractValues.py -r raster.tif -s shape.shp -f median -i ID
#
# Examples for points shapefile: python ExtractValues.py -r raster.tif -s shape.shp -i ID -p
#
########################################################################################################
import os
import argparse
import sys
import pandas as pd
import numpy as np
import multiprocessing
from joblib import Parallel, delayed
from tqdm import tqdm
import rasterio
try:
from rasterstats import zonal_stats
except ImportError:
print("ERROR: Could not import rasterstats Python library.")
print("Check if rasterstats is installed.")
try:
import shapefile
except ImportError:
print("ERROR: Could not import PyShp Python library.")
print("Check if PyShp is installed.")
def ExtractValues(raster, shp, func, ID, num_cores, points):
""" Extract raster values by a shapefile mask.
Several statistics are allowed.
"""
# read raster properties
with rasterio.open(raster) as r:
count = r.count
# band names
bandNames = []
for i in range(count):
a = "B" + str(i+1)
bandNames.append(a)
# Shapefile management
shape = shapefile.Reader(shp)
records = pd.DataFrame(shape.records())
n = pd.DataFrame(shape.fields)[0].values.tolist().index(ID)
id = records[n-1]
# Extract values
if points == True:
def _function(i, shp, raster):
stats = point_query(shp, raster, band=i+1)
return pd.DataFrame(stats)
else:
def _function(i, shp, raster):
stats = zonal_stats(shp, raster, stats=func, band=i+1)
return pd.DataFrame(stats)
# parallel processing
stats = Parallel(n_jobs=num_cores)(delayed(_function)(i, shp, raster)
for i in tqdm(range(count)))
# set the final data frame
df = pd.concat(stats, axis=1) # concatenate all dataframes into one
df.columns = bandNames # add colum names
df.index = id # and shapefile ID to index
# save data to .CSV file
name = os.path.basename(raster)
name2 = os.path.basename(shp)
df.to_csv(name[:-4] + "_" + name2[:-4] +".csv", index=False, header=True, na_rep='NA')
if __name__ == "__main__":
# create the arguments for the algorithm
parser = argparse.ArgumentParser()
parser.add_argument('-r', '--raster', help='Input raster', type=str)
parser.add_argument('-s', '--shapefile', help='Input shapefile', type=str)
parser.add_argument(
'-f', '--function', help='Input function to extract [default = "mean"]', type=str, default="mean")
parser.add_argument('-i', '--id', help='Shapefile ID to store in the CSV', type=str)
parser.add_argument('-p', '--points', help='Shapefile are points',
action="store_true", default=False)
parser.add_argument('-c', '--cores', help='Number of cores in parallel processing',
type=int, default=4)
parser.add_argument('--version', action='version', version='%(prog)s 1.0')
args = vars(parser.parse_args())
# run Extraction
raster = args['raster']
shp = args['shapefile']
ID = args['id']
func = args['function']
num_cores = args['cores']
points = args['points']
# Check that the input parameter has been specified.
if raster == None:
# Print an error message if not and exit.
print("Error: No input image file provided.")
sys.exit()
if shp == None:
# Print an error message if not and exit.
print("Error: No input shapefile file provided.")
sys.exit()
if ID == None:
# Print an error message if not and exit.
print("Error: No input id provided.")
sys.exit()
if func == None:
# Print an error message if not and exit.
print("Error: No extracting function provided.")
sys.exit()
if points == True:
ExtractValues(raster, shp, ID, num_cores, points)
else:
ExtractValues(raster, shp, func, ID, num_cores, points)