-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmurko.py
executable file
·3572 lines (3212 loc) · 117 KB
/
murko.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
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: Martin Savko ([email protected])
# based on F. Chollet's https://keras.io/examples/vision/oxford_pets_image_segmentation/
# Model based on The One Hundred Layers Tiramisu: Fully convolutional DenseNets for Semantic Segmentation, arXiv:1611.09326
# With main difference being use of SeparableConv2D instead of Conv2D and
# using GroupNormalization instead of BatchNormalization. Plus using
# additional Weight standardization (based on Qiao et al. Micro-Batch
# Training with Batch-Channel Normalization and Weight Standardization
# arXiv:1903.10520v2)
from tensorflow.keras import regularizers
import matplotlib.pyplot as plt
from skimage.morphology import remove_small_objects
from skimage.measure import regionprops
from skimage.transform import resize
from keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau
from keras.models import Model, load_model
from tensorflow.keras.preprocessing import image
from tensorflow.keras.preprocessing.image import (
save_img,
load_img,
img_to_array,
array_to_img,
)
from tensorflow.keras import layers
from tensorflow import keras
import tensorflow.experimental.numpy as tnp
import tensorflow as tf
import os
import sys
import time
import math
import zmq
import glob
import numpy as np
import random
import re
import pickle
import traceback
import pylab
import seaborn as sns
import simplejpeg
import copy
import scipy.ndimage as ndi
sns.set(color_codes=True)
# from matplotlib import rc
# rc('font', **{'family':'serif','serif':['Palatino']})
# rc('text', usetex=True)
try:
from skimage.morphology.footprints import disk
except BaseException:
from skimage.morphology.selem import disk
directory = "images_and_labels_augmented"
img_size = (1024, 1360)
model_img_size = (512, 512)
num_classes = 1
batch_size = 8
params = {
"segmentation": {"loss": "binary_focal_crossentropy", "metrics": "BIoU"},
"click_segmentation": {"loss": "binary_focal_crossentropy", "metrics": "BIoUm"},
"click_regression": {
"loss": "mean_squared_error",
"metrics": "mean_absolute_error",
},
}
networks = {
"fcdn103": {
"growth_rate": 16,
"layers_scheme": [4, 5, 7, 10, 12],
"bottleneck": 15,
},
"fcdn67": {"growth_rate": 16, "layers_scheme": [5] * 5, "bottleneck": 5},
"fcdn56": {"growth_rate": 12, "layers_scheme": [4] * 5, "bottleneck": 4},
}
calibrations = {
1: np.array([0.00160829, 0.001612]),
2: np.array([0.00129349, 0.0012945]),
3: np.array([0.00098891, 0.00098577]),
4: np.array([0.00075432, 0.00075136]),
5: np.array([0.00057437, 0.00057291]),
6: np.array([0.00043897, 0.00043801]),
7: np.array([0.00033421, 0.00033406]),
8: np.array([0.00025234, 0.00025507]),
9: np.array([0.00019332, 0.00019494]),
10: np.array([0.00015812, 0.00015698]),
}
"""
dataset composition:
notion fraction_label fraction_total
crystal: 0.051084, 0.023338
loop_inside: 0.118100, 0.053953
loop: 0.294535, 0.134557
stem: 0.062713, 0.028650
pin: 0.035046, 0.016011
capillary: 0.004127, 0.001885
ice: 0.026989, 0.012330
foreground: 0.407406, 0.186121
background: 1.781519, 0.813879
"""
# loss_weights_from_stats =\
# {'crystal': 8,
# 'loop_inside': 3.5,
# 'loop': 1.5,
# 'stem': 6.5,
# 'pin': 5.0,
# 'capillary': 1.,
# 'ice': 1.,
# 'foreground': 1.0,
# 'click': 1.}
"""
total pixels 1805946880 (1.806G)
total foreground 319001744 (0.319G, 0.1766 of all)
notion fraction_label fraction_total weight_label weight_total
crystal 0.1173 0.0207 8.5 48.3
loop_inside 0.2485 0.0439 4.0 22.8
loop 0.6427 0.1135 1.6 8.8
stem 0.1876 0.0331 5.3 30.2
pin 0.1242 0.0219 8.0 45.6
capillary 0.0102 0.0018 98.4 557.0
ice 0.0630 0.0111 15.9 89.9
foreground 1.0000 0.1766 1.0 5.7
total 5.6612 1.0000 0.2 1.0
"""
loss_weights_from_stats = {
"crystal": 8.5,
"loop_inside": 4.0,
"loop": 1.6,
"stem": 5.3,
"pin": 8.0,
"capillary": 1.0,
"ice": 15.9,
"foreground": 1.0,
"click": 1.0,
}
def compare(h1, h2, what="crystal"):
pylab.figure(1)
for key in h1:
if what in key and "loss" not in key:
pylab.plot(h1[key], label=key)
pylab.legend()
pylab.figure(2)
for key in h2:
if what in key and "loss" not in key:
pylab.plot(h2[key], label=key)
pylab.legend()
pylab.show()
def plot_history(
history,
h=None,
notions=[
"crystal",
"loop_inside",
"loop",
"stem",
"pin",
"capillary",
"ice",
"foreground",
],
):
if h is None:
h = pickle.load(open(history, "rb"), encoding="bytes")
template = history.replace(".history", "")
pylab.figure(figsize=(16, 9))
pylab.title(template)
for notion in notions:
key = "val_%s_BIoU_1" % notion
if key in h:
pylab.plot(h[key], "o-", label=notion)
else:
continue
pylab.ylim([-0.1, 1.1])
pylab.grid(True)
pylab.legend()
pylab.savefig("%s_metrics.png" % template)
def analyse_histories(
notions=["crystal", "loop_inside", "loop", "stem", "pin", "foreground"]
):
histories = (
glob.glob("*.history")
+ glob.glob("experiments/*.history")
+ glob.glob("backup/*.history")
)
metrics_table = {}
for history in histories:
print(history)
h = pickle.load(open(history, "rb"), encoding="bytes")
plot_history(history, h=h, notions=notions)
val_metrics = []
for notion in notions:
key = "val_%s_BIoU_1" % notion
if key in h:
val_metrics.append(h["val_%s_BIoU_1" % notion])
val_metrics = np.array(val_metrics)
try:
best = val_metrics.max(axis=1).T
best
except BaseException:
best = "problem in determining expected metrics"
line = "%s: %s" % (best, history)
print(line)
os.system('echo "%s" >> histories.txt' % line)
def resize_images(images, size, method="bilinear", align_corners=False):
"""See https://www.tensorflow.org/versions/master/api_docs/python/tf/image/resize_images .
Args
method: The method used for interpolation. One of ('bilinear', 'nearest', 'bicubic', 'area').
"""
methods = {
"bilinear": tf.image.ResizeMethod.BILINEAR,
"nearest": tf.image.ResizeMethod.NEAREST_NEIGHBOR,
"bicubic": tf.image.ResizeMethod.BICUBIC,
"area": tf.image.ResizeMethod.AREA,
}
return tf.image.resize_images(images, size, methods[method], align_corners)
class UpsampleLike(keras.layers.Layer):
"""
Keras layer for upsampling a Tensor to be the same shape as another Tensor.
based on https://github.com/xuannianz/keras-fcos.git
"""
def call(self, inputs, **kwargs):
source, target = inputs
target_shape = K.shape(target)
return resize_images(
source, (target_shape[1], target_shape[2]), method="nearest"
)
def compute_output_shape(self, input_shape):
return (input_shape[0][0],) + input_shape[1][1:3] + (input_shape[0][-1],)
def get_pixels(
directory="/nfs/data2/Martin/Research/murko/images_and_labels",
notions=[
"crystal",
"loop_inside",
"loop",
"stem",
"pin",
"capillary",
"ice",
"foreground",
],
print_table=True,
):
masks = glob.glob("%s/*/masks.npy" % directory)
pixel_counts = dict([(notion, 0) for notion in notions])
pixel_counts["total"] = 0
for mask in masks:
m = np.load(mask)
for k, notion in enumerate(notions):
pixel_counts[notion] += m[:, :, k].sum()
pixel_counts["total"] += np.prod(m.shape[:2])
if print_table:
print(
"total pixels %d (%.3fG)".ljust(15)
% (pixel_counts["total"], pixel_counts["total"] / 1e9)
)
print(
"total foreground %d (%.3fG, %.4f of all)".ljust(15)
% (
pixel_counts["foreground"],
pixel_counts["foreground"] / 1e9,
pixel_counts["foreground"] / pixel_counts["total"],
)
)
print()
print(
"notion".rjust(15),
"fraction_label".rjust(15),
"fraction_total".rjust(15),
"weight_label".rjust(20),
"weight_total".rjust(20),
)
for key in pixel_counts:
print(
key.rjust(15),
"%.4f".rjust(10) % (pixel_counts[key] / pixel_counts["foreground"]),
"%.4f".rjust(15) % (pixel_counts[key] / pixel_counts["total"]),
"%3.1f".zfill(2).rjust(20)
% (pixel_counts["foreground"] / pixel_counts[key]),
"%3.1f".zfill(2).rjust(20)
% (pixel_counts["total"] / pixel_counts[key]),
)
return pixel_counts
def get_flops(model_h5_path):
session = tf.compat.v1.Session()
graph = tf.compat.v1.get_default_graph()
with graph.as_default():
with session.as_default():
model = tf.keras.models.load_model(model_h5_path)
run_meta = tf.compat.v1.RunMetadata()
opts = tf.compat.v1.profiler.ProfileOptionBuilder.float_operation()
# We use the Keras session graph in the call to the profiler.
flops = tf.compat.v1.profiler.profile(
graph=graph, run_meta=run_meta, cmd="op", options=opts
)
return flops.total_float_ops
class WSConv2D(tf.keras.layers.Conv2D):
"""https://github.com/joe-siyuan-qiao/WeightStandardization"""
def __init__(self, *args, **kwargs):
super(WSConv2D, self).__init__(*args, **kwargs)
self.eps = 1.0e-5
self.std = False
def standardize_kernel(self, kernel):
original_dtype = kernel.dtype
mean = tf.math.reduce_mean(kernel, axis=(0, 1, 2), keepdims=True)
kernel = kernel - mean
if self.std:
std = tf.keras.backend.std(kernel, axis=[0, 1, 2], keepdims=True)
std = std + tf.constant(self.eps, dtype=std.dtype)
kernel = kernel / std
kernel = tf.cast(kernel, dtype=original_dtype)
return kernel
def call(self, inputs):
self.kernel.assign(self.standardize_kernel(self.kernel))
return super().call(inputs)
class WSSeparableConv2D(tf.keras.layers.SeparableConv2D):
"""https://github.com/joe-siyuan-qiao/WeightStandardization"""
def __init__(self, *args, **kwargs):
super(WSSeparableConv2D, self).__init__(*args, **kwargs)
self.eps = 1.0e-5
self.std = False
def standardize_kernel(self, kernel):
original_dtype = kernel.dtype
mean = tf.math.reduce_mean(kernel, axis=(0, 1, 2), keepdims=True)
kernel = kernel - mean
if self.std:
std = tf.math.reduce_std(kernel, axis=[0, 1, 2], keepdims=True)
std = std + tf.constant(self.eps, dtype=std.dtype)
kernel = kernel / std
kernel = tf.cast(kernel, dtype=original_dtype)
return kernel
def call(self, inputs):
self.pointwise_kernel.assign(self.standardize_kernel(self.pointwise_kernel))
self.depthwise_kernel.assign(self.standardize_kernel(self.depthwise_kernel))
return super().call(inputs)
def generate_click_loss_and_metric_figures(
click_radius=360e-3, image_shape=(1024, 1360), nclicks=10, ntries=1000, display=True
):
resize_factor = np.array(image_shape) / np.array((1024, 1360))
distances = []
bfcs = []
bio1 = []
bio1m = tf.keras.metrics.BinaryIoUm(target_class_ids=[1], threshold=0.5)
bio0 = []
bio0m = tf.keras.metrics.BinaryIoUm(target_class_ids=[0], threshold=0.5)
biob = []
biobm = tf.keras.metrics.BinaryIoUm(target_class_ids=[0, 1], threshold=0.5)
concepts = {
"bfcs": bfcs,
"bio1": bio1,
"bio0": bio0,
"biob": biob,
"distances": distances,
}
for k in range(nclicks):
click = (
np.array(image_shape)
* np.random.rand(
2,
)
).astype(int)
cpi_true = click_probability_image(
click[1],
click[0],
image_shape,
click_radius=click_radius,
resize_factor=resize_factor,
scale_click=False,
)
cpi_true = np.expand_dims(cpi_true, (0, -1))
for n in range(ntries // nclicks):
tclick = (
np.array(image_shape)
* np.random.rand(
2,
)
).astype(int)
cpi_pred = click_probability_image(
tclick[1],
tclick[0],
image_shape,
click_radius=click_radius,
resize_factor=resize_factor,
scale_click=False,
)
cpi_pred = np.expand_dims(cpi_pred, (0, -1))
concepts["distances"].append(np.linalg.norm(click - tclick, 2))
concepts["bfcs"].append(
tf.keras.losses.binary_focal_crossentropy(cpi_true, cpi_pred)
.numpy()
.mean()
)
bio1m.reset_state()
bio1m.update_state(cpi_true, cpi_pred)
concepts["bio1"].append(bio1m.result().numpy())
bio0m.reset_state()
bio0m.update_state(cpi_true, cpi_pred)
concepts["bio0"].append(bio0m.result().numpy())
biobm.reset_state()
biobm.update_state(cpi_true, cpi_pred)
concepts["biob"].append(biobm.result().numpy())
for concept in concepts:
concepts[concept] = np.array(concepts[concept])
concepts["distances"] /= np.linalg.norm(image_shape, 2)
concepts["bfcs"] /= concepts["bfcs"].max()
pylab.figure(figsize=(16, 9))
pylab.title(
"image shape %dx%d, click_radius=%.3f"
% (image_shape[0], image_shape[1], click_radius)
)
for concept in ["bfcs", "bio1", "bio0", "biob"]:
pylab.plot(concepts["distances"], concepts[concept], "o", label=concept)
pylab.xlabel("distances")
pylab.ylabel("loss/metrics")
pylab.savefig(
"click_metric_cr_%.3f_img_shape_%dx%d.png"
% (click_radius, image_shape[0], image_shape[1])
)
pylab.legend()
if display:
pylab.show()
return concepts
class ClickMetric(tf.keras.metrics.MeanAbsoluteError):
def __init__(self, name="click_metric", dtype=None):
super(ClickMetric, self).__init__(name=name, dtype=dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
return super().update_state(y_true, y_pred, sample_weight)
class ClickLoss(tf.keras.losses.MeanSquaredError):
def call(self, ci_true, ci_pred):
com_true = tf_center_of_mass(ci_true)
com_pred = tf_centre_of_mass(ci_pred)
mse = super().call(com_true, com_pred)
mse = replacenan(mse)
bcl = tf.reduce_mean(
tf.keras.losses.binary_crossentropy(ci_true, ci_pred), axis=(1, 2)
)
click_present = tf.reshape(K.max(ci_true, axis=(1, 2)), (-1))
total = bcl * (1 - click_present) + mse * (click_present)
return total
def gauss2d(x=0, y=0, mx=0, my=0, sx=1, sy=1):
return np.exp(
-((x - mx) ** 2.0 / (2.0 * sx**2.0) + (y - my) ** 2.0 / (2.0 * sy**2.0))
)
def click_probability_image(
click_x,
click_y,
img_shape,
zoom=1,
click_radius=320e-3,
resize_factor=1.0,
scale_click=True,
):
x = np.arange(0, img_shape[1], 1)
y = np.arange(0, img_shape[0], 1)
x, y = np.meshgrid(x, y)
if scale_click:
mmppx = calibrations[zoom] / resize_factor
else:
mmppx = calibrations[1] / resize_factor
sx = click_radius / mmppx.mean()
sy = sx
z = gauss2d(x, y, mx=click_x, my=click_y, sx=sx, sy=sy)
return z
def replacenan(t):
return tf.where(tf.math.is_nan(t), tf.zeros_like(t), t)
def click_loss(ci_true, ci_pred):
total = tf.keras.losses.mean_squared_error(ci_true, ci_pred)
return total
def tf_center_of_mass(image_batch, threshold=0.5):
"""https://stackoverflow.com/questions/51724450/finding-centre-of-mass-of-tensor-tensorflow"""
print(image_batch.shape)
tf.cast(image_batch >= threshold, tf.float32)
batch_size, height, width, depth = image_batch.shape
# Make array of coordinates (each row contains three coordinates)
ii, jj, kk = tf.meshgrid(
tf.range(height), tf.range(width), tf.range(depth), indexing="ij"
)
coords = tf.stack(
[tf.reshape(ii, (-1,)), tf.reshape(jj, (-1,)), tf.reshape(kk, (-1))], axis=-1
)
coords = tf.cast(coords, tf.float32)
# Rearrange input into one vector per volume
volumes_flat = tf.reshape(image_batch, [-1, height * width, 1])
# Compute total mass for each volume
total_mass = tf.reduce_sum(volumes_flat, axis=1)
# Compute centre of mass
centre_of_mass = tf.reduce_sum(volumes_flat * coords, axis=1) / total_mass
return centre_of_mass
def click_image_loss(ci_true, ci_pred):
if K.max(ci_true) == 0:
return tf.keras.losses.binary_crossentropy(y_true, y_pred)
y_true = centre_of_mass(ci_true)
y_pred = centre_of_mass(ci_pred)
return tf.keras.losses.mean_squared_error(y_true, y_pred)
def click_mean_absolute_error(ci_true, ci_pred):
if K.max(ci_pred) < 0.5 and K.max(ci_true) == 0:
return 0
y_true = centre_of_mass(ci_true)
y_pred = centre_of_mass(ci_pred)
return tf.keras.losses.mean_absolute_error(y_true, y_pred)
def click_batch_loss(click_true_batch, click_pred_image_batch):
return [
click_loss(click_true, click_pred_image)
for click_true, click_pred_image in zip(
click_true_batch, click_pred_image_batch
)
]
def get_click_from_single_click_image(click_image):
click_pred = np.zeros((3,))
m = click_image.max()
click_pred[:2] = np.array(
np.unravel_index(np.argmax(click_image), click_image.shape)[:2], dtype="float32"
)
click_pred[2] = m
return click_pred
def get_clicks_from_click_image_batch(click_image_batch):
input_shape = click_image_batch.shape
output_shape = (input_shape[0], 3)
click_pred = np.zeros(output_shape)
for k, click_image in enumerate(click_image_batch):
click_pred[k] = get_click_from_single_click_image(click_image)
return click_pred
def mean_iou(y_true, y_pred):
prec = []
for t in np.arange(0.5, 1.0, 0.05):
y_pred_ = tf.to_int32(y_pred > t)
score, up_opt = tf.metrics.mean_iou(y_true, y_pred_, 2)
K.get_session().run(tf.local_variables_initializer())
with tf.control_dependencies([up_opt]):
score = tf.identity(score)
prec.append(score)
return K.mean(K.stack(prec), axis=0)
def display_target(target_array):
normalized_array = (target_array.astype("uint8")) * 127
plt.axis("off")
plt.imshow(normalized_array[:, :, 0])
def flip_axis(x, axis):
x = np.asarray(x).swapaxes(axis, 0)
x = x[::-1, ...]
x = x.swapaxes(0, axis)
return x
def get_transposed_img_and_target(img, target):
new_axes_order = (
1,
0,
) + tuple(range(2, len(img.shape)))
img = np.transpose(img, new_axes_order)
new_axes_order = (
1,
0,
) + tuple(range(2, len(target.shape)))
target = np.transpose(target, new_axes_order) # [:len(target.shape)])
return img, target
def get_flipped_img_and_target(img, target):
axis = random.choice([0, 1])
img = flip_axis(img, axis)
target = flip_axis(target, axis)
return img, target
def get_transformed_img_and_target(
img,
target,
default_transform_gang=[0, 0, 0, 0, 1, 1],
zoom_factor=0.25,
shift_factor=0.25,
shear_factor=45,
size=(512, 512),
rotate_probability=1,
shift_probability=1,
shear_probability=1,
zoom_probability=1,
theta_min=-30.0,
theta_max=30.0,
resize=False,
):
if resize:
img = resize(img, size, anti_aliasing=True)
target = resize(target, size, anti_aliasing=True)
theta, tx, ty, shear, zx, zy = default_transform_gang
size_y, size_x = img.shape[:2]
# rotate
if random.random() < rotate_probability:
theta = random.uniform(theta_min, theta_max)
# shear
if random.random() < shear_probability:
shear = random.uniform(-shear_factor, +shear_factor)
# shift
if random.random() < shift_probability:
tx = random.uniform(-shift_factor * size_x, +shift_factor * size_x)
ty = random.uniform(-shift_factor * size_y, +shift_factor * size_y)
# zoom
if random.random() < zoom_probability:
zx = random.uniform(1 - zoom_factor, 1 + zoom_factor)
zy = zx
if np.any(np.array([theta, tx, ty, shear, zx, zy]) != default_transform_gang):
transform_arguments = {
"theta": theta,
"tx": tx,
"ty": ty,
"shear": shear,
"zx": zx,
"zy": zy,
}
img = image.apply_affine_transform(img, **transform_arguments)
target = image.apply_affine_transform(target, **transform_arguments)
# target = image.apply_affine_transform(target, fill_mode='constant', cval=0, **transform_arguments)
return img, target
def get_dataset(batch_size, img_size, img_paths, augment=False):
dataset = tf.data.Dataset.from_tensor_slices(img_paths)
def size_differs(original_size, img_size):
return original_size[0] != img_size[0] or original_size[1] != img_size[1]
def augment_sample(
img_path,
img,
target,
user_click,
do_swap_backgrounds,
do_flip,
do_transpose,
zoom,
candidate_backgrounds,
notions,
zoom_factor,
shift_factor,
shear_factor,
):
if do_swap_backgrounds is True and "background" not in img_path:
new_background = random.choice(candidate_backgrounds[zoom])
if size_differs(img.shape[:2], new_background.shape[:2]):
new_background = resize(new_background, img.shape[:2], anti_aliasing=True)
img[target[:, :, notions.index("foreground")] == 0] = new_background[
target[:, :, notions.index("foreground")] == 0
]
if self.augment and do_transpose is True:
img, target = get_transposed_img_and_target(img, target)
if self.augment and do_flip is True:
img, target = get_flipped_img_and_target(img, target)
if self.augment:
img, target = get_transformed_img_and_target(
img,
target,
zoom_factor=zoom_factor,
shift_factor=shift_factor,
shear_factor=shear_factor,
)
return img, target
def get_img_and_target(img_path, img_string="img.jpg", label_string="masks.npy"):
original_image = load_img(img_path)
original_size = original_image.size[::-1]
img = img_to_array(original_image, dtype="float32") / 255.0
masks_name = img_path.replace(img_string, label_string)
target = np.load(masks_name)
return img, target
def get_img(img_path, size=(224, 224)):
original_image = load_img(img_path)
img = img_to_array(original_image, dtype="float32") / 255.0
img = resize(img, size, anti_aliasing=True)
return img
def get_batch(i, img_paths, batch_size):
half, r = divmod(batch_size, 2)
indices = np.arange(i - half, i + half + r)
return [img_paths[divmod(item, len(img_paths))[1]] for item in indices]
def load_ground_truth_image(path, target_size):
ground_truth = np.expand_dims(
load_img(path, target_size=target_size, color_mode="grayscale"), 2
)
if ground_truth.max() > 0:
ground_truth = np.array(ground_truth / ground_truth.max(), dtype="uint8")
else:
ground_truth = np.array(ground_truth, dtype="uint8")
return ground_truth
class MultiTargetDataset(keras.utils.Sequence):
def __init__(
self,
batch_size,
img_size,
img_paths,
img_string="img.jpg",
label_string="masks.npy",
click_string="user_click.npy",
augment=False,
transform=True,
transpose=True,
flip=True,
swap_backgrounds=True,
zoom_factor=0.25,
shift_factor=0.25,
shear_factor=45,
default_transform_gang=[0, 0, 0, 0, 1, 1],
scale_click=False,
click_radius=320e-3,
min_scale=0.15,
max_scale=1.0,
dynamic_batch_size=False,
number_batch_size_scales=32,
possible_ratios=[0.75, 1.0],
pixel_budget=768 * 992,
artificial_size_increase=1,
notions=[
"crystal",
"loop_inside",
"loop",
"stem",
"pin",
"capillary",
"ice",
"foreground",
"click",
],
notion_indices={
"crystal": 0,
"loop_inside": 1,
"loop": 2,
"stem": 3,
"pin": 4,
"capillary": 5,
"ice": 6,
"foreground": 7,
"click": -1,
},
shuffle_at_0=False,
click="segmentation",
target=True,
black_and_white=True,
random_brightness=True,
random_channel_shift=False,
verbose=False,
):
self.batch_size = batch_size
self.img_size = img_size
if artificial_size_increase > 1:
self.img_paths = img_paths * int(artificial_size_increase)
else:
self.img_paths = img_paths
self.nimages = len(self.img_paths)
self.img_string = img_string
self.label_string = label_string
self.click_string = click_string
self.augment = augment
self.transform = transform
self.transpose = transpose
self.flip = flip
self.swap_backgrounds = swap_backgrounds
self.zoom_factor = zoom_factor
self.shift_factor = shift_factor
self.shear_factor = shear_factor
self.default_transform_gang = np.array(default_transform_gang)
self.scale_click = scale_click
self.click_radius = click_radius
self.dynamic_batch_size = dynamic_batch_size
if self.dynamic_batch_size:
self.batch_size = 1
self.possible_scales = np.linspace(
min_scale, max_scale, number_batch_size_scales
)
self.possible_ratios = possible_ratios
self.pixel_budget = pixel_budget
self.notions = notions
self.notion_indices = notion_indices
self.candidate_backgrounds = {}
self.batch_img_paths = []
if self.swap_backgrounds:
backgrounds = glob.glob("./Backgrounds/*.jpg") + glob.glob(
"./Backgrounds/*.tif"
)
for img_path in backgrounds:
zoom = int(re.findall(".*_zoom_([\\d]*).*", img_path)[0])
background = load_img(img_path)
background = img_to_array(background, dtype="float32") / 255.0
if zoom in self.candidate_backgrounds:
self.candidate_backgrounds[zoom].append(background)
else:
self.candidate_backgrounds[zoom] = [background]
self.shuffle_at_0 = shuffle_at_0
self.click = click
self.target = target
self.black_and_white = black_and_white
self.random_brightness = random_brightness
self.random_channel_shift = random_channel_shift
self.verbose = verbose
def __len__(self):
return math.ceil(len(self.img_paths) / self.batch_size)
def consider_click(self):
if self.target and "click" in self.notions:
return True
return False
def __getitem__(self, idx):
if idx == 0 and self.shuffle_at_0:
random.Random().shuffle(self.img_paths)
if self.dynamic_batch_size:
img_size = get_img_size_as_scale_of_pixel_budget(
random.choice(self.possible_scales),
pixel_budget=self.pixel_budget,
ratio=random.choice(self.possible_ratios),
)
batch_size = get_dynamic_batch_size(
img_size, pixel_budget=self.pixel_budget
)
i = idx
self.batch_img_paths = get_batch(i, self.img_paths, batch_size)
else:
img_size = self.img_size[:]
batch_size = self.batch_size
i = idx * self.batch_size
start_index = i
end_index = i + batch_size
self.batch_img_paths = self.img_paths[start_index:end_index]
final_img_size = img_size[:]
# this handles case at the very last step ...
batch_size = len(self.batch_img_paths)
do_flip = False
do_transpose = False
do_transform = False
do_swap_backgrounds = False
do_black_and_white = False
do_random_brightness = False
do_random_channel_shift = False
if self.augment:
if self.transform and random.random() < 0.5:
do_transform = True
if self.verbose:
print("do_transform")
if self.transpose and random.random() < 0.5:
final_img_size = img_size[::-1]
do_transpose = True
if self.verbose:
print("do_transpose")
if self.flip and random.random() < 0.5:
do_flip = True
if self.verbose:
print("do_flip")
else:
if self.flip and random.random() < 0.5:
do_flip = True
if self.verbose:
print("do_flip")
if self.swap_backgrounds and random.random() < 0.25:
do_swap_backgrounds = True
if self.verbose:
print("do_swap_backgrounds")
if self.black_and_white and random.random() < 0.25:
do_black_and_white = True
if self.verbose:
print("do_black_and_white")
if self.random_brightness and random.random() < 0.25:
do_random_brightness = True
if self.verbose:
print("do_random_brightness")
if (
not do_black_and_white
and self.random_channel_shift
and random.random() < 0.25
):
do_random_channel_shift = True
if self.verbose:
print("do_random_channel_shift")
x = np.zeros((batch_size,) + final_img_size + (3,), dtype="float32")
y = [
np.zeros((batch_size,) + final_img_size + (1,), dtype="uint8")
for notion in self.notions
if "click" not in notion
]
if "click" in self.notions:
if click == "click_segmentation":
y.append(
np.zeros((batch_size,) + final_img_size + (1,), dtype="float32")
)
else:
y.append(np.zeros((batch_size,) + (3,), dtype="float32"))
for j, img_path in enumerate(self.batch_img_paths):
resize_factor = 1.0
original_image = load_img(img_path)
original_size = original_image.size[::-1]