-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathdeep_learning_crop.R
1718 lines (1308 loc) · 52.2 KB
/
deep_learning_crop.R
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Script: Applying deep learning to satellite imagery to map rice crops in the local GPU ------------------------------------------------------------
# Author: Ricardo Dal'Agnol da Silva (ricds@hotmail.com)
# Date Created: 2021-08-09
# R version 4.1.0 (2021-05-18)
#
## What this script does?
## i) Start with a raw satellite image
## ii) Overlay it with samples and crop the data into patches
## iii) Train a DL model, use the DL model to predict the class for all image
## This step can be done in local machine with GPU or Google Colab
## iv) Combine the prediction (multiple patches) into a single mosaic
## v) Assess map accuracy quantitatively and qualitatively (visually)
## vi) Compare results with a previously produced Random Forests map
# clean environment
rm(list = ls()); gc()
# general libraries
library(pacman) # install.packages("pacman")
p_load(raster,
rgdal,
rgeos,
gdalUtils,
sp,
leaflet,
mapview,
magick,
sf,
parallel, doParallel, foreach,
caret
)
# directory to tensorflow python environment
## this is required if running DL in the local computer with GPU, otherwise you can run the DL in Google Colab
## this is only if you have a GPU and want to run in your own computer
## Guide to install here: https://doi.org/10.5281/zenodo.3929709
tensorflow_dir = "C:\\ProgramData\\Miniconda3\\envs\\r-tensorflow"
# set working directory
## here you need to set up your own directory containing the dataset
## https://zenodo.org/record/5504554/files/DL_Unet_CropExample_dataset.rar
setwd("D:\\2_Projects\\7_Presentation_Classes\\19_Minicourse_DeepLearning_Satellite\\")
# number of cores
no_cores = 7
# path to the gdal files and to the osgeo .bat (to run mosaic function)
## in case you don't have this installed, you need to download it from https://www.osgeo.org/projects/osgeo4w/
gdal_path = "C:\\OSGeo4W\\bin\\"
osgeo_path = "C:\\OSGeo4W"
# directory in the computer to save images
output_dir = "2_Images\\"
dir.create(output_dir, showWarnings = FALSE)
# functions ---------------------------------------------------------------
# function to extract data from a raster (x) from a SpatialPolygons object (y) faster than extract()
fast_extract = function(x,y) {
value = list()
for (i in 1:length(y)) {
tmp = crop(x, y[i,])
#value[[i]] = extract(tmp, y[i,])
value[[i]] = as.numeric(na.omit(mask(tmp, y[i,])[]))
rm(tmp)
}
return(value)
}
# function to extract data from a raster (x) from a SpatialPolygons object (y) faster than extract()
fast_extract_parallel = function(x,y) {
# libraries needed
require(parallel) # install.packages("parallel")
require(doParallel) # install.packages("doParallel")
require(foreach) # install.packages("foreach")
# Begin cluster
cl = parallel::makeCluster(detectCores()-1) # here you specify the number of processors you want to use, if you dont know you can use detectCores() and ideally use that number minus one
#cl = parallel::makeCluster(3, outfile="D:/r_parallel_log.txt") # if you use this you can see prints in the txt
registerDoParallel(cl)
# apply the model in parallel
# sometimes you need to specify in the package parameter (.packages) the name of package of the functions you are using
value = foreach(i=1:length(y)) %dopar% { # note the %dopar% here
require(raster)
return(as.numeric(na.omit(mask(crop(x, y[i,]), y[i,])[])))
}
return(value)
}
# function to get the sp with the extent of a raster object
rasext_to_sp = function(x) {
y = as(extent(x), "SpatialPolygons")
crs(y) = crs(x)
return(y)
}
# convert raster to vector using gdal_polygonize
# this version accept the python path and poligonizer path separetely
polygonizer_v2 <- function(x, outshape=NULL, pypath=NULL, polipath = NULL, readpoly=TRUE,
fillholes=FALSE, aggregate=FALSE,
quietish=TRUE) {
# x: an R Raster layer, or the file path to a raster file recognised by GDAL
# outshape: the path to the output shapefile (if NULL, a temporary file will
# be created)
# pypath: the path to gdal_polygonize.py or OSGeo4W.bat (if NULL, the function
# will attempt to determine the location)
# readpoly: should the polygon shapefile be read back into R, and returned by
# this function? (logical)
# fillholes: should holes be deleted (i.e., their area added to the containing
# polygon)
# aggregate: should polygons be aggregated by their associated raster value?
# quietish: should (some) messages be suppressed? (logical)
if (isTRUE(readpoly) || isTRUE(fillholes)) require(rgdal)
#cmd <- Sys.which(paste0(pypath, '\\OSGeo4W.bat'))
cmd = pypath
if (is.null(pypath) | is.null(polipath)) {
stop("Could not find gdal_polygonize.py or OSGeo4W on your system.")
}
if (!is.null(outshape)) {
outshape <- sub('\\.shp$', '', outshape)
f.exists <- file.exists(paste(outshape, c('shp', 'shx', 'dbf'), sep='.'))
if (any(f.exists))
stop(sprintf('File already exists: %s',
toString(paste(outshape, c('shp', 'shx', 'dbf'),
sep='.')[f.exists])), call.=FALSE)
} else outshape <- tempfile()
if (is(x, 'Raster')) {
require(raster)
writeRaster(x, {f <- tempfile(fileext='.tif')})
rastpath <- normalizePath(f)
} else if (is.character(x)) {
rastpath <- normalizePath(x)
} else stop('x must be a file path (character string), or a Raster object.')
# system2(cmd, args=(
# sprintf('"%s" "%s" %s -f "ESRI Shapefile" "%s.shp"',
# pypath, rastpath, ifelse(quietish, '-q ', ''), outshape)))
system2(cmd, sprintf('"%s" "%s" %s -f "ESRI Shapefile" "%s.shp"',
polipath, rastpath, ifelse(quietish, '-q ', ''), outshape))
if(isTRUE(aggregate)||isTRUE(readpoly)||isTRUE(fillholes)) {
shp <- readOGR(dirname(outshape), layer=basename(outshape),
verbose=!quietish)
} else return(NULL)
if (isTRUE(fillholes)) {
poly_noholes <- lapply(shp@polygons, function(x) {
Filter(function(p) p@ringDir==1, x@Polygons)[[1]]
})
pp <- SpatialPolygons(mapply(function(x, id) {
list(Polygons(list(x), ID=id))
}, poly_noholes, row.names(shp)), proj4string=CRS(proj4string(shp)))
shp <- SpatialPolygonsDataFrame(pp, shp@data)
if(isTRUE(aggregate)) shp <- aggregate(shp, names(shp))
writeOGR(shp, dirname(outshape), basename(outshape),
'ESRI Shapefile', overwrite=TRUE)
}
if(isTRUE(aggregate) & !isTRUE(fillholes)) {
shp <- aggregate(shp, names(shp))
writeOGR(shp, dirname(outshape), basename(outshape),
'ESRI Shapefile', overwrite=TRUE)
}
ifelse(isTRUE(readpoly), return(shp), return(NULL))
}
# function from spatial.tools (does not work in R4.0.2 yet so we copied from previous version)
modify_raster_margins = function (x, extent_delta = c(0, 0, 0, 0), value = NA)
{
x_extents <- extent(x)
res_x <- res(x)
x_modified <- x
if (any(extent_delta < 0)) {
ul_mod <- extent_delta[c(1, 3)] * res_x
ul_mod[ul_mod > 0] <- 0
lr_mod <- extent_delta[c(2, 4)] * res_x
lr_mod[lr_mod > 0] <- 0
crop_extent <- c(x_extents@xmin, x_extents@xmax, x_extents@ymin,
x_extents@ymax)
crop_extent[c(1, 3)] <- crop_extent[c(1, 3)] - ul_mod
crop_extent[c(2, 4)] <- crop_extent[c(2, 4)] + lr_mod
x_modified <- crop(x_modified, crop_extent)
}
if (any(extent_delta > 0)) {
ul_mod <- extent_delta[c(1, 3)] * res_x
ul_mod[ul_mod < 0] <- 0
lr_mod <- extent_delta[c(2, 4)] * res_x
lr_mod[lr_mod < 0] <- 0
extend_extent <- c(x_extents@xmin, x_extents@xmax, x_extents@ymin,
x_extents@ymax)
extend_extent[c(1, 3)] <- extend_extent[c(1, 3)] - ul_mod
extend_extent[c(2, 4)] <- extend_extent[c(2, 4)] + lr_mod
x_modified <- extend(x_modified, extend_extent, value = value)
}
return(x_modified)
}
# split the extent of a sp object
split_extent_gdal = function(x, block_size = 1000, na_rm = T, remove_all_zero = T, gdal_path = NULL) {
if (is.null(gdal_path)) stop("Missing GDAL path.")
# x = LIDAR_ANA_2017
# x = LIDAR_ST1_2016
x_ext = extent(x)
# create a temporary raster within the extent with block_size as pixel size
#n_x = ceiling(abs((x_ext[2] - x_ext[1])) / block_size)
n_y = abs((x_ext[4] - x_ext[3])) / block_size
# adjust extent to fit the cells
x_ext_mod = x_ext
x_ext_mod[4] = x_ext_mod[4] + ((ceiling(n_y) - n_y) * block_size)
#
r = raster(x_ext_mod, crs = crs(x), resolution = block_size)
r[] = NA
#
#plot(extend(extent(r),100), asp=1)
#plot(r, add=T, col="red")
fname = paste0(tempfile(), ".tif")
writeRaster(r, filename = fname, overwrite=T)
if (inMemory(x)) {
fname_x = paste0(tempfile(), "_x.tif")
writeRaster(x, filename = fname_x)
x = raster(fname_x)
}
# calculate the average of x inside the pixels
#gdal_path = "C:\\GDAL_64\\"
# command
gdalwarp = paste(paste0(gdal_path,"gdalwarp")
#,"-r average -wm 9999"
,"-r average -wm 2047"
,x@file@name
,fname
)
system(gdalwarp)
# load
r2 = raster(fname)
#plot(r2)
# convert raster to polygons - only those with values
r2_pol = rasterToPolygons(r2, dissolve=F, na.rm=na_rm)
# plot(r2_pol)
# exclude all zero
if (remove_all_zero) {
idx = which(r2_pol@data[]==0)
if (length(idx) > 0) r2_pol = r2_pol[-idx,]
}
# create extents
ext_list = list()
i=1
for (i in 1:length(r2_pol)) {
ext_list[[i]] = extent(r2_pol[i,])
}
unlink(fname)
return(ext_list)
}
#
# split the extent of a sp object, border in meters
split_extent_gdal_border = function(x, block_size = 1000, na_rm = T, remove_all_zero = T, gdal_path = NULL, border = block_size*0.125) {
if (is.null(gdal_path)) stop("Missing GDAL path.")
# x = LIDAR_ANA_2017
# x = LIDAR_ST1_2016
x_ext = extent(x)
# adjust border
vect_overlap = c(-border, border, -border, border)
x_ext = extent(x) - vect_overlap
# create a temporary raster within the extent with block_size as pixel size
#n_x = ceiling(abs((x_ext[2] - x_ext[1])) / block_size)
n_y = abs((x_ext[4] - x_ext[3])) / block_size
# adjust extent to fit the cells
x_ext_mod = x_ext
x_ext_mod[4] = x_ext_mod[4] + ((ceiling(n_y) - n_y) * block_size)
#
r = raster(x_ext_mod, crs = crs(x), resolution = block_size)
r[] = NA
#
#plot(extend(extent(r),100), asp=1)
#plot(r, add=T, col="red")
fname = paste0(tempfile(), ".tif")
writeRaster(r, filename = fname, overwrite=T)
# we do this always now in order to always get only one layer for this purpose
# otherwise, if the image has more than one band, the gdalwarp does not work
#if (inMemory(x)) {
fname_x = paste0(tempfile(), "_x.tif")
writeRaster(x[[1]], filename = fname_x)
x = raster(fname_x)
#}
# calculate the average of x inside the pixels
#gdal_path = "C:\\GDAL_64\\"
# command
gdalwarp = paste(paste0(gdal_path,"gdalwarp")
#,"-r average -wm 9999"
,"-r average -wm 2047"
,x@file@name
,fname
)
system(gdalwarp)
# load
r2 = raster(fname)
#plot(r2)
# convert raster to polygons - only those with values
r2_pol = rasterToPolygons(r2, dissolve=F, na.rm=na_rm)
# plot(r2_pol)
# exclude all zero
if (remove_all_zero) {
idx = which(r2_pol@data[]==0)
if (length(idx) > 0) r2_pol = r2_pol[-idx,]
}
# create extents
ext_list = list()
i=1
for (i in 1:length(r2_pol)) {
ext_list[[i]] = extent(r2_pol[i,])
}
unlink(fname)
return(ext_list)
}
#
# split the extent of a sp object
split_extent_gdal_bottom = function(x, block_size = 1000, na_rm = T, remove_all_zero = T, gdal_path = NULL) {
if (is.null(gdal_path)) stop("Missing GDAL path.")
# x = LIDAR_ANA_2017
# x = LIDAR_ST1_2016
x_ext = extent(x)
# create a temporary raster within the extent with block_size as pixel size
#n_x = ceiling(abs((x_ext[2] - x_ext[1])) / block_size)
n_y = abs((x_ext[4] - x_ext[3])) / block_size
# adjust extent to fit the cells
x_ext_mod = x_ext
#x_ext_mod[4] = x_ext_mod[4] + ((ceiling(n_y) - n_y) * block_size)
x_ext_mod[3] = x_ext_mod[3] - ((ceiling(n_y) - n_y) * block_size)
#
r = raster(x_ext_mod, crs = crs(x), resolution = block_size)
r[] = NA
#
#plot(extend(extent(r),100), asp=1)
#plot(r, add=T, col="red")
fname = paste0(tempfile(), ".tif")
writeRaster(r, filename = fname, overwrite=T)
if (inMemory(x)) {
fname_x = paste0(tempfile(), "_x.tif")
writeRaster(x, filename = fname_x)
x = raster(fname_x)
}
# calculate the average of x inside the pixels
#gdal_path = "C:\\GDAL_64\\"
# command
gdalwarp = paste(paste0(gdal_path,"gdalwarp")
#,"-r average -wm 9999"
,"-r average -wm 2047"
,x@file@name
,fname
)
system(gdalwarp)
# load
r2 = raster(fname)
#plot(r2)
# convert raster to polygons - only those with values
r2_pol = rasterToPolygons(r2, dissolve=F, na.rm=na_rm)
# plot(r2_pol)
# exclude all zero
if (remove_all_zero) {
idx = which(r2_pol@data[]==0)
if (length(idx) > 0) r2_pol = r2_pol[-idx,]
}
# create extents
ext_list = list()
i=1
for (i in 1:length(r2_pol)) {
ext_list[[i]] = extent(r2_pol[i,])
}
unlink(fname)
return(ext_list)
}
#
# function to remove the last 4 digits of a string (usually the extension e.g. ".tif") and substitute it for another string
sub_extension = function (x, y) {
return(paste0(substr(x, 1, nchar(x)-4), y))
}
# 1) load field data -----------------------------------------------------
# load field data
field_data = readOGR("1_Field\\ARROZ-RS_Safra_2019_2020\\RS_ARROZ_IRRIG_INUND_1920.shp")
# lets filter these data to only one municipality, list municipalities and get only one
unique(field_data$NM_MUNICIP)
field_data = field_data[field_data$NM_MUNICIP == "URUGUAIANA",]
# reproject to the same projection of the satellite data
field_data = spTransform(field_data, crs("+proj=utm +zone=21 +south +datum=WGS84 +units=m +no_defs"))
# visualization
if (FALSE) {
# simple plot
plot(field_data)
# visualize it over google map
map = leaflet() %>%
#addTiles() %>%
addTiles(urlTemplate = "https://mts1.google.com/vt/lyrs=s&hl=en&src=app&x={x}&y={y}&z={z}&s=G", attribution = 'Google') %>%
addPolygons(data = field_data)
map ## show the map
}
# 2) define images to use and visualize ----------------------------------------------------
# list images
img_list = list.files("2_Images", full.names=T, pattern = "singledate")
# which bands to use?
bands_to_use = 1:4
# name to add for this experiment
exp_str = "singledate"
# set up deep learning
training_data_dir = "5_sampling1_singledate"
dir.create(training_data_dir, showWarnings = F)
prediction_data_dir = "6_sampling1_prediction_singledate"
dir.create(training_data_dir, showWarnings = F)
weights_fname = "5_sampling1_singledate\\weights_r_save\\unet_tf2_385_0.9311.h5" # best weight
result_fname = "rice_map_single"
# visualize the images
if (FALSE) {
s2 = stack(img_list)
plot(s2[[5]])
# for singledate
mapview(s2[[5]]) + field_data # ndvi
mapview(s2[[4]]) + field_data # nir
# for multidate
mapview(s2[[4]]) + field_data # Feb 2020 NDVI
}
#
img_dir = paste0(training_data_dir, "./input/image")
class_dir = paste0(training_data_dir,"./input/class")
# 3) deep learning create grid of patches -----------------------------------------------
# load one image
img = stack(img_list[1])
# create a temporary raster within the extent with block_size as pixel size
# block_size is the size of each tile in meters
block_size = 128*10
#
x_ext = extent(img)
# get the number of cells in the y axis
#n_x = ceiling(abs((x_ext[2] - x_ext[1])) / block_size)
n_y = abs((x_ext[4] - x_ext[3])) / block_size
# adjust extent to fit the cells
x_ext_mod = x_ext
x_ext_mod[4] = x_ext_mod[4] + ((ceiling(n_y) - n_y) * block_size)
# create a raster with this adjusted extent which resolution is our patch size
r = raster(x_ext_mod, crs = crs(img), resolution = block_size)
r[] = 1
# convert raster pixels to polygons
r_pol = rasterToPolygons(r, dissolve=F)#, na.rm=na_rm)
r_pol$id = 1:length(r_pol)
# visualize
x11()
plot(img[[1]])
plot(r_pol,add=T)
# save
writeOGR(r_pol, dsn = "4_grid", layer = "grid", overwrite_layer = T, driver = "ESRI Shapefile")
# 4) deep learning sampling ----------------------------------------------------------------
## the aim of this part is to crop the image into patches that we just created for the locations that have samples
## Note: a limitation to the current code we are using is that it only takes 4 bands
## this is because the use of the PNG file, need to adjust the code to use tif
## so we can use more bands, this is why we just get 4 bands in the [[]] here
## this takes ~15min
# libraries
p_load(raster, rgdal, rgeos, gdalUtils, sp, sf)
# load files
img = stack(img_list)[[bands_to_use]]
samples = st_as_sf(field_data)
grid = st_read("4_grid\\grid.shp")
# reproject samples to the same CRS of the img and grid
samples = st_transform(samples, as.character(crs(grid)))
# create other folders
dir.create(paste0(training_data_dir, "\\input\\image\\"), showWarnings = F, recursive=T)
dir.create(paste0(training_data_dir, "\\input\\class\\"), showWarnings = F, recursive=T)
# rasterize the samples
library(fasterize)
samples_raster = fasterize(samples, img[[1]])
samples_raster[is.na(samples_raster)]=0
# visualize
plot(samples_raster)
# libraries needed
p_load(parallel, doParallel, foreach)
# Begin cluster
cl = parallel::makeCluster(no_cores) # here you specify the number of processors you want to use, if you dont know you can use detectCores() and ideally use that number minus one
#cl = parallel::makeCluster(3, outfile="D:/r_parallel_log.txt") # if you use this you can see prints in the txt
registerDoParallel(cl)
# for each extent
i=1
#foreach(i = 1:1500, .inorder=F, .errorhandling='remove') %dopar% { # test just a few files
foreach(i = 1:length(grid$id), .inorder=F, .errorhandling='remove') %dopar% {
require(raster)
require(png)
require(rgeos)
require(sf)
# function to get the sp with the extent of a raster object
rasext_to_sp = function(x) {
y = as(extent(x), "SpatialPolygons")
crs(y) = crs(x)
return(y)
}
# check if there is intersection
if (!gIntersects(rasext_to_sp(img), as_Spatial(grid[i,]))) return(NA)
# crop img and mask
img_tmp = crop(img, grid[i,])
class_tmp = crop(samples_raster, grid[i,])
# define class presence or absence
class_presence = "NOO"
if(1 %in% getValues(class_tmp[[1]])) class_presence="YES"
print(class_presence)
# row and columns are the same
if (dim(class_tmp)[1] == dim(class_tmp)[2]) {
# visualization
if (FALSE) {
#if (class_presence == "YES") {
plot(class_tmp); plot(img_tmp)
plot(stack(img_tmp, class_tmp), main = paste("layer:",i))
# plot(extent(img_tmp),asp=1)
# plotRGB(img_tmp, r=1, g=2, b=3, add=T, stretch="lin")
# plot(extent(img_tmp),asp=1)
# plot(class_tmp,add=T)
}
# save if YES - only if it has samples
if (class_presence == "YES") {
# we divide by the scale of data
# for 1 layer
#img_tmp2 = matrix(img_tmp, ncol = ncol(img_tmp), byrow = T) / 2047
# for more layers
#img_tmp = stack(crop(img, grid[i,]) ,crop(img, grid[i,])*2 ,crop(img, grid[i,])*3,crop(img, grid[i,])*4 )
img_tmp2 = array(img_tmp, c(nrow(img_tmp), ncol(img_tmp), nlayers(img))) #/ 2047
img_tmp2 = aperm(img_tmp2, c(2,1,3))
#
png::writePNG(img_tmp2, paste0(training_data_dir,"\\input\\image\\img_",class_presence,"_",sprintf("%05.0f",i),".png"))
#
class_tmp = matrix(class_tmp, ncol = ncol(class_tmp), byrow = T)
png::writePNG(class_tmp, paste0(training_data_dir,"\\input\\class\\cla_",class_presence,"_",sprintf("%05.0f",i),".png"))
}
}
print(paste0(i,ifelse(class_presence=="YES", " YES","")))
}
# finish cluster
stopCluster(cl)
# 4a) Visualize some patch samples --------------------------------------------
# list samples
list_img = list.files(img_dir, pattern = "*.png", full.names = TRUE)
list_mask = list.files(class_dir, pattern = "*.png", full.names = TRUE)
length(list_img)
# plot
# i=1
i = sample(1:length(list_img), 1)
r = stack(list_img[i], list_mask[i])
plot(r)
r
print(i)
# 5) DL data visualization -----------------------------------------------
# libraries we're going to need later
# always put reticulate and use_python as the first packages to load, or you will not be able to choose the conda env/python
p_load(reticulate)
use_python(tensorflow_dir, required = T)
p_load(keras, tfdatasets, tidyverse, rsample, magick)
#py_config()
# Quick visualization
## it picks a random sample to show
## if you run multiple times you will see different samples
images <- tibble(
img = list.files(img_dir, pattern = "*.png", full.names = TRUE),
mask = list.files(class_dir, pattern = "*.png", full.names = TRUE)
) %>%
sample_n(2) %>%
map(. %>% magick::image_read())
#
out <- magick::image_append(c(
magick::image_append(images$img, stack = TRUE),
magick::image_append(images$mask, stack = TRUE)
))
#
plot(out)
# 6) deep learning training U-Net --------------------------------------------------
# libraries we're going to need later
# always put reticulate and use_python as the first packages to load, or you will not be able to choose the conda env/python
p_load(reticulate)
use_python(tensorflow_dir, required = T)
p_load(keras, tfdatasets, tidyverse, rsample, magick)
#py_config()
# parameters
#epochs = 400L
epochs = 15L
batch_size = 32L
lr_rate = 0.0001
decay_rate = 0.0001
img_dir = paste0(training_data_dir, "./input/image")
class_dir = paste0(training_data_dir,"./input/class")
data_n_layers = 4
# Quick visualization
images <- tibble(
img = list.files(img_dir, pattern = "*.png", full.names = TRUE),
mask = list.files(class_dir, pattern = "*.png", full.names = TRUE)
) %>%
sample_n(2) %>%
map(. %>% magick::image_read())
#
out <- magick::image_append(c(
magick::image_append(images$img, stack = TRUE),
magick::image_append(images$mask, stack = TRUE)
))
#
plot(out)
# load all data
data_full <- tibble(
img = list.files(img_dir, pattern = "*.png", full.names = TRUE),
mask = list.files(class_dir, pattern = "*.png", full.names = TRUE)
)
# random sorting of the data
set.seed(10)
random_order=sample(1:dim(data_full)[1],dim(data_full)[1])
data_full_reorder <- data_full[random_order,]
# split the data between training and validation
data_full_reorder <- initial_split(data_full_reorder, prop = 0.8)
train_samples = length(data_full_reorder$in_id)
train_fname = training(data_full_reorder)$img
test_fname = testing(data_full_reorder)$img
# find the id on the name of imgs string
idx_last_underline = regexpr("\\_[^\\_]*$", basename(test_fname)[1])[1]
ids_validation = as.numeric(substr(basename(test_fname), idx_last_underline + 1, nchar(basename(test_fname))[1] - 4))
# find the id on the name of imgs string
idx_last_underline = regexpr("\\_[^\\_]*$", basename(train_fname)[1])[1]
ids_train = as.numeric(substr(basename(train_fname), idx_last_underline + 1, nchar(basename(train_fname))[1] - 4))
# get the polygons inside each block id
grid = readOGR("4_grid\\grid.shp")
samples_patches_validation = grid[grid$id %in% ids_validation,]
samples_patches_train = grid[grid$id %in% ids_train,]
plot(samples_patches_train, main="train = black, validation = red")
lines(samples_patches_validation, col="red")
# save
save(samples_patches_train, samples_patches_validation, file = paste0("deep_learning_patch_samples_",exp_str,".RData"))
## the model
# mixed precision
tf$keras$mixed_precision$experimental$set_policy('mixed_float16')
dice_coef <- custom_metric("custom", function(y_true, y_pred, smooth = 1.0) {
y_true_f <- k_flatten(y_true)
y_pred_f <- k_flatten(y_pred)
intersection <- k_sum(y_true_f * y_pred_f)
result <- (2 * intersection + smooth) /
(k_sum(y_true_f) + k_sum(y_pred_f) + smooth)
return(result)
})
bce_dice_loss <- function(y_true, y_pred) {
result <- loss_binary_crossentropy(y_true, y_pred) +
(1 - dice_coef(y_true, y_pred))
return(result)
}
#
get_unet_128 <- function(input_shape = c(128, 128, data_n_layers),
num_classes = 1) {
inputs <- layer_input(shape = input_shape)
# 128
down1 <- inputs %>%
layer_conv_2d(filters = 64, kernel_size = c(3, 3), padding = "same") %>%
layer_batch_normalization() %>%
layer_activation("relu") %>%
layer_conv_2d(filters = 64, kernel_size = c(3, 3), padding = "same") %>%
layer_batch_normalization() %>%
layer_activation("relu")
down1_pool <- down1 %>%
layer_max_pooling_2d(pool_size = c(2, 2), strides = c(2, 2))
# 64
down2 <- down1_pool %>%
layer_conv_2d(filters = 128, kernel_size = c(3, 3), padding = "same") %>%
layer_batch_normalization() %>%
layer_activation("relu") %>%
layer_conv_2d(filters = 128, kernel_size = c(3, 3), padding = "same") %>%
layer_batch_normalization() %>%
layer_activation("relu")
down2_pool <- down2 %>%
layer_max_pooling_2d(pool_size = c(2, 2), strides = c(2, 2))
# 32
down3 <- down2_pool %>%
layer_conv_2d(filters = 256, kernel_size = c(3, 3), padding = "same") %>%
layer_batch_normalization() %>%
layer_activation("relu") %>%
layer_conv_2d(filters = 256, kernel_size = c(3, 3), padding = "same") %>%
layer_batch_normalization() %>%
layer_activation("relu")
down3_pool <- down3 %>%
layer_max_pooling_2d(pool_size = c(2, 2), strides = c(2, 2))
# 16
down4 <- down3_pool %>%
layer_conv_2d(filters = 512, kernel_size = c(3, 3), padding = "same") %>%
layer_batch_normalization() %>%
layer_activation("relu") %>%
layer_conv_2d(filters = 512, kernel_size = c(3, 3), padding = "same") %>%
layer_batch_normalization() %>%
layer_activation("relu")
down4_pool <- down4 %>%
layer_max_pooling_2d(pool_size = c(2, 2), strides = c(2, 2))
# 8
center <- down4_pool %>%
layer_conv_2d(filters = 1024, kernel_size = c(3, 3), padding = "same") %>%
layer_batch_normalization() %>%
layer_activation("relu") %>%
layer_conv_2d(filters = 1024, kernel_size = c(3, 3), padding = "same") %>%
layer_batch_normalization() %>%
layer_activation("relu")
# center
up4 <- center %>%
layer_upsampling_2d(size = c(2, 2)) %>%
{layer_concatenate(inputs = list(down4, .), axis = 3)} %>%
layer_conv_2d(filters = 512, kernel_size = c(3, 3), padding = "same") %>%
layer_batch_normalization() %>%
layer_activation("relu") %>%
layer_conv_2d(filters = 512, kernel_size = c(3, 3), padding = "same") %>%
layer_batch_normalization() %>%
layer_activation("relu") %>%
layer_conv_2d(filters = 512, kernel_size = c(3, 3), padding = "same") %>%
layer_batch_normalization() %>%
layer_activation("relu")
# 16
up3 <- up4 %>%
layer_upsampling_2d(size = c(2, 2)) %>%
{layer_concatenate(inputs = list(down3, .), axis = 3)} %>%
layer_conv_2d(filters = 256, kernel_size = c(3, 3), padding = "same") %>%
layer_batch_normalization() %>%
layer_activation("relu") %>%
layer_conv_2d(filters = 256, kernel_size = c(3, 3), padding = "same") %>%
layer_batch_normalization() %>%
layer_activation("relu") %>%
layer_conv_2d(filters = 256, kernel_size = c(3, 3), padding = "same") %>%
layer_batch_normalization() %>%
layer_activation("relu")
# 32
up2 <- up3 %>%
layer_upsampling_2d(size = c(2, 2)) %>%
{layer_concatenate(inputs = list(down2, .), axis = 3)} %>%
layer_conv_2d(filters = 128, kernel_size = c(3, 3), padding = "same") %>%
layer_batch_normalization() %>%
layer_activation("relu") %>%
layer_conv_2d(filters = 128, kernel_size = c(3, 3), padding = "same") %>%
layer_batch_normalization() %>%
layer_activation("relu") %>%
layer_conv_2d(filters = 128, kernel_size = c(3, 3), padding = "same") %>%
layer_batch_normalization() %>%
layer_activation("relu")
# 64
up1 <- up2 %>%
layer_upsampling_2d(size = c(2, 2)) %>%
{layer_concatenate(inputs = list(down1, .), axis = 3)} %>%
layer_conv_2d(filters = 64, kernel_size = c(3, 3), padding = "same") %>%
layer_batch_normalization() %>%
layer_activation("relu") %>%
layer_conv_2d(filters = 64, kernel_size = c(3, 3), padding = "same") %>%
layer_batch_normalization() %>%
layer_activation("relu") %>%
layer_conv_2d(filters = 64, kernel_size = c(3, 3), padding = "same") %>%
layer_batch_normalization() %>%
layer_activation("relu")
# 128
classify <- layer_conv_2d(up1,
filters = num_classes,
kernel_size = c(1, 1),
dtype = 'float32', # mixed precision
activation = "sigmoid")
model <- keras_model(
inputs = inputs,
outputs = classify
)
model %>% compile(
optimizer = optimizer_rmsprop(lr = lr_rate, decay = decay_rate),
loss = bce_dice_loss,
#loss = bce_dice_loss_flooding,
metrics = c(dice_coef)
)
return(model)
}
#
model <- get_unet_128()
## data augmentation
# random brightness, contrast, hue
random_bsh <- function(img) {
img <- img %>%
tf$image$random_brightness(max_delta = 0.2) %>%
tf$image$random_contrast(lower = 0.9, upper = 1.1) # %>%
# img <- tf$math$multiply(img,tf$random$uniform(shape = shape(1L), minval = 0.4 ,maxval = 1.6 ,dtype = tf$float32))
# for RGB
# img_aug <- img[,,1:3] %>%
# tf$image$random_saturation(lower = 0.9, upper = 1.1) %>%
# tf$image$random_hue(max_delta = 0.2) #%>%
#
# img <- tf$keras$backend$concatenate(
# list(img_aug[,,1:3,drop=FALSE],img[,,4,drop=FALSE]), axis=-1L
# ) %>% tf$clip_by_value(0, 1)
}
random_flip_up_down <- function(x,y) { tf$cond(tf$less(y , 0.25) , function() tf$image$flip_up_down(x), function() x) }
random_flip_left_right <- function(x,y) { tf$cond(tf$greater(y , 0.75), function() tf$image$flip_left_right(x), function() x) }
# map data
create_dataset <- function(data, train, batch_size = 8L, data_n_layers = 3) {
dataset <- data %>%
mutate(rot = ifelse(runif(dim(data)[1])>0.75,1,0)*runif(dim(data)[1],min=0,max=2*pi)) %>%
tensor_slices_dataset() %>%
dataset_map(~.x %>% list_modify(
img = tf$image$decode_png(tf$io$read_file(.x$img),channels=data_n_layers),
mask = tf$image$decode_png(tf$io$read_file(.x$mask),channels=1)
)) %>%
dataset_map(~.x %>% list_modify(
img = tf$image$convert_image_dtype(.x$img, dtype = tf$float32),
#mask = tf$image$convert_image_dtype(.x$mask, dtype = tf$uint8)
mask = tf$image$convert_image_dtype(.x$mask, dtype = tf$float32)
))
# set rot variable to a random uniform value
dataset <- dataset %>% dataset_map(~.x %>% list_modify(
rot =tf$random$uniform(shape = shape(1L), minval = 0 ,maxval = 1 ,dtype = tf$float32)
))
# apply up/down and left/right flip conditioned by rot
dataset <- dataset %>%
dataset_map(~.x %>% list_modify(
img = random_flip_up_down(x=.x$img,y=.x$rot),
mask = random_flip_up_down(x=.x$mask,y=.x$rot)
)) %>%
dataset_map(~.x %>% list_modify(
img = random_flip_left_right(x=.x$img,y=.x$rot),
mask = random_flip_left_right(x=.x$mask,y=.x$rot)
))
# data augmentation performed on training set only
if (train) {