forked from meder411/OmniDepth-PyTorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
criteria.py
89 lines (64 loc) · 2.04 KB
/
criteria.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
import torch
import torch.nn as nn
import torch.nn.functional as F
class SquaredGradientLoss(nn.Module):
'''Compute the gradient magnitude of an image using the simple filters as in:
Garg, Ravi, et al. "Unsupervised cnn for single view depth estimation: Geometry to the rescue." European Conference on Computer Vision. Springer, Cham, 2016.
'''
def __init__(self):
super(SquaredGradientLoss, self).__init__()
self.register_buffer('dx_filter', torch.FloatTensor([
[0,0,0],
[-0.5,0,0.5],
[0,0,0]]).view(1,1,3,3))
self.register_buffer('dy_filter', torch.FloatTensor([
[0,-0.5,0],
[0,0,0],
[0,0.5,0]]).view(1,1,3,3))
def forward(self, pred, mask):
dx = F.conv2d(
pred,
self.dx_filter.to(pred.get_device()),
padding=1,
groups=pred.shape[1])
dy = F.conv2d(
pred,
self.dy_filter.to(pred.get_device()),
padding=1,
groups=pred.shape[1])
error = mask * \
(dx.abs().sum(1, keepdim=True) + dy.abs().sum(1, keepdim=True))
return error.sum() / (mask > 0).sum().float()
class L2Loss(nn.Module):
def __init__(self):
super(L2Loss, self).__init__()
self.metric = nn.MSELoss()
def forward(self, pred, gt, mask):
error = mask * self.metric(pred, gt)
return error.sum() / (mask > 0).sum().float()
class MultiScaleL2Loss(nn.Module):
def __init__(self, alpha_list, beta_list):
super(MultiScaleL2Loss, self).__init__()
self.depth_metric = L2Loss()
self.grad_metric = SquaredGradientLoss()
self.alpha_list = alpha_list
self.beta_list = beta_list
def forward(self, pred_list, gt_list, mask_list):
# Go through each scale and accumulate errors
depth_error = 0
for i in range(len(pred_list)):
depth_pred = pred_list[i]
depth_gt = gt_list[i]
mask = mask_list[i]
alpha = self.alpha_list[i]
beta = self.beta_list[i]
# Compute depth error at this scale
depth_error += alpha * self.depth_metric(
depth_pred,
depth_gt,
mask)
# Compute gradient error at this scale
depth_error += beta * self.grad_metric(
depth_pred,
mask)
return depth_error