-
Notifications
You must be signed in to change notification settings - Fork 0
/
dem_nan_ratio.py
executable file
·92 lines (63 loc) · 2.11 KB
/
dem_nan_ratio.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
dem_nan_ratio.py
-------------
Calculates the ratio between NaN to all pixel of the image and plots the images.
Usage: dem_nan_ratio.py --data=<path> [--p]
dem_nan_ratio.py -h | --help
Options:
-h | --help Show this screen
--data Input file
--p Plot the result
"""
##########
# IMPORT #
##########
import os, sys
import numpy as np
from osgeo import gdal
from matplotlib import pyplot as plt
import docopt
#############
# FUNCTIONS #
#############
def read_from_file(input_file):
ds = gdal.OpenEx(input_file, allowed_drivers=['GTiff'])
ds_band = ds.GetRasterBand(1)
values = ds_band.ReadAsArray(0, 0, ds.RasterXSize, ds.RasterYSize)
ncol, nrow = ds.RasterXSize, ds.RasterYSize
nodata = ds_band.GetNoDataValue()
return (values, ncol, nrow, nodata)
def convert_to_binary(dem, nodata):
out = np.zeros_like(dem)
out[dem <= nodata] = 0
out[dem > nodata] = 1
return out
def plot_binary(dem_binary, input_file):
fig, ax = plt.subplots()
ax.imshow(dem_binary)
ax.set_title('Binary Mask')
filename = os.path.basename(input_file)
out_path = os.path.dirname(input_file)
fig.savefig(os.path.join(out_path, '{}_binary.pdf'.format(filename.split('.')[0])), format='PDF', dpi=150)
plt.show()
def calculate_nan_ratio(input_file, plot):
dem_data = read_from_file(input_file)
dem, ncol, nrow, nodata = dem_data[0], dem_data[1], dem_data[2], dem_data[3]
dem_binary = convert_to_binary(dem, nodata)
# count 0 and 1 values
unique, counts = np.unique(dem_binary, return_counts=True)
count_results = dict(zip(unique, counts))
print('Number of NaN pixel: {}'.format(count_results[0]))
print('Total number of pixel: {}'.format(dem_binary.size))
print('Ratio NaN to DEM pixel: {}'.format(count_results[0]/dem_binary.size))
if(plot):
plot_binary(dem_binary, input_file)
########
# MAIN #
########
arguments = docopt.docopt(__doc__)
input_file = arguments['--data']
plot = arguments['--p']
calculate_nan_ratio(input_file, plot)