forked from Wuziyi616/CFUN
-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.py
1904 lines (1603 loc) · 83.9 KB
/
model.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
"""
CFUN
The main CFUN model implementation.
"""
import time
import math
import os
import re
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.utils.data
from torch.autograd import Variable
import utils
import backbone
import mask_branch
############################################################
# Logging Utility Functions
############################################################
def log(text, array=None):
"""Prints a text message. And, optionally, if a Numpy array is provided it
prints it's shape, min, and max values.
"""
if array is not None:
text = text.ljust(25)
text += ("shape: {:20} min: {:10.5f} max: {:10.5f}".format(
str(array.shape),
array.min() if array.size else "",
array.max() if array.size else ""))
print(text)
def print_progress_bar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill=''):
"""Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
prefix - Optional : prefix string (Str)
suffix - Optional : suffix string (Str)
decimals - Optional : positive number of decimals in percent complete (Int)
length - Optional : character length of bar (Int)
fill - Optional : bar fill character (Str)
"""
percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
filled_length = int(length * iteration // total)
bar = fill * filled_length + '-' * (length - filled_length)
print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end='\n')
# Print New Line on Complete
if iteration == total:
print()
############################################################
# Pytorch Utility Functions
############################################################
def unique1d(tensor):
if tensor.size()[0] == 0 or tensor.size()[0] == 1:
return tensor
tensor = tensor.sort()[0]
unique_bool = tensor[1:] != tensor[:-1]
first_element = Variable(torch.ByteTensor([True]), requires_grad=False)
if tensor.is_cuda:
first_element = first_element.cuda()
unique_bool = torch.cat((first_element, unique_bool), dim=0)
return tensor[unique_bool.detach()]
def intersect1d(tensor1, tensor2):
aux = torch.cat((tensor1, tensor2), dim=0)
aux = aux.sort()[0]
return aux[:-1][(aux[1:] == aux[:-1]).detach()]
def log2(x):
"""Implementation of log2. Pytorch doesn't have a native implementation."""
ln2 = torch.log(torch.FloatTensor([2.0]))
if x.is_cuda:
ln2 = ln2.cuda()
return torch.log(x) / ln2
def compute_backbone_shapes(config, image_shape):
"""Computes the depth, width and height of each stage of the backbone network.
Returns:
[N, (depth, height, width)]. Where N is the number of stages
"""
H, W, D = image_shape[:3]
return np.array(
[[int(math.ceil(D / stride)),
int(math.ceil(H / stride)),
int(math.ceil(W / stride))]
for stride in config.BACKBONE_STRIDES])
############################################################
# FPN Graph
############################################################
class TopDownLayer(nn.Module):
"""Generate the Pyramid Feature Maps.
Returns [p2_out, p3_out, c0_out], where p2_out and p3_out is used for RPN
and c0_out is used for mrcnn mask branch.
"""
def __init__(self, in_channels, out_channels):
super(TopDownLayer, self).__init__()
self.conv1 = nn.Conv3d(in_channels, out_channels, kernel_size=1, stride=1)
self.conv2 = nn.Conv3d(out_channels, out_channels, kernel_size=3, stride=1, padding=1)
def forward(self, x, y):
y = F.interpolate(y, scale_factor=2)
x = self.conv1(x)
return self.conv2(x + y)
class FPN(nn.Module):
def __init__(self, C1, C2, C3, out_channels, config):
super(FPN, self).__init__()
self.out_channels = out_channels
self.C1 = C1
self.C2 = C2
self.C3 = C3
self.P3_conv1 = nn.Conv3d(config.BACKBONE_CHANNELS[1] * 4, self.out_channels, kernel_size=1, stride=1)
self.P3_conv2 = nn.Conv3d(self.out_channels, self.out_channels, kernel_size=3, stride=1, padding=1)
self.P2_conv1 = nn.Conv3d(config.BACKBONE_CHANNELS[0] * 4, self.out_channels, kernel_size=1, stride=1)
self.P2_conv2 = nn.Conv3d(self.out_channels, self.out_channels, kernel_size=3, stride=1, padding=1)
def forward(self, x):
x = self.C1(x)
x = self.C2(x)
c2_out = x
x = self.C3(x)
c3_out = x
p3_out = self.P3_conv1(c3_out)
p2_out = self.P2_conv1(c2_out) + F.upsample(p3_out, scale_factor=2)
p3_out = self.P3_conv2(p3_out)
p2_out = self.P2_conv2(p2_out)
return [p2_out, p3_out]
############################################################
# Proposal Layer
############################################################
def apply_box_deltas(boxes, deltas):
"""Applies the given deltas to the given boxes.
boxes: [N, 6] where each row is z1, y1, x1, z2, y2, x2
deltas: [N, 6] where each row is [dz, dy, dx, log(dd), log(dh), log(dw)]
"""
# Convert to z, y, x, d, h, w
depth = boxes[:, 3] - boxes[:, 0]
height = boxes[:, 4] - boxes[:, 1]
width = boxes[:, 5] - boxes[:, 2]
center_z = boxes[:, 0] + 0.5 * depth
center_y = boxes[:, 1] + 0.5 * height
center_x = boxes[:, 2] + 0.5 * width
# Apply deltas
center_z += deltas[:, 0] * depth
center_y += deltas[:, 1] * height
center_x += deltas[:, 2] * width
depth *= torch.exp(deltas[:, 3])
height *= torch.exp(deltas[:, 4])
width *= torch.exp(deltas[:, 5])
# Convert back to z1, y1, x1, z2, y2, x2
z1 = center_z - 0.5 * depth
y1 = center_y - 0.5 * height
x1 = center_x - 0.5 * width
z2 = z1 + depth
y2 = y1 + height
x2 = x1 + width
result = torch.stack([z1, y1, x1, z2, y2, x2], dim=1)
return result
def clip_boxes(boxes, window):
"""boxes: [N, 6] each col is z1, y1, x1, z2, y2, x2
window: [6] in the form z1, y1, x1, z2, y2, x2
"""
boxes = torch.stack(
[boxes[:, 0].clamp(float(window[0]), float(window[3])),
boxes[:, 1].clamp(float(window[1]), float(window[4])),
boxes[:, 2].clamp(float(window[2]), float(window[5])),
boxes[:, 3].clamp(float(window[0]), float(window[3])),
boxes[:, 4].clamp(float(window[1]), float(window[4])),
boxes[:, 5].clamp(float(window[2]), float(window[5]))], 1)
return boxes
def proposal_layer(inputs, proposal_count, nms_threshold, anchors, config=None):
"""Receives anchor scores and selects a subset to pass as proposals
to the second stage. Filtering is done based on anchor scores and
non-max suppression to remove overlaps. It also applies bounding
box refinement deltas to anchors.
Inputs:
rpn_probs: [batch, anchors, (bg prob, fg prob)]
rpn_bbox: [batch, anchors, (dz, dy, dx, log(dd), log(dh), log(dw))]
Returns:
Proposals in normalized coordinates [batch, rois, (z1, y1, x1, z2, y2, x2)]
"""
# Currently only supports batchsize 1
inputs[0] = inputs[0].squeeze(0)
inputs[1] = inputs[1].squeeze(0)
# Box Scores. Use the foreground class confidence. [Batch, num_rois, 1]
scores = inputs[0][:, 1]
# Box deltas [batch, num_rois, 6]
deltas = inputs[1]
std_dev = torch.from_numpy(np.reshape(config.RPN_BBOX_STD_DEV, [1, 6])).float()
if config.GPU_COUNT:
std_dev = std_dev.cuda()
deltas = deltas * std_dev
# Improve performance by trimming to top anchors by score
# and doing the rest on the smaller subset.
pre_nms_limit = min(config.PRE_NMS_LIMIT, anchors.size()[0])
scores, order = scores.sort(descending=True)
order = order[:pre_nms_limit]
scores = scores[:pre_nms_limit]
deltas = deltas[order.detach(), :]
anchors = anchors[order.detach(), :]
# Apply deltas to anchors to get refined anchors.
# [batch, N, (z1, y1, x1, z2, y2, x2)]
boxes = apply_box_deltas(anchors, deltas)
# Clip to image boundaries. [batch, N, (z1, y1, x1, z2, y2, x2)]
height, width, depth = config.IMAGE_SHAPE[:3]
window = np.array([0, 0, 0, depth, height, width]).astype(np.float32)
boxes = clip_boxes(boxes, window)
# Non-max suppression
keep = utils.non_max_suppression(boxes.cpu().detach().numpy(),
scores.cpu().detach().numpy(), nms_threshold, proposal_count)
keep = torch.from_numpy(keep).long()
boxes = boxes[keep, :]
# Normalize dimensions to range of 0 to 1.
norm = torch.from_numpy(np.array([depth, height, width, depth, height, width])).float()
if config.GPU_COUNT:
norm = norm.cuda()
normalized_boxes = boxes / norm
# Add back batch dimension
normalized_boxes = normalized_boxes.unsqueeze(0)
return normalized_boxes
############################################################
# ROIAlign Layer
############################################################
def RoI_Align(feature_map, pool_size, boxes):
"""Implementation of 3D RoI Align (actually it's just pooling rather than align).
feature_map: [channels, depth, height, width]. Generated from FPN.
pool_size: [D, H, W]. The shape of the output.
boxes: [num_boxes, (z1, y1, x1, z2, y2, x2)].
"""
boxes = utils.denorm_boxes_graph(boxes, (feature_map.size()[1], feature_map.size()[2], feature_map.size()[3]))
boxes[:, 0] = boxes[:, 0].floor()
boxes[:, 1] = boxes[:, 1].floor()
boxes[:, 2] = boxes[:, 2].floor()
boxes[:, 3] = boxes[:, 3].ceil()
boxes[:, 4] = boxes[:, 4].ceil()
boxes[:, 5] = boxes[:, 5].ceil()
boxes = boxes.long()
output = torch.zeros((boxes.size()[0], feature_map.size()[0], pool_size[0], pool_size[1], pool_size[2])).cuda()
for i in range(boxes.size()[0]):
try:
output[i] = F.interpolate((feature_map[:, boxes[i][0]:boxes[i][3], boxes[i][1]:boxes[i][4], boxes[i][2]:boxes[i][5]]).unsqueeze(0),
size=pool_size, mode='trilinear', align_corners=True).cuda()
except:
print("RoI_Align error!")
print("box:", boxes[i], "feature_map size:", feature_map.size())
pass
return output.cuda()
def pyramid_roi_align(inputs, pool_size, test_flag=False):
"""Implements ROI Pooling on multiple levels of the feature pyramid.
Params:
- pool_size: [depth, height, width] of the output pooled regions. Usually [7, 7, 7]
- image_shape: [height, width, depth, channels]. Shape of input image in pixels
Inputs:
- boxes: [batch, num_boxes, (z1, y1, x1, z2, y2, x2)] in normalized coordinates.
- Feature maps: List of feature maps from different levels of the pyramid.
Each is [batch, channels, depth, height, width]
Output:
Pooled regions in the shape: [num_boxes, channels, depth, height, width].
The width, height and depth are those specific in the pool_shape in the layer
constructor.
"""
# Currently only supports batchsize 1
if test_flag:
for i in range(0, len(inputs)):
inputs[i] = inputs[i].squeeze(0)
else:
for i in range(1, len(inputs)):
inputs[i] = inputs[i].squeeze(0)
# Crop boxes [batch, num_boxes, (y1, x1, z1, y2, x2, z2)] in normalized coordinates
boxes = inputs[0]
# Feature Maps. List of feature maps from different level of the
# feature pyramid. Each is [batch, channels, depth, height, width]
feature_maps = inputs[1:]
# Assign each ROI to a level in the pyramid based on the ROI volume.
z1, y1, x1, z2, y2, x2 = boxes.chunk(6, dim=1)
d = z2 - z1
h = y2 - y1
w = x2 - x1
# Equation 1 in the Feature Pyramid Networks paper.
# Account for the fact that our coordinates are normalized here.
# TODO: change the equation here
roi_level = 4 + (1. / 3.) * log2(h * w * d)
roi_level = roi_level.round().int()
roi_level = roi_level.clamp(2, 3)
# Loop through levels and apply ROI pooling to P2 or P3.
pooled = []
box_to_level = []
for i, level in enumerate(range(2, 4)):
ix = (roi_level == level)
if not ix.any():
continue
ix = torch.nonzero(ix)[:, 0]
level_boxes = boxes[ix.detach(), :]
# Keep track of which box is mapped to which level
box_to_level.append(ix.detach())
# Stop gradient propagation to ROI proposals
level_boxes = level_boxes.detach()
# Crop and Resize
# From Mask R-CNN paper: "We sample four regular locations, so that we can evaluate
# either max or average pooling. In fact, interpolating only a single value at each bin center
# (without pooling) is nearly as effective."
# Here we use the simplified approach of a single value per bin.
# Result: [batch * num_boxes, channels, pool_depth, pool_height, pool_width]
pooled_features = RoI_Align(feature_maps[i], pool_size, level_boxes)
pooled.append(pooled_features)
# Pack pooled features into one tensor
pooled = torch.cat(pooled, dim=0)
# Pack box_to_level mapping into one array and add another
# column representing the order of pooled boxes
box_to_level = torch.cat(box_to_level, dim=0)
# Rearrange pooled features to match the order of the original boxes
_, box_to_level = torch.sort(box_to_level)
pooled = pooled[box_to_level, :, :, :]
return pooled
############################################################
# Detection Target Layer
############################################################
def bbox_overlaps(boxes1, boxes2):
"""Computes IoU overlaps between two sets of boxes.
boxes1, boxes2: [N, (z1, y1, x1, z2, y2, x2)].
"""
# 1. Tile boxes2 and repeat boxes1. This allows us to compare
# every boxes1 against every boxes2 without loops.
boxes1_repeat = boxes2.size()[0]
boxes2_repeat = boxes1.size()[0]
boxes1 = boxes1.repeat(1, boxes1_repeat).view(-1, 6)
boxes2 = boxes2.repeat(boxes2_repeat, 1)
# 2. Compute intersections
b1_z1, b1_y1, b1_x1, b1_z2, b1_y2, b1_x2 = boxes1.chunk(6, dim=1)
b2_z1, b2_y1, b2_x1, b2_z2, b2_y2, b2_x2 = boxes2.chunk(6, dim=1)
z1 = torch.max(b1_z1, b2_z1)[:, 0]
y1 = torch.max(b1_y1, b2_y1)[:, 0]
x1 = torch.max(b1_x1, b2_x1)[:, 0]
z2 = torch.min(b1_z2, b2_z2)[:, 0]
y2 = torch.min(b1_y2, b2_y2)[:, 0]
x2 = torch.min(b1_x2, b2_x2)[:, 0]
zeros = Variable(torch.zeros(z1.size()[0]), requires_grad=False)
if z1.is_cuda:
zeros = zeros.cuda()
intersection = torch.max(x2 - x1, zeros) * torch.max(y2 - y1, zeros) * torch.max(z2 - z1, zeros)
# 3. Compute unions
b1_volume = (b1_z2 - b1_z1) * (b1_y2 - b1_y1) * (b1_x2 - b1_x1)
b2_volume = (b2_z2 - b2_z1) * (b2_y2 - b2_y1) * (b2_x2 - b2_x1)
union = b1_volume[:, 0] + b2_volume[:, 0] - intersection
# 4. Compute IoU and reshape to [boxes1, boxes2]
iou = intersection / union
overlaps = iou.view(boxes2_repeat, boxes1_repeat)
return overlaps
def detection_target_layer(proposals, gt_class_ids, gt_boxes, gt_masks, config):
"""Subsamples proposals and generates target box refinement, class_ids,
and masks for each.
Inputs:
proposals: [batch, N, (z1, y1, x1, z2, y2, x2)] in normalized coordinates. Might
be zero padded if there are not enough proposals.
gt_class_ids: [batch, MAX_GT_INSTANCES] Integer class IDs.
gt_boxes: [batch, MAX_GT_INSTANCES, (z1, y1, x1, z2, y2, x2)] in normalized
coordinates.
gt_masks: [batch, MAX_GT_INSTANCES, depth, height, width] of np.int32 type
Returns: Target ROIs and corresponding class IDs, bounding box shifts,
and masks.
rois: [batch, TRAIN_ROIS_PER_IMAGE, (z1, y1, x1, z2, y2, x2)] in normalized coordinates
target_class_ids: [batch, TRAIN_ROIS_PER_IMAGE]. Integer class IDs.
target_deltas: [batch, TRAIN_ROIS_PER_IMAGE, NUM_CLASSES,
(dz, dy, dx, log(dd), log(dh), log(dw), class_id)]
Class-specific bbox refinements.
target_mask: [batch, TRAIN_ROIS_PER_IMAGE, depth, height, width)
Masks cropped to bbox boundaries and resized to neural
network output size.
"""
# Currently only supports batchsize 1
proposals = proposals.squeeze(0)
gt_class_ids = gt_class_ids.squeeze(0)
gt_boxes = gt_boxes.squeeze(0)
gt_masks = gt_masks.squeeze(0)
# Compute overlaps matrix [proposals, gt_boxes]
overlaps = bbox_overlaps(proposals, gt_boxes)
# Determine positive and negative ROIs
roi_iou_max = torch.max(overlaps, dim=1)[0]
print("rpn_roi_iou_max:", roi_iou_max.max())
# 1. Positive ROIs are those with >= 0.5 IoU with a GT box
positive_roi_bool = roi_iou_max >= config.DETECTION_TARGET_IOU_THRESHOLD
# Subsample ROIs. Aim for 33% positive
# Positive ROIs
if torch.nonzero(positive_roi_bool).size()[0] != 0:
positive_indices = torch.nonzero(positive_roi_bool)[:, 0]
positive_count = int(config.TRAIN_ROIS_PER_IMAGE *
config.ROI_POSITIVE_RATIO)
rand_idx = torch.randperm(positive_indices.size()[0])
rand_idx = rand_idx[:positive_count]
if config.GPU_COUNT:
rand_idx = rand_idx.cuda()
positive_indices = positive_indices[rand_idx]
positive_count = positive_indices.size()[0]
positive_rois = proposals[positive_indices.detach(), :]
# Assign positive ROIs to GT boxes.
positive_overlaps = overlaps[positive_indices.detach(), :]
roi_gt_box_assignment = torch.max(positive_overlaps, dim=1)[1]
roi_gt_boxes = gt_boxes[roi_gt_box_assignment.detach(), :]
roi_gt_class_ids = gt_class_ids[roi_gt_box_assignment.detach()]
# Compute bbox refinement for positive ROIs
deltas = Variable(utils.box_refinement(positive_rois.detach(), roi_gt_boxes.detach()), requires_grad=False)
std_dev = torch.from_numpy(config.BBOX_STD_DEV).float()
if config.GPU_COUNT:
std_dev = std_dev.cuda()
deltas /= std_dev
# Assign positive ROIs to GT masks
# Permute masks to [N, depth, height, width]
# Pick the right mask for each ROI
roi_gt_masks = np.zeros((positive_rois.shape[0], 8,) + config.MASK_SHAPE)
for i in range(0, positive_rois.shape[0]):
z1 = int(gt_masks.shape[1]*positive_rois[i, 0])
z2 = int(gt_masks.shape[1]*positive_rois[i, 3])
y1 = int(gt_masks.shape[2]*positive_rois[i, 1])
y2 = int(gt_masks.shape[2]*positive_rois[i, 4])
x1 = int(gt_masks.shape[3]*positive_rois[i, 2])
x2 = int(gt_masks.shape[3]*positive_rois[i, 5])
crop_mask = gt_masks[:, z1:z2, y1:y2, x1:x2].cpu().numpy()
crop_mask = utils.resize(crop_mask, (8,) + config.MASK_SHAPE, order=0, preserve_range=True)
roi_gt_masks[i, :, :, :, :] = crop_mask
roi_gt_masks = torch.from_numpy(roi_gt_masks).cuda()
roi_gt_masks = roi_gt_masks.type(torch.DoubleTensor)
else:
positive_count = 0
# 2. Negative ROIs are those with < 0.5 with every GT box.
negative_roi_bool = roi_iou_max < config.DETECTION_TARGET_IOU_THRESHOLD
negative_roi_bool = negative_roi_bool
# Negative ROIs. Add enough to maintain positive:negative ratio.
if torch.nonzero(negative_roi_bool).size()[0] != 0 and positive_count > 0:
negative_indices = torch.nonzero(negative_roi_bool)[:, 0]
r = 1.0 / config.ROI_POSITIVE_RATIO
negative_count = int(r * positive_count - positive_count)
rand_idx = torch.randperm(negative_indices.size()[0])
rand_idx = rand_idx[:negative_count]
if config.GPU_COUNT:
rand_idx = rand_idx.cuda()
negative_indices = negative_indices[rand_idx]
negative_count = negative_indices.size()[0]
negative_rois = proposals[negative_indices.detach(), :]
else:
negative_count = 0
# Append negative ROIs and pad bbox deltas and masks that
# are not used for negative ROIs with zeros.
if positive_count > 0 and negative_count > 0:
rois = torch.cat((positive_rois, negative_rois), dim=0)
zeros = Variable(torch.zeros(negative_count), requires_grad=False).long()
if config.GPU_COUNT:
zeros = zeros.cuda()
roi_gt_class_ids = torch.cat([roi_gt_class_ids.long(), zeros], dim=0)
zeros = Variable(torch.zeros(negative_count, 6), requires_grad=False)
if config.GPU_COUNT:
zeros = zeros.cuda()
deltas = torch.cat([deltas, zeros], dim=0)
zeros = Variable(torch.zeros(negative_count, config.MASK_SHAPE[0], config.MASK_SHAPE[1], config.MASK_SHAPE[2]),
requires_grad=False)
if config.GPU_COUNT:
zeros = zeros.cuda()
masks = roi_gt_masks
elif positive_count > 0:
rois = positive_rois
elif negative_count > 0:
positive_rois = Variable(torch.FloatTensor(), requires_grad=False)
rois = negative_rois
zeros = Variable(torch.zeros(negative_count), requires_grad=False)
if config.GPU_COUNT:
zeros = zeros.cuda()
positive_rois = positive_rois.cuda()
roi_gt_class_ids = zeros
zeros = Variable(torch.zeros(negative_count, 6), requires_grad=False).int()
if config.GPU_COUNT:
zeros = zeros.cuda()
deltas = zeros
zeros = Variable(torch.zeros(negative_count, config.MASK_SHAPE[0], config.MASK_SHAPE[1], config.MASK_SHAPE[2]),
requires_grad=False)
if config.GPU_COUNT:
zeros = zeros.cuda()
masks = zeros
else:
positive_rois = Variable(torch.FloatTensor(), requires_grad=False)
rois = Variable(torch.FloatTensor(), requires_grad=False)
roi_gt_class_ids = Variable(torch.IntTensor(), requires_grad=False)
deltas = Variable(torch.FloatTensor(), requires_grad=False)
masks = Variable(torch.FloatTensor(), requires_grad=False)
if config.GPU_COUNT:
positive_rois = positive_rois.cuda()
rois = rois.cuda()
roi_gt_class_ids = roi_gt_class_ids.cuda()
deltas = deltas.cuda()
masks = masks.cuda()
return positive_rois, rois, roi_gt_class_ids, deltas, masks
############################################################
# Detection Layer
############################################################
def clip_to_window(window, boxes):
"""window: (z1, y1, x1, z2, y2, x2). The window in the image we want to clip to.
boxes: [N, (z1, y1, x1, z2, y2, x2)]
"""
boxes[:, 0] = boxes[:, 0].clamp(float(window[0]), float(window[3]))
boxes[:, 1] = boxes[:, 1].clamp(float(window[1]), float(window[4]))
boxes[:, 2] = boxes[:, 2].clamp(float(window[2]), float(window[5]))
boxes[:, 3] = boxes[:, 3].clamp(float(window[0]), float(window[3]))
boxes[:, 4] = boxes[:, 4].clamp(float(window[1]), float(window[4]))
boxes[:, 5] = boxes[:, 5].clamp(float(window[2]), float(window[5]))
return boxes
def refine_detections(rois, probs, deltas, window, config):
"""Refine classified proposals and filter overlaps and return final
detections.
Inputs:
rois: [N, (z1, y1, x1, z2, y2, x2)] in normalized coordinates
probs: [N, num_classes]. Class probabilities.
deltas: [N, num_classes, (dz, dy, dx, log(dd), log(dh), log(dw))]. Class-specific
bounding box deltas.
window: (z1, y1, x1, z2, y2, x2) in image coordinates. The part of the image
that contains the image excluding the padding.
Returns detections shaped: [N, (z1, y1, x1, z2, y2, x2, class_id, score)]
"""
# Class IDs per ROI
_, class_ids = torch.max(probs, dim=1)
# Class probability of the top class of each ROI
# Class-specific bounding box deltas
idx = torch.arange(class_ids.size()[0]).long()
if config.GPU_COUNT:
idx = idx.cuda()
class_scores = probs[idx, class_ids.detach()]
deltas_specific = deltas[idx, class_ids.detach()]
# Apply bounding box deltas
# Shape: [boxes, (z1, y1, x1, z2, y2, x2)] in normalized coordinates
std_dev = torch.from_numpy(np.reshape(config.RPN_BBOX_STD_DEV, [1, 6])).float()
if config.GPU_COUNT:
std_dev = std_dev.cuda()
refined_rois = apply_box_deltas(rois, deltas_specific * std_dev)
# Convert coordinates to image domain
height, width, depth = config.IMAGE_SHAPE[:3]
scale = torch.from_numpy(np.array([depth, height, width, depth, height, width])).float()
if config.GPU_COUNT:
scale = scale.cuda()
refined_rois *= scale
# Clip boxes to image window
refined_rois = clip_to_window(window, refined_rois)
# Round and cast to int since we're dealing with pixels now
refined_rois = torch.round(refined_rois)
# Filter out background boxes
keep_bool = class_ids > 0
# Filter out low confidence boxes
if config.DETECTION_MIN_CONFIDENCE:
keep_bool = keep_bool & (class_scores >= config.DETECTION_MIN_CONFIDENCE)
keep = torch.nonzero(keep_bool)[:, 0]
# Apply per-class NMS
pre_nms_class_ids = class_ids[keep.detach()]
pre_nms_scores = class_scores[keep.detach()]
pre_nms_rois = refined_rois[keep.detach()]
for i, class_id in enumerate(unique1d(pre_nms_class_ids)):
# Pick detections of this class
ixs = torch.nonzero(pre_nms_class_ids == class_id)[:, 0]
# Sort
ix_rois = pre_nms_rois[ixs.detach()]
ix_scores = pre_nms_scores[ixs]
ix_scores, order = ix_scores.sort(descending=True)
ix_rois = ix_rois[order.detach(), :]
class_keep = utils.non_max_suppression(ix_rois.cpu().detach().numpy(), ix_scores.cpu().detach().numpy(),
config.DETECTION_NMS_THRESHOLD, config.DETECTION_MAX_INSTANCES)
class_keep = torch.from_numpy(class_keep).long()
# Map indices
class_keep = keep[ixs[order[class_keep].detach()].detach()]
if i == 0:
nms_keep = class_keep
else:
nms_keep = unique1d(torch.cat((nms_keep, class_keep)))
keep = intersect1d(keep, nms_keep)
# Keep top detections
roi_count = config.DETECTION_MAX_INSTANCES
roi_count = min(roi_count, keep.size()[0])
top_ids = class_scores[keep.detach()].sort(descending=True)[1][:roi_count]
keep = keep[top_ids.detach()]
# Arrange output as [N, (z1, y1, x1, z2, y2, x2, class_id, score)]
# Coordinates are in image domain.
result = torch.cat((refined_rois[keep.detach()],
class_ids[keep.detach()].unsqueeze(1).float(),
class_scores[keep.detach()].unsqueeze(1)), dim=1)
return result
def detection_layer(config, rois, mrcnn_class, mrcnn_bbox, image_meta):
"""Takes classified proposal boxes and their bounding box deltas and
returns the final detection boxes.
Returns:
[batch, num_detections, (z1, y1, x1, z2, y2, x2, class_score)] in pixels
"""
# Currently only supports batchsize 1
rois = rois.squeeze(0)
_, _, window, _ = parse_image_meta(image_meta)
window = window[0]
detections = refine_detections(rois, mrcnn_class, mrcnn_bbox, window, config)
return detections
############################################################
# Region Proposal Network
############################################################
class RPN(nn.Module):
"""Builds the model of Region Proposal Network.
anchors_per_location: number of anchors per pixel in the feature map
anchor_stride: Controls the density of anchors. Typically 1 (anchors for
every pixel in the feature map), or 2 (every other pixel).
Returns:
rpn_logits: [batch, D, H, W, 2] Anchor classifier logits (before softmax)
rpn_probs: [batch, D, H, W, 2] Anchor classifier probabilities.
rpn_bbox: [batch, D, H, W, (dz, dy, dx, log(dd), log(dh), log(dw))] Deltas to be applied to anchors.
"""
def __init__(self, anchors_per_location, anchor_stride, channel, conv_channel):
super(RPN, self).__init__()
self.conv_shared = nn.Conv3d(channel, conv_channel, kernel_size=3, stride=anchor_stride, padding=1)
self.relu = nn.ReLU(inplace=True)
self.conv_class = nn.Conv3d(conv_channel, 2 * anchors_per_location, kernel_size=1, stride=1)
self.softmax = nn.Softmax(dim=2)
self.conv_bbox = nn.Conv3d(conv_channel, 6 * anchors_per_location, kernel_size=1, stride=1)
def forward(self, x):
# Shared convolutional base of the RPN
x = self.relu(self.conv_shared(x))
# Anchor Score. [batch, anchors per location * 2, depth, height, width].
rpn_class_logits = self.conv_class(x)
# Reshape to [batch, anchors, 2]
rpn_class_logits = rpn_class_logits.permute(0, 2, 3, 4, 1)
rpn_class_logits = rpn_class_logits.contiguous()
rpn_class_logits = rpn_class_logits.view(x.size()[0], -1, 2)
# Softmax on last dimension of BG/FG.
rpn_probs = self.softmax(rpn_class_logits)
# Bounding box refinement. [batch, anchors per location * 6, D, H, W]
# where 6 == delta [z, y, x, log(d), log(h), log(w)]
rpn_bbox = self.conv_bbox(x)
# Reshape to [batch, anchors, 6]
rpn_bbox = rpn_bbox.permute(0, 2, 3, 4, 1)
rpn_bbox = rpn_bbox.contiguous()
rpn_bbox = rpn_bbox.view(x.size()[0], -1, 6)
return [rpn_class_logits, rpn_probs, rpn_bbox]
############################################################
# Feature Pyramid Network Heads
############################################################
class Classifier(nn.Module):
def __init__(self, channel, pool_size, image_shape, num_classes, fc_size, test_flag=False):
super(Classifier, self).__init__()
self.pool_size = pool_size
self.image_shape = image_shape
self.fc_size = fc_size
self.test_flag = test_flag
self.conv1 = nn.Conv3d(channel, fc_size, kernel_size=self.pool_size, stride=1)
self.bn1 = nn.BatchNorm3d(fc_size, eps=0.001, momentum=0.01)
self.conv2 = nn.Conv3d(fc_size, fc_size, kernel_size=1, stride=1)
self.bn2 = nn.BatchNorm3d(fc_size, eps=0.001, momentum=0.01)
self.relu = nn.ReLU(inplace=True)
self.linear_class = nn.Linear(fc_size, num_classes)
self.softmax = nn.Softmax(dim=1)
self.linear_bbox = nn.Linear(fc_size, num_classes * 6)
def forward(self, x, rois):
x = pyramid_roi_align([rois] + x, self.pool_size, self.test_flag)
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.conv2(x)
x = self.bn2(x)
x = self.relu(x)
x = x.view(-1, self.fc_size)
mrcnn_class_logits = self.linear_class(x)
mrcnn_probs = self.softmax(mrcnn_class_logits)
mrcnn_bbox = self.linear_bbox(x)
mrcnn_bbox = mrcnn_bbox.view(mrcnn_bbox.size()[0], -1, 6)
return [mrcnn_class_logits, mrcnn_probs, mrcnn_bbox]
class Mask(nn.Module):
def __init__(self, channel, pool_size, num_classes, conv_channel, stage, test_flag=False):
super(Mask, self).__init__()
self.pool_size = pool_size
self.test_flag = test_flag
self.modified_u_net = mask_branch.Modified3DUNet(channel, num_classes, stage, conv_channel)
self.softmax = nn.Softmax(dim=1)
def forward(self, x, rois):
x = pyramid_roi_align([rois] + x, self.pool_size, self.test_flag)
x = self.modified_u_net(x)
output = self.softmax(x)
return x, output
############################################################
# Loss Functions
############################################################
def compute_rpn_class_loss(rpn_match, rpn_class_logits):
"""RPN anchor classifier loss.
rpn_match: [batch, anchors, 1]. Anchor match type. 1=positive,
-1=negative, 0=neutral anchor.
rpn_class_logits: [batch, anchors, 2]. RPN classifier logits for FG/BG.
"""
# Squeeze last dim to simplify
rpn_match = rpn_match.squeeze(2)
# Get anchor classes. Convert the -1/+1 match to 0/1 values.
anchor_class = (rpn_match == 1).long()
# Positive and Negative anchors contribute to the loss,
# but neutral anchors (match value = 0) don't.
indices = torch.nonzero(rpn_match != 0)
# Pick rows that contribute to the loss and filter out the rest.
rpn_class_logits = rpn_class_logits[indices.detach()[:, 0], indices.detach()[:, 1], :]
anchor_class = anchor_class[indices.detach()[:, 0], indices.detach()[:, 1]]
# Cross-entropy loss
loss = F.cross_entropy(rpn_class_logits, anchor_class)
return loss
def compute_rpn_bbox_loss(target_bbox, rpn_match, rpn_bbox):
"""Return the RPN bounding box loss graph.
target_bbox: [batch, max positive anchors, (dz, dy, dx, log(dd), log(dh), log(dw))].
Uses 0 padding to fill in unused bbox deltas.
rpn_match: [batch, anchors, 1]. Anchor match type. 1=positive,
-1=negative, 0=neutral anchor.
rpn_bbox: [batch, anchors, (dz, dy, dx, log(dd), log(dh), log(dw))]
"""
# Squeeze last dim to simplify
rpn_match = rpn_match.squeeze(2)
# Positive anchors contribute to the loss, but negative and
# neutral anchors (match value of 0 or -1) don't.
indices = torch.nonzero(rpn_match == 1)
# Pick bbox deltas that contribute to the loss
rpn_bbox = rpn_bbox[indices.detach()[:, 0], indices.detach()[:, 1]]
# Trim target bounding box deltas to the same length as rpn_bbox.
target_bbox = target_bbox[0, :rpn_bbox.size()[0], :]
# Smooth L1 loss
loss = F.smooth_l1_loss(rpn_bbox, target_bbox)
return loss
def compute_mrcnn_class_loss(target_class_ids, pred_class_logits):
"""Loss for the classifier head of Mask RCNN.
target_class_ids: [batch, num_rois]. Integer class IDs. Uses zero
padding to fill in the array.
pred_class_logits: [batch, num_rois, num_classes]
"""
# Loss
if target_class_ids.size()[0] != 0:
loss = F.cross_entropy(pred_class_logits, target_class_ids.long())
else:
loss = Variable(torch.FloatTensor([0]), requires_grad=False)
if target_class_ids.is_cuda:
loss = loss.cuda()
return loss
def compute_mrcnn_bbox_loss(target_bbox, target_class_ids, pred_bbox):
"""Loss for Mask R-CNN bounding box refinement.
target_bbox: [batch, num_rois, (dz, dy, dx, log(dd), log(dh), log(dw))]
target_class_ids: [batch, num_rois]. Integer class IDs.
pred_bbox: [batch, num_rois, num_classes, (dz, dy, dx, log(dd), log(dh), log(dw))]
"""
if target_class_ids.size()[0] != 0:
# Only positive ROIs contribute to the loss. And only
# the right class_id of each ROI. Get their indices.
positive_roi_ix = torch.nonzero(target_class_ids > 0)[:, 0]
positive_roi_class_ids = target_class_ids[positive_roi_ix.detach()].long()
indices = torch.stack((positive_roi_ix, positive_roi_class_ids), dim=1)
# Gather the deltas (predicted and true) that contribute to loss
target_bbox = target_bbox[indices[:, 0].detach(), :]
pred_bbox = pred_bbox[indices[:, 0].detach(), indices[:, 1].detach(), :]
# Smooth L1 loss
loss = F.smooth_l1_loss(pred_bbox, target_bbox)
else:
loss = Variable(torch.FloatTensor([0]), requires_grad=False)
if target_class_ids.is_cuda:
loss = loss.cuda()
return loss
def compute_mrcnn_mask_loss(target_masks, target_class_ids, pred_masks):
"""Mask binary cross-entropy loss for the masks head.
target_masks: [batch, num_rois, depth, height, width].
A float32 tensor of values 0 or 1. Uses zero padding to fill array.
target_class_ids: [batch, num_rois]. Integer class IDs. Zero padded.
pred_masks: [batch, proposals, num_classes, depth, height, width] float32 tensor
with values from 0 to 1.
"""
if target_class_ids.size()[0] != 0:
# Only positive ROIs contribute to the loss. And only the class specific mask of each ROI.
positive_ix = torch.nonzero(target_class_ids > 0)[:, 0]
positive_class_ids = target_class_ids[positive_ix.detach()].long()
indices = torch.stack((positive_ix, positive_class_ids), dim=1)
# Gather the masks (predicted and true) that contribute to loss
y_true_ = target_masks[indices[:,0], :, :, :]
y_true = y_true_.long().cuda()
y_true = torch.argmax(y_true,dim=1)
y_pred = pred_masks[indices[:, 0].detach(), :, :, :, :]
# Binary cross entropy
los = nn.CrossEntropyLoss().cuda()
loss = los(y_pred, y_true)
else:
loss = Variable(torch.FloatTensor([0]), requires_grad=False)
if target_class_ids.is_cuda:
loss = loss.cuda()
return loss
def compute_mrcnn_mask_edge_loss(target_masks, target_class_ids, pred_masks):
"""Mask edge mean square error loss for the Edge Agreement Head.
Here I use the Sobel kernel without smoothing the ground_truth masks.
target_masks: [batch, num_rois, depth, height, width].
target_class_ids: [batch, num_rois]. Integer class IDs. Zero padded.
pred_masks: [batch, proposals, num_classes, depth, height, width] float32 tensor with values from 0 to 1.
"""
if target_class_ids.size()[0] != 0:
# Generate the xyz dimension Sobel kernels
kernel_x = np.array([[[1, 2, 1], [0, 0, 0], [-1, -2, -1]],
[[2, 4, 2], [0, 0, 0], [-2, -4, -2]],
[[1, 2, 1], [0, 0, 0], [-1, -2, -1]]])
kernel_y = kernel_x.transpose((1, 0, 2))
kernel_z = kernel_x.transpose((0, 2, 1))
kernel = torch.from_numpy(np.array([kernel_x, kernel_y, kernel_z]).reshape((3, 1, 3, 3, 3))).float().cuda()
# Only positive ROIs contribute to the loss. And only the class specific mask of each ROI.
positive_ix = torch.nonzero(target_class_ids > 0)[:, 0]
positive_class_ids = target_class_ids[positive_ix.detach()].long()
indices = torch.stack((positive_ix, positive_class_ids), dim=1)
# Gather the masks (predicted and true) that contribute to loss
y_true = target_masks[:indices.size()[0], 1:, :, :]
y_pred = pred_masks[indices[:, 0].detach(), 1:, :, :, :]
# Implement the edge detection convolution
loss_fn = nn.MSELoss()
loss = torch.FloatTensor([0]).cuda()
for i in range(indices.size()[0]):
y_true_ = y_true[i]
y_pred_ = y_pred[i].unsqueeze(0) # [N, 7, 64, 64, 64]
for j in range(7):
y_true_final = F.conv3d(y_true_[j, :, :, :].unsqueeze(0).unsqueeze(0).cuda().float(), kernel)
y_pred_final = F.conv3d(y_pred_[:, j, :, :, :].unsqueeze(1), kernel)
y_true_final = torch.sqrt(torch.pow(y_true_final[:, 0], 2) + torch.pow(y_true_final[:, 1], 2) +
torch.pow(y_true_final[:, 0], 2))
y_pred_final = torch.sqrt(torch.pow(y_pred_final [:, 0], 2) + torch.pow(y_pred_final [:, 1], 2) +
torch.pow(y_pred_final [:, 0], 2))
# Mean Square Error
loss += loss_fn(y_pred_final, y_true_final)
loss /= indices.size()[0]
else:
loss = Variable(torch.FloatTensor([0]), requires_grad=False)
if target_class_ids.is_cuda:
loss = loss.cuda()
return loss
def compute_losses(rpn_match, rpn_bbox, rpn_class_logits, rpn_pred_bbox, target_class_ids, mrcnn_class_logits,
target_deltas, mrcnn_bbox, target_mask, mrcnn_mask, mrcnn_mask_logits, stage):
rpn_class_loss = compute_rpn_class_loss(rpn_match, rpn_class_logits)
rpn_bbox_loss = compute_rpn_bbox_loss(rpn_bbox, rpn_match, rpn_pred_bbox)
mrcnn_class_loss = compute_mrcnn_class_loss(torch.from_numpy(np.where(target_class_ids > 0, 1, 0)).cuda(),
mrcnn_class_logits)
mrcnn_bbox_loss = compute_mrcnn_bbox_loss(target_deltas,
torch.from_numpy(np.where(target_class_ids > 0, 1, 0)).cuda(), mrcnn_bbox)
mrcnn_mask_loss = compute_mrcnn_mask_loss(target_mask, target_class_ids, mrcnn_mask_logits)
if stage == 'finetune':
mrcnn_mask_edge_loss = compute_mrcnn_mask_edge_loss(target_mask, target_class_ids, mrcnn_mask)
else:
mrcnn_mask_edge_loss = Variable(torch.FloatTensor([0]), requires_grad=False).cuda()
return [rpn_class_loss, rpn_bbox_loss, mrcnn_class_loss, mrcnn_bbox_loss, mrcnn_mask_loss, mrcnn_mask_edge_loss]