forked from kendrik-wah/cs3237_weather_nowcasting
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wr_rain_pred.py
397 lines (289 loc) · 11.9 KB
/
wr_rain_pred.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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
# -*- coding: utf-8 -*-
"""CS3237_wr_rain_pred.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1q0nOgrfmsGDrrW0jbj8YfIqrYMkCyLu1
"""
"""
Before running this code:
1. Clone the RainNet's repository
2. Download the RainNet's pretrained weights and CNN rain classifier weights
3. Install cmapy package (used to import custom colormaps for use in OpenCV)
"""
import io
import os
from PIL import Image
import cv2
import cmapy
import matplotlib.colors as mcolors
import numpy as np
import requests
from datetime import datetime
from dateutil import tz
from numpy import asarray
import time
from rainnet import rainnet
from keras.models import load_model
################################
# Helper functions for RainNet #
################################
cmap_data = [(1.0, 1.0, 1.0),
(0.3137255012989044, 0.8156862854957581, 0.8156862854957581),
(0.0, 1.0, 1.0),
(0.0, 0.8784313797950745, 0.501960813999176),
(0.0, 0.7529411911964417, 0.0),
(0.501960813999176, 0.8784313797950745, 0.0),
(1.0, 1.0, 0.0),
(1.0, 0.6274510025978088, 0.0),
(1.0, 0.0, 0.0),
(1.0, 0.125490203499794, 0.501960813999176),
(0.9411764740943909, 0.250980406999588, 1.0),
(0.501960813999176, 0.125490203499794, 1.0)]
# (0.250980406999588, 0.250980406999588, 1.0),
# (0.125490203499794, 0.125490203499794, 0.501960813999176),
# (0.125490203499794, 0.125490203499794, 0.125490203499794),
# (0.501960813999176, 0.501960813999176, 0.501960813999176),
# (0.8784313797950745, 0.8784313797950745, 0.8784313797950745),
# (0.9333333373069763, 0.8313725590705872, 0.7372549176216125),
# (0.8549019694328308, 0.6509804129600525, 0.47058823704719543),
# (0.6274510025978088, 0.42352941632270813, 0.23529411852359772),
# (0.4000000059604645, 0.20000000298023224, 0.0)]
precipitation_cmap = mcolors.ListedColormap(cmap_data, 'precipitation')
def Scaler(array):
return np.log(array+0.01)
def invScaler(array):
return np.exp(array) - 0.01
def pad_to_shape(array, from_shape=900, to_shape=928, how="mirror"):
# calculate how much to pad in respect with native resolution
padding = int( (to_shape - from_shape) / 2)
# for input shape as (batch, W, H, channels)
if how == "zero":
array_padded = np.pad(array, ((0,0),(padding,padding),(padding,padding),(0,0)), mode="constant", constant_values=0)
elif how == "mirror":
array_padded = np.pad(array, ((0,0),(padding,padding),(padding,padding),(0,0)), mode="reflect")
return array_padded
def pred_to_rad(pred, from_shape=928, to_shape=900):
# pred shape 12,928,928
padding = int( (from_shape - to_shape) / 2)
return pred[::, padding:padding+to_shape, padding:padding+to_shape].copy()
def data_preprocessing(X):
# 0. Right shape for batch
X = np.moveaxis(X, 0, -1)
X = X[np.newaxis, ::, ::, ::]
# 1. To log scale
X = Scaler(X)
# 2. from 900x900 to 928x928
X = pad_to_shape(X)
return X
def data_postprocessing(nwcst):
# 0. Squeeze empty dimensions
nwcst = np.squeeze(np.array(nwcst))
# 1. Convert back to rainfall depth
nwcst = invScaler(nwcst)
# 2. Convert from 928x928 back to 900x900
nwcst = pred_to_rad(nwcst)
# 3. Return only positive values
nwcst = np.where(nwcst>0, nwcst, 0)
return nwcst
def prediction(model_instance, input_data, lead_time):
input_data = data_preprocessing(input_data)
nwcst = []
print("Forecasting the probability of rain within the next {} minutes...\n".format(lead_time*15))
for i in range(lead_time):
# make prediction
pred = model_instance.predict(input_data)
# print(pred.dtype)
# pred_copy = pred.squeeze()
# pred_copy = cv2.normalize(pred_copy, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8U)
# print(pred_copy.shape, type(pred_copy))
# heatmap = cv2.applyColorMap(pred_copy, cmapy.cmap(precipitation_cmap))
# cv2.imwrite('prediction_{}.png'.format(i), heatmap)
# append prediction to holder
nwcst.append(pred)
# append prediction to the input shifted on one step ahead
input_data = np.concatenate([input_data[::, ::, ::, 1:], pred], axis=-1)
nwcst = data_postprocessing(nwcst)
new_nwcst = cv2.normalize(nwcst[lead_time - 1], None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8U)
heatmap = cv2.applyColorMap(new_nwcst, cmapy.cmap(precipitation_cmap))
#cv2.imwrite(output_img_name, heatmap)
#for i in range(lead_time):
#new_nwcst = cv2.normalize(nwcst[i], None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8U)
#heatmap = cv2.applyColorMap(new_nwcst, cmapy.cmap(precipitation_cmap))
#cv2.imwrite('nwcst_{}.png'.format(i), heatmap)
return heatmap
######################################
# Helper functions for rain_pred_CNN #
######################################
def generate_timestamp(look_back=10):
timestamps = []
first_img = True
from_zone = tz.gettz('UTC')
to_zone = tz.gettz('Asia/Singapore')
utc = datetime.utcnow()
# Change timezone from UTC to Singapore time
utc = utc.replace(tzinfo=from_zone)
# Convert time zone
sg_time = utc.astimezone(to_zone)
year = '2020'
month = '11'
day = str(sg_time.strftime("%d"))
hour = int(sg_time.strftime("%H"))
minute = int(sg_time.strftime("%M"))
minute -= 10
if (minute < 0):
minute += 60
hour -= 1
second = '0000'
while(minute % 5 != 0):
minute -= 1
while (len(timestamps) < look_back):
minute = str(minute)
if (minute == '0'):
minute = '00'
if (minute == '5'):
minute = '05'
if len(str(hour)) == 1:
hour = '0' + str(hour)
name = year + month + day + str(hour) + str(minute) + second
timestamps.append(name)
minute = int(minute)
minute -= 15
if (minute < 0):
hour -= 1
minute += 60
if (hour < 0):
day = str(int(day) - 1)
hour = 23
if first_img:
#print("\nCollecting weather radar images for the current timestamp (2020-11-17-13-10-0000) and 30 minutes before...".format(year, month, day, hour, minute, second))
print("\nCollecting weather radar images for the current timestamp ({}-{}-{}-{}-{}-{}) and 30 minutes before...".format(year, month, day, hour, minute, second))
first_img = False
#timestamps.reverse() # reverse list so that the oldest timestamp is first in the list
return timestamps
def download_SG_data(name):
try:
startTime = time.time()
url = "http://www.weather.gov.sg/files/rainarea/50km/v2/dpsri_70km_{}dBR.dpsri.png".format(name)
r = requests.get(url)
with open('rainnet/live/{}.png'.format(name), 'wb') as f:
f.write(r.content)
print("Downloaded", url)
print("Time Taken:", time.time() - startTime)
return True
except:
print("unable to fetch")
return False
def resize_image(image):
imageName = image
image = Image.open('rainnet/live/{}.png'.format(imageName))
new_image = image.resize((900,900)).convert("L")
# new_image.save('rainnet/live/{}.png'.format(imageName)) # for debugging
data = asarray(new_image)
# print(data.shape) # for debugging
return data
def concat_images(timestamp_list):
prev = []
downloaded_imgs = []
for i in timestamp_list:
if (download_SG_data(i)):
downloaded_imgs.append(i)
if (len(downloaded_imgs) > 3):
break
downloaded_imgs.reverse()
for i in downloaded_imgs:
current = resize_image(i)
if i == downloaded_imgs[-1]:
latest = current
else:
prev.append(current)
S_latest = np.concatenate([prev, latest[np.newaxis, ::, ::]], axis=0)
# print(S_latest.shape) # for debugging
S_latest_timestep = downloaded_imgs[-1]
# print(S_latest_timestep) # for debugging
print("All images collected.\n")
return S_latest
def load_image(image_fname):
img = cv2.imread(image_fname)
# Resize the colored images to (450 x 450)
# Too bad that the Google Colab GPU doesn't have enough
# memory for me to train the CNN with a bigger input size.
img = cv2.resize(img,(450,450))
return img
def white2black(image):
new_img = image
white_px = np.asarray([255, 255, 255])
black_px = np.asarray([0 , 0 , 0 ])
(row, col, _) = image.shape
for r in range(row):
for c in range(col):
px = image[r][c]
if all(px == white_px):
new_img[r][c] = black_px
cv2.imwrite('nwcst_b.png', new_img)
return new_img
def predict_rain(wr_image, rain_pred_CNN):
# Use custom CNN to classfiy radar images as "rain" or "no_rain"
# image = load_image(wr_image)
image = white2black(wr_image) # convert to black background (because training images had black background)
# Resize the colored images to (450 x 450)
# Too bad that the Google Colab GPU doesn't have enough
# memory for me to train the CNN with a bigger input size.
image = cv2.resize(image,(450,450))
image = np.array(image)/255.0 # scale pixel values
image = np.expand_dims(image, axis=0) # change dimensions to (1, 450, 450, 3)
result = rain_pred_CNN.predict(image)
pr_rain = result[0][0]
if result[0][0] >= 0.5:
is_rain = True
#print("{} prediction: rain with probability {}".format(filename, result[0][0]))
else:
is_rain = False
#print("{} prediction: no rain with probability {}".format(filename, 1- result[0][0]))
return is_rain, pr_rain
def download_Overlay_data():
try:
url = "http://www.weather.gov.sg/wp-content/themes/wiptheme/images/SG-Township.png".format()
r = requests.get(url)
with open('rainnet/live/SG_Township.png', 'wb') as f:
f.write(r.content)
except:
print("unable to fetch")
def resize_image_pred(image):
# imageName = image
# image = Image.open('./{}.png'.format(imageName))
new_image = Image.fromarray(image).resize((853, 479)).convert("RGBA")
# overlay = Image.open('rainnet/live/{}.png'.format('SG_Township')).convert("RGBA")
#new_image.paste(overlay, (0, 0), overlay)
#new_image.save('rainnet/predictions/{}.png'.format(imageName))
#data = asarray(new_image)
# print(data.shape)
return new_image
def overlay_SG_map(pred_wr_img):
new_image = resize_image_pred(pred_wr_img)
overlay = Image.open('rainnet/live/{}.png'.format('SG_Township')).convert("RGBA")
new_image.paste(overlay, (0, 0), overlay)
new_image.save('rainnet/predictions/sg_nwcst.png')
data = asarray(new_image)
# print(data.shape) # for debugging
def load_models():
RN_model = rainnet.rainnet()
RN_model.load_weights("rainnet_weights.h5")
rain_pred_CNN = load_model("rain_classifier.h5")
return RN_model, rain_pred_CNN
def CNN_get_rain_prediction(lead_time=2):
print("Loading CNN models...")
RN_model , rain_pred_CNN = load_models()
print("Done!\n\n")
timestamp_list = generate_timestamp()
#timestamp_list = ['2020111713350000', '2020111713200000','2020111713050000', '2020111712500000']
#timestamp_list = ['2020111715000000', '2020111714450000','2020111714300000', '2020111714150000']
#print(timestamp_list)
SG_latest = concat_images(timestamp_list)
#print(SG_latest.shape)
pred_wr_img = prediction(RN_model, SG_latest, lead_time)
download_Overlay_data()
overlay_SG_map(pred_wr_img)
is_rain, pr_rain = predict_rain(pred_wr_img, rain_pred_CNN)
return is_rain, pr_rain
# Set lead_time (in hours) to be larger than 1
# CNN_get_rain_prediction(lead_time=4)