Li-zhangsheng commited on
Commit
a851d68
·
verified ·
1 Parent(s): 83ab733

Upload model code and weights

Browse files
Different networks compare(without CD-model)/CD-DCU-Net/CD-DCU-Net.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ from torchsummary import summary
5
+
6
+ class DoubleConv(nn.Module):
7
+ def __init__(self, in_channels, out_channels, mid_channels=None):
8
+ super().__init__()
9
+ if not mid_channels:
10
+ mid_channels = out_channels
11
+ self.double_conv = nn.Sequential(
12
+ nn.Conv2d(in_channels, mid_channels, kernel_size=3, padding=1, bias=False),
13
+ nn.BatchNorm2d(mid_channels),
14
+ nn.ReLU(inplace=True),
15
+
16
+ nn.Conv2d(mid_channels, out_channels, kernel_size=3, padding=1, bias=False),
17
+ nn.BatchNorm2d(out_channels),
18
+ nn.ReLU(inplace=True),
19
+
20
+
21
+
22
+ )
23
+
24
+ def forward(self, x):
25
+ return self.double_conv(x)
26
+
27
+ # Downsample with max pooling.
28
+ class Down(nn.Module):
29
+ def __init__(self, in_channels, out_channels):
30
+ super().__init__()
31
+ self.maxpool_conv = nn.Sequential(
32
+ nn.MaxPool2d(2),
33
+ DoubleConv(in_channels, out_channels, )
34
+ )
35
+
36
+ def forward(self, x):
37
+ return self.maxpool_conv(x)
38
+
39
+
40
+ class Up(nn.Module):
41
+ def __init__(self, in_channels, out_channels, bilinear=False):
42
+ super().__init__()
43
+ if bilinear:
44
+ self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
45
+ self.conv = DoubleConv(in_channels + in_channels // 2, out_channels)
46
+ else:
47
+ self.up = nn.ConvTranspose2d(in_channels, in_channels // 2, kernel_size=2, stride=2)
48
+ self.conv = DoubleConv(in_channels // 2 + out_channels, out_channels)
49
+
50
+ def forward(self, x1, x2):
51
+ x1 = self.up(x1)
52
+
53
+ diffY = x2.size()[2] - x1.size()[2]
54
+ diffX = x2.size()[3] - x1.size()[3]
55
+ x1 = F.pad(x1, [diffX // 2, diffX - diffX // 2,
56
+ diffY // 2, diffY - diffY // 2])
57
+ x = torch.cat([x2, x1], dim=1)
58
+ return self.conv(x)
59
+
60
+
61
+ class OutConv(nn.Module):
62
+ def __init__(self, in_channels, out_channels=2):
63
+ super(OutConv, self).__init__()
64
+ self.conv = nn.Sequential(
65
+
66
+ nn.Conv2d(in_channels, in_channels, kernel_size=3, padding=1, bias=False),
67
+ nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, bias=False),
68
+ )
69
+
70
+ def forward(self, x):
71
+ return self.conv(x)
72
+
73
+
74
+ class UNet(nn.Module):
75
+ def __init__(self, n_channels=3, bilinear=False):
76
+ super(UNet, self).__init__()
77
+ self.n_channels = n_channels
78
+ self.bilinear = bilinear
79
+
80
+ # Encoder.
81
+ self.inc = DoubleConv(n_channels, 64)
82
+ self.down1 = Down(64, 128)
83
+ self.down2 = Down(128, 256)
84
+ self.down3 = Down(256, 512)
85
+ self.down4 = Down(512, 1024)
86
+
87
+ # Decoder.
88
+ self.up1 = Up(1024, 512, bilinear)
89
+ self.up2 = Up(512, 256, bilinear)
90
+ self.up3 = Up(256, 128, bilinear)
91
+ self.up4 = Up(128, 64, bilinear)
92
+
93
+ self.outc = OutConv(64, 2)
94
+
95
+
96
+
97
+
98
+ def forward(self, x):
99
+ # Encoder path.
100
+ x1 = self.inc(x)
101
+ x2 = self.down1(x1)
102
+ x3 = self.down2(x2)
103
+ x4 = self.down3(x3)
104
+ x5 = self.down4(x4)
105
+
106
+ # Decoder path.
107
+ x = self.up1(x5, x4)
108
+ x = self.up2(x, x3)
109
+ x = self.up3(x, x2)
110
+ x = self.up4(x, x1)
111
+
112
+ # Predict the means.
113
+ outputs = self.outc(x)
114
+ M_mean = outputs[:, 0:1] # M mean.
115
+ D_mean = outputs[:, 1:2] # D mean.
116
+ return {'M_mean': M_mean, 'D_mean': D_mean}
117
+
118
+
119
+ if __name__ == "__main__":
120
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
121
+ model = UNet(3, bilinear=False).to(device)
122
+ print(summary(model, (3, 1360, 672)))
123
+
124
+ # Example input.
125
+ x = torch.randn(1, 3, 1360, 672).to(device)
126
+ output = model(x)
127
+ print("output M:", output['M_mean'].shape)
128
+ print("output D:", output['D_mean'].shape)
Different networks compare(without CD-model)/CD-DCU-Net/kaiming_initial.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:803c37a13a57ef13b65e7efba14a4887db157b3c741dcf81f2db7365b2b9f3ae
3
+ size 373054279
Different networks compare(without CD-model)/CD-DCU-Net/proposed_initial.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:999311c996fb89a3745d73b7d697186864c9fe726d659cbb0b7ce8cf29c6f3cb
3
+ size 373054087
Different networks compare(without CD-model)/DFPP-Net/DFPP-Net.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3ce31951b648bc87218991dc43705916680007e7c94baa616032512ea378ad84
3
+ size 4103675
Different networks compare(without CD-model)/DFPP-Net/DFPP-Net.py ADDED
@@ -0,0 +1,544 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+
5
+
6
+ # ============================================================
7
+ # Basic convolution block.
8
+ # ============================================================
9
+
10
+ def default_conv(in_channels, out_channels, kernel_size, bias=True):
11
+ return nn.Conv2d(
12
+ in_channels,
13
+ out_channels,
14
+ kernel_size,
15
+ padding=kernel_size // 2,
16
+ bias=bias
17
+ )
18
+
19
+
20
+ class BBlock(nn.Module):
21
+ def __init__(self, conv, in_channels, out_channels, kernel_size, act=nn.ReLU(True), bn=False):
22
+ super().__init__()
23
+ layers = [conv(in_channels, out_channels, kernel_size)]
24
+ if bn:
25
+ layers.append(nn.BatchNorm2d(out_channels))
26
+ if act is not None:
27
+ layers.append(act)
28
+ self.body = nn.Sequential(*layers)
29
+
30
+ def forward(self, x):
31
+ return self.body(x)
32
+
33
+
34
+ class ResBlock(nn.Module):
35
+ def __init__(self, conv, channels, kernel_size, act=nn.ReLU(True), bn=False):
36
+ super().__init__()
37
+ layers = [conv(channels, channels, kernel_size)]
38
+ if bn:
39
+ layers.append(nn.BatchNorm2d(channels))
40
+ layers.append(act)
41
+ layers.append(conv(channels, channels, kernel_size))
42
+ if bn:
43
+ layers.append(nn.BatchNorm2d(channels))
44
+ self.body = nn.Sequential(*layers)
45
+
46
+ def forward(self, x):
47
+ return x + self.body(x)
48
+
49
+
50
+ class DBlockCom(nn.Module):
51
+ def __init__(self, conv, in_channels, out_channels, kernel_size, act=nn.ReLU(True), bn=False):
52
+ super().__init__()
53
+ self.proj = None
54
+ if in_channels != out_channels:
55
+ self.proj = conv(in_channels, out_channels, 1)
56
+
57
+ layers = [conv(in_channels, out_channels, kernel_size)]
58
+ if bn:
59
+ layers.append(nn.BatchNorm2d(out_channels))
60
+ layers.append(act)
61
+ layers.append(conv(out_channels, out_channels, kernel_size))
62
+ if bn:
63
+ layers.append(nn.BatchNorm2d(out_channels))
64
+ self.body = nn.Sequential(*layers)
65
+
66
+ def forward(self, x):
67
+ res = self.proj(x) if self.proj is not None else x
68
+ return res + self.body(x)
69
+
70
+
71
+ # ============================================================
72
+ # Haar DWT / IWT
73
+ # Input height and width must be divisible by 2.
74
+ # An input of 1360 x 672 supports three consecutive downsampling stages.
75
+ # ============================================================
76
+
77
+ class DWT(nn.Module):
78
+ def forward(self, x):
79
+ B, C, H, W = x.shape
80
+ if H % 2 != 0 or W % 2 != 0:
81
+ raise RuntimeError(f"DWT requires even H and W, but got H={H}, W={W}")
82
+
83
+ x1 = x[:, :, 0::2, 0::2] / 2.0
84
+ x2 = x[:, :, 1::2, 0::2] / 2.0
85
+ x3 = x[:, :, 0::2, 1::2] / 2.0
86
+ x4 = x[:, :, 1::2, 1::2] / 2.0
87
+
88
+ ll = x1 + x2 + x3 + x4
89
+ hl = -x1 - x2 + x3 + x4
90
+ lh = -x1 + x2 - x3 + x4
91
+ hh = x1 - x2 - x3 + x4
92
+
93
+ return torch.cat([ll, hl, lh, hh], dim=1)
94
+
95
+
96
+ class IWT(nn.Module):
97
+ def forward(self, x):
98
+ B, C, H, W = x.shape
99
+ if C % 4 != 0:
100
+ raise RuntimeError(f"IWT requires channel divisible by 4, but got C={C}")
101
+
102
+ out_c = C // 4
103
+ x1 = x[:, 0:out_c, :, :] / 2.0
104
+ x2 = x[:, out_c:out_c * 2, :, :] / 2.0
105
+ x3 = x[:, out_c * 2:out_c * 3, :, :] / 2.0
106
+ x4 = x[:, out_c * 3:out_c * 4, :, :] / 2.0
107
+
108
+ out = torch.zeros(
109
+ B,
110
+ out_c,
111
+ H * 2,
112
+ W * 2,
113
+ device=x.device,
114
+ dtype=x.dtype
115
+ )
116
+
117
+ out[:, :, 0::2, 0::2] = x1 - x2 - x3 + x4
118
+ out[:, :, 1::2, 0::2] = x1 - x2 + x3 - x4
119
+ out[:, :, 0::2, 1::2] = x1 + x2 - x3 - x4
120
+ out[:, :, 1::2, 1::2] = x1 + x2 + x3 + x4
121
+
122
+ return out
123
+
124
+
125
+ # ============================================================
126
+ # Feature Align Module
127
+ # Prefer torchvision.ops.DeformConv2d.
128
+ # Fall back to a regular convolution when DeformConv2d is unavailable.
129
+ # ============================================================
130
+
131
+ try:
132
+ from torchvision.ops import DeformConv2d
133
+ HAS_DEFORM = True
134
+ except Exception:
135
+ DeformConv2d = None
136
+ HAS_DEFORM = False
137
+
138
+
139
+ class FeatureAlign(nn.Module):
140
+ """
141
+ Input: x [B, 2, C, H, W]
142
+ x[:,0] is the support-frame feature.
143
+ x[:,1] is the reference-frame feature.
144
+
145
+ Output: [B, 2, C, H, W]
146
+ The first frame is aligned to the second, which remains the reference.
147
+ """
148
+
149
+ def __init__(self, feats):
150
+ super().__init__()
151
+ self.feats = feats
152
+
153
+ self.offset_body = nn.Sequential(
154
+ nn.Conv2d(feats * 2, feats, 3, 1, 1),
155
+ nn.ReLU(inplace=True),
156
+ nn.Conv2d(feats, feats, 3, 1, 1),
157
+ nn.ReLU(inplace=True),
158
+ nn.Conv2d(feats, 18, 3, 1, 1)
159
+ )
160
+
161
+ if HAS_DEFORM:
162
+ self.dcn = DeformConv2d(feats, feats, kernel_size=3, padding=1)
163
+ else:
164
+ self.dcn = nn.Conv2d(feats, feats, kernel_size=3, padding=1)
165
+
166
+ self.refine = nn.Sequential(
167
+ nn.Conv2d(feats, feats, 3, 1, 1),
168
+ nn.ReLU(inplace=True),
169
+ nn.Conv2d(feats, feats, 3, 1, 1)
170
+ )
171
+
172
+ def forward(self, x):
173
+ B, T, C, H, W = x.shape
174
+ assert T == 2, f"FeatureAlign expects 2 frames, but got {T}"
175
+ assert C == self.feats, f"FeatureAlign channel mismatch: expected {self.feats}, got {C}"
176
+
177
+ support = x[:, 0, :, :, :]
178
+ ref = x[:, 1, :, :, :]
179
+
180
+ offset = self.offset_body(torch.cat([support, ref], dim=1))
181
+
182
+ if HAS_DEFORM:
183
+ aligned = self.dcn(support, offset)
184
+ else:
185
+ aligned = self.dcn(support)
186
+
187
+ aligned = aligned + self.refine(aligned)
188
+
189
+ out = torch.stack([aligned, ref], dim=1)
190
+ return out
191
+
192
+
193
+ # ============================================================
194
+ # MWCNN + Align
195
+ # Adapted version with no hard-coded 960, 480, or 240 dimensions.
196
+ # ============================================================
197
+
198
+ class MWCNNAlign(nn.Module):
199
+ def __init__(
200
+ self,
201
+ csff=False,
202
+ feats=32,
203
+ conv=default_conv,
204
+ stage0_align=True,
205
+ stage1_align=False,
206
+ stage2_align=False
207
+ ):
208
+ super().__init__()
209
+
210
+ self.feats = feats
211
+ self.stage0_align = stage0_align
212
+ self.stage1_align = stage1_align
213
+ self.stage2_align = stage2_align
214
+
215
+ n_feats = feats
216
+ kernel_size = 3
217
+ nColor = 1
218
+ act = nn.ReLU(True)
219
+
220
+ self.DWT = DWT()
221
+ self.IWT = IWT()
222
+
223
+ self.head = nn.Sequential(
224
+ BBlock(conv, nColor, n_feats, kernel_size, act=act)
225
+ )
226
+
227
+ self.d_l0 = nn.Sequential(
228
+ DBlockCom(conv, n_feats, n_feats, kernel_size, act=act, bn=False)
229
+ )
230
+
231
+ self.d_l1 = nn.Sequential(
232
+ BBlock(conv, n_feats * 4, n_feats * 2, kernel_size, act=act, bn=False),
233
+ DBlockCom(conv, n_feats * 2, n_feats * 2, kernel_size, act=act, bn=False)
234
+ )
235
+
236
+ self.d_l2 = nn.Sequential(
237
+ BBlock(conv, n_feats * 8, n_feats * 4, kernel_size, act=act, bn=False),
238
+ DBlockCom(conv, n_feats * 4, n_feats * 4, kernel_size, act=act, bn=False)
239
+ )
240
+
241
+ self.pro_l3 = nn.Sequential(
242
+ BBlock(conv, n_feats * 16, n_feats * 8, kernel_size, act=act, bn=False),
243
+ DBlockCom(conv, n_feats * 8, n_feats * 8, kernel_size, act=act, bn=False),
244
+ DBlockCom(conv, n_feats * 8, n_feats * 8, kernel_size, act=act, bn=False),
245
+ BBlock(conv, n_feats * 8, n_feats * 16, kernel_size, act=act, bn=False)
246
+ )
247
+
248
+ self.i_l2 = nn.Sequential(
249
+ DBlockCom(conv, n_feats * 4, n_feats * 4, kernel_size, act=act, bn=False),
250
+ BBlock(conv, n_feats * 4, n_feats * 8, kernel_size, act=act, bn=False)
251
+ )
252
+
253
+ self.i_l1 = nn.Sequential(
254
+ DBlockCom(conv, n_feats * 2, n_feats * 2, kernel_size, act=act, bn=False),
255
+ BBlock(conv, n_feats * 2, n_feats * 4, kernel_size, act=act, bn=False)
256
+ )
257
+
258
+ self.i_l0 = nn.Sequential(
259
+ DBlockCom(conv, n_feats, n_feats, kernel_size, act=act, bn=False)
260
+ )
261
+
262
+ self.tail = nn.Sequential(
263
+ conv(n_feats, nColor, kernel_size)
264
+ )
265
+
266
+ self.aligned0 = FeatureAlign(feats=n_feats)
267
+ self.aligned1 = FeatureAlign(feats=n_feats * 2)
268
+ self.aligned2 = FeatureAlign(feats=n_feats * 4)
269
+
270
+ self.concat = conv(n_feats * 2, n_feats, kernel_size)
271
+
272
+ self.csff = csff
273
+ if csff:
274
+ self.csff_enc0 = nn.Conv2d(n_feats, n_feats, kernel_size=1, bias=False)
275
+ self.csff_enc1 = nn.Conv2d(n_feats * 2, n_feats * 2, kernel_size=1, bias=False)
276
+ self.csff_enc2 = nn.Conv2d(n_feats * 4, n_feats * 4, kernel_size=1, bias=False)
277
+
278
+ def forward(self, x, SAM_feature=None, stage_out=None):
279
+ """
280
+ x: [B*2, 1, H, W]
281
+ """
282
+ BandNum, _, h, w = x.shape
283
+ assert BandNum % 2 == 0, "MWCNNAlign expects input batch to be B*2"
284
+
285
+ x_shallow = self.head(x)
286
+
287
+ if SAM_feature is not None:
288
+ SAM_feature1 = SAM_feature.reshape(-1, self.feats, h, w)
289
+ x_shallow = torch.cat([x_shallow, SAM_feature1], dim=1)
290
+ x_shallow = self.concat(x_shallow)
291
+
292
+ x0 = self.d_l0(x_shallow)
293
+
294
+ if self.stage0_align:
295
+ _, c0, h0, w0 = x0.shape
296
+ x0_aligned = self.aligned0(x0.reshape(BandNum // 2, 2, c0, h0, w0))
297
+ x0 = x0_aligned.reshape(BandNum, c0, h0, w0)
298
+
299
+ if stage_out is not None:
300
+ x0 = x0 + stage_out[0] + stage_out[5]
301
+
302
+ x1 = self.d_l1(self.DWT(x0))
303
+
304
+ if self.stage1_align:
305
+ _, c1, h1, w1 = x1.shape
306
+ x1_aligned = self.aligned1(x1.reshape(BandNum // 2, 2, c1, h1, w1))
307
+ x1 = x1_aligned.reshape(BandNum, c1, h1, w1)
308
+
309
+ if stage_out is not None:
310
+ x1 = x1 + stage_out[1] + stage_out[4]
311
+
312
+ x2 = self.d_l2(self.DWT(x1))
313
+
314
+ if self.stage2_align:
315
+ _, c2, h2, w2 = x2.shape
316
+ x2_aligned = self.aligned2(x2.reshape(BandNum // 2, 2, c2, h2, w2))
317
+ x2 = x2_aligned.reshape(BandNum, c2, h2, w2)
318
+
319
+ if stage_out is not None:
320
+ x2 = x2 + stage_out[2] + stage_out[3]
321
+
322
+ x_2 = self.IWT(self.pro_l3(self.DWT(x2))) + x2
323
+ x_1 = self.IWT(self.i_l2(x_2)) + x1
324
+ x_0 = self.IWT(self.i_l1(x_1)) + x0
325
+
326
+ x_img = self.tail(self.i_l0(x_0)) + x
327
+
328
+ return [x0, x1, x2, x_2, x_1, x_0, x_img]
329
+
330
+
331
+ # ============================================================
332
+ # SAM
333
+ # ============================================================
334
+
335
+ class SAM(nn.Module):
336
+ def __init__(self, n_feat, kernel_size=1, bias=False):
337
+ super().__init__()
338
+ self.conv1 = default_conv(n_feat, n_feat, kernel_size, bias=bias)
339
+ self.conv2 = default_conv(n_feat, 2, kernel_size, bias=bias)
340
+ self.conv3 = default_conv(2, n_feat, kernel_size, bias=bias)
341
+
342
+ def forward(self, x, x_img):
343
+ x1 = self.conv1(x)
344
+ img = self.conv2(x) + x_img
345
+ x2 = torch.sigmoid(self.conv3(img))
346
+ x1 = x1 * x2
347
+ x1 = x1 + x
348
+ return x1, img
349
+
350
+
351
+ # ============================================================
352
+ # Final model: three input frames with M and D outputs.
353
+ # ============================================================
354
+
355
+ class DFPPNet3FrameMD(nn.Module):
356
+ """
357
+ Input:
358
+ x: [B, 3, H, W]
359
+
360
+ Output:
361
+ {
362
+ 'M_mean': [B, 1, H, W],
363
+ 'D_mean': [B, 1, H, W]
364
+ }
365
+
366
+ Interface used by the training code:
367
+ outputs = model(inputs)
368
+ BNNLoss(outputs, labels, mask)
369
+ """
370
+
371
+ def __init__(
372
+ self,
373
+ n_feat=32,
374
+ out_c=2,
375
+ stage0_align=True,
376
+ stage1_align=False,
377
+ stage2_align=False,
378
+ return_aux=False
379
+ ):
380
+ super().__init__()
381
+
382
+ self.n_feat = n_feat
383
+ self.return_aux = return_aux
384
+
385
+ self.MWCNN1 = MWCNNAlign(
386
+ csff=False,
387
+ feats=n_feat,
388
+ stage0_align=stage0_align,
389
+ stage1_align=stage1_align,
390
+ stage2_align=stage2_align
391
+ )
392
+
393
+ self.MWCNN2 = MWCNNAlign(
394
+ csff=True,
395
+ feats=n_feat,
396
+ stage0_align=stage0_align,
397
+ stage1_align=stage1_align,
398
+ stage2_align=stage2_align
399
+ )
400
+
401
+ self.MWCNN3 = MWCNNAlign(
402
+ csff=True,
403
+ feats=n_feat,
404
+ stage0_align=stage0_align,
405
+ stage1_align=stage1_align,
406
+ stage2_align=stage2_align
407
+ )
408
+
409
+ self.sam12 = SAM(n_feat * 2, kernel_size=1, bias=False)
410
+ self.sam23 = SAM(n_feat * 2, kernel_size=1, bias=False)
411
+
412
+ self.pred1 = nn.Sequential(
413
+ default_conv(n_feat * 2, n_feat, 3, bias=True),
414
+ nn.ReLU(inplace=True),
415
+ default_conv(n_feat, out_c, 3, bias=True)
416
+ )
417
+
418
+ self.pred2 = nn.Sequential(
419
+ default_conv(n_feat * 2, n_feat, 3, bias=True),
420
+ nn.ReLU(inplace=True),
421
+ default_conv(n_feat, out_c, 3, bias=True)
422
+ )
423
+
424
+ self.pred3 = nn.Sequential(
425
+ default_conv(n_feat * 2, n_feat, 3, bias=True),
426
+ nn.ReLU(inplace=True),
427
+ default_conv(n_feat, out_c, 3, bias=True)
428
+ )
429
+
430
+ @staticmethod
431
+ def flatten_pair(pair):
432
+ """
433
+ pair: [B, 2, H, W]
434
+ return: [B*2, 1, H, W]
435
+ """
436
+ B, C, H, W = pair.shape
437
+ assert C == 2, f"pair should have 2 channels, got {C}"
438
+ return pair.unsqueeze(2).reshape(B * C, 1, H, W)
439
+
440
+ @staticmethod
441
+ def split_md(pred):
442
+ M_mean = pred[:, 0:1, :, :]
443
+ D_mean = pred[:, 1:2, :, :]
444
+ return M_mean, D_mean
445
+
446
+ def forward(self, x):
447
+ """
448
+ x: [B, 3, H, W]
449
+ Process three dynamic fringe-pattern input frames.
450
+ The ground truth is assumed to correspond to the first frame, so f1 is the reference.
451
+ """
452
+ B, C, H, W = x.shape
453
+ assert C == 3, f"DFPPNet3FrameMD expects 3 input frames, got {C}"
454
+
455
+ # Three consecutive DWT stages require H and W to be divisible by 8.
456
+ if H % 8 != 0 or W % 8 != 0:
457
+ raise RuntimeError(
458
+ f"Input H and W should be divisible by 8 for this MWCNN structure, "
459
+ f"but got H={H}, W={W}"
460
+ )
461
+
462
+ f1 = x[:, 0:1, :, :] # First frame, used as the reference.
463
+ f2 = x[:, 1:2, :, :]
464
+ f3 = x[:, 2:3, :, :]
465
+
466
+ # Three branches:
467
+ # Branch 1: f1 with f1.
468
+ # Branch 2: align f2 to f1.
469
+ # Branch 3: align f3 to f1.
470
+ pair11 = torch.cat([f1, f1], dim=1)
471
+ pair21 = torch.cat([f2, f1], dim=1)
472
+ pair31 = torch.cat([f3, f1], dim=1)
473
+
474
+ # ---------------------------
475
+ # Stage 1
476
+ # ---------------------------
477
+ x1_img = self.flatten_pair(pair11)
478
+ stage1_feature = self.MWCNN1(x1_img)
479
+
480
+ feat1 = stage1_feature[5].reshape(B, -1, H, W)
481
+ sam_feat1, _ = self.sam12(feat1, pair11)
482
+ pred1 = self.pred1(feat1)
483
+
484
+ # ---------------------------
485
+ # Stage 2
486
+ # ---------------------------
487
+ x2_img = self.flatten_pair(pair21)
488
+ stage2_feature = self.MWCNN2(
489
+ x2_img,
490
+ SAM_feature=sam_feat1,
491
+ stage_out=stage1_feature
492
+ )
493
+
494
+ feat2 = stage2_feature[5].reshape(B, -1, H, W)
495
+ sam_feat2, _ = self.sam23(feat2, pair21)
496
+ pred2 = self.pred2(feat2)
497
+
498
+ # ---------------------------
499
+ # Stage 3
500
+ # ---------------------------
501
+ x3_img = self.flatten_pair(pair31)
502
+ stage3_feature = self.MWCNN3(
503
+ x3_img,
504
+ SAM_feature=sam_feat2,
505
+ stage_out=stage2_feature
506
+ )
507
+
508
+ feat3 = stage3_feature[5].reshape(B, -1, H, W)
509
+ pred3 = self.pred3(feat3)
510
+
511
+ M_mean, D_mean = self.split_md(pred3)
512
+
513
+ outputs = {
514
+ "M_mean": M_mean,
515
+ "D_mean": D_mean
516
+ }
517
+
518
+ if self.return_aux:
519
+ outputs["aux"] = [pred1, pred2, pred3]
520
+
521
+ return outputs
522
+
523
+
524
+ # ============================================================
525
+ # Basic test.
526
+ # ============================================================
527
+
528
+ if __name__ == "__main__":
529
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
530
+
531
+ model = DFPPNet3FrameMD(
532
+ n_feat=16,
533
+ stage0_align=True,
534
+ stage1_align=False,
535
+ stage2_align=False
536
+ ).to(device)
537
+
538
+ x = torch.randn(1, 3, 1360, 672).to(device)
539
+
540
+ with torch.no_grad():
541
+ y = model(x)
542
+
543
+ print("M_mean:", y["M_mean"].shape)
544
+ print("D_mean:", y["D_mean"].shape)
Different networks compare(without CD-model)/DR-U-Net/DR-U-Net.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:16c5f909e66cb74b208e110c9cf48da2ec2bf6074bce6b8803f6057e995229d1
3
+ size 217441994
Different networks compare(without CD-model)/DR-U-Net/DR-U-Net.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ from torchsummary import summary
5
+
6
+ class SimplifiedResidualBlock(nn.Module):
7
+ """
8
+ Simplified residual block with a 3x3 convolution, batch normalization,
9
+ ReLU, and a skip connection. The activate_last option controls the final
10
+ activation function.
11
+ Conv -> BN -> ReLU -> Add Skip -> (Optional) ReLU
12
+ """
13
+ def __init__(self, in_channels, out_channels, stride=1, activate_last=True):
14
+ super(SimplifiedResidualBlock, self).__init__()
15
+ self.activate_last = activate_last # Control whether to apply the final activation.
16
+
17
+ # Main convolution layer.
18
+ self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False)
19
+ self.bn = nn.BatchNorm2d(out_channels)
20
+ self.relu1 = nn.ReLU(inplace=False) # Keep the operation out of place.
21
+
22
+ # The skip connection must handle channel and spatial-size mismatches.
23
+ self.shortcut = nn.Sequential() # Identity mapping by default.
24
+ if stride != 1 or in_channels != out_channels:
25
+ # Use a 1x1 convolution when the dimensions do not match.
26
+ self.shortcut = nn.Sequential(
27
+ nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, bias=False),
28
+ nn.BatchNorm2d(out_channels)
29
+ )
30
+
31
+ self.relu2 = nn.ReLU(inplace=False) # Keep the operation out of place.
32
+
33
+
34
+ def forward(self, x):
35
+ identity = self.shortcut(x) # Match dimensions for the skip connection.
36
+
37
+ out = self.conv(x)
38
+ out = self.bn(out)
39
+ out = self.relu1(out) # Apply activation after the main-path convolution.
40
+
41
+ out = out + identity # Add the residual out of place.
42
+
43
+ if self.activate_last:
44
+ out = self.relu2(out)
45
+
46
+ return out
47
+
48
+ # Down uses two SimplifiedResidualBlock modules and returns the pre-pooling features.
49
+ class Down(nn.Module):
50
+ def __init__(self, in_channels, out_channels):
51
+ super().__init__()
52
+ # Downsample with MaxPool2d first.
53
+ self.maxpool = nn.MaxPool2d(2)
54
+ # Follow with two SimplifiedResidualBlock modules, both with final activation.
55
+ # The first block changes in_channels to out_channels.
56
+ self.residual_block1 = SimplifiedResidualBlock(in_channels, out_channels, activate_last=True)
57
+ # The second block keeps out_channels unchanged.
58
+ self.residual_block2 = SimplifiedResidualBlock(out_channels, out_channels, activate_last=True)
59
+
60
+ def forward(self, x):
61
+ x_before_pool = x # Pre-pooling features used by the skip connection.
62
+ x = self.maxpool(x)
63
+ x = self.residual_block1(x)
64
+ x = self.residual_block2(x) # Pass through the second residual block.
65
+ return x, x_before_pool # Return post-pooling and pre-pooling outputs.
66
+
67
+ # Up uses ConvTranspose2d for upsampling and computes output padding.
68
+ class Up(nn.Module):
69
+ def __init__(self, up_input_channels, skip_channels, output_channels, bilinear=False):
70
+ super().__init__()
71
+ self.bilinear = bilinear
72
+ if bilinear:
73
+ self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
74
+ self.conv = SimplifiedResidualBlock(up_input_channels + skip_channels, output_channels, activate_last=True)
75
+ else:
76
+ # Instantiate ConvTranspose2d when transposed convolution is selected.
77
+ # Do not set output_padding here; spatial matching is handled in forward.
78
+ self.up = nn.ConvTranspose2d(up_input_channels, up_input_channels // 2, kernel_size=2, stride=2)
79
+ # self.conv concatenates the size-adjusted x1 and x2 tensors.
80
+ self.conv = SimplifiedResidualBlock(up_input_channels // 2 + skip_channels, output_channels, activate_last=True)
81
+
82
+
83
+ def forward(self, x1, x2): # x1 is input from lower layer, x2 is skip connection (target size)
84
+
85
+ if self.bilinear:
86
+ x1 = self.up(x1)
87
+ else:
88
+ # Use ConvTranspose2d for upsampling
89
+ x1 = self.up(x1)
90
+
91
+ # Resize the ConvTranspose2d output to match x2.
92
+ # F.interpolate adjusts x1 to the spatial dimensions of x2.
93
+ # Nearest-neighbor interpolation is used here; bilinear is another option.
94
+ if x1.size()[2:] != x2.size()[2:]:
95
+ # print(f"Debug: Resizing x1 from {x1.size()} to {x2.size()}")
96
+ x1 = F.interpolate(x1, size=x2.size()[2:], mode='nearest')
97
+
98
+
99
+ # Now x1 should have the same spatial size as x2
100
+ # A check can still be useful as a safeguard, but padding/cropping should ideally not be needed.
101
+ # Cropping is unnecessary because F.interpolate already matches the sizes.
102
+ # diffY = x2.size()[2] - x1.size()[2]
103
+ # diffX = x2.size()[3] - x1.size()[3]
104
+ # if diffY != 0 or diffX != 0:
105
+ # print(f"Warning: Size mismatch after ConvTranspose2d + Interpolate in Up. DiffX: {diffX}, DiffY: {diffY}. Check logic.")
106
+ # # Fallback cropping (should ideally not be necessary with interpolate)
107
+ # x1 = x1[:, :, :x2.size(2), :x2.size(3)]
108
+
109
+
110
+ # Concatenate x2 and x1
111
+ x = torch.cat([x2, x1], dim=1)
112
+
113
+ # Pass through the residual block
114
+ x = self.conv(x)
115
+ return x
116
+
117
+ # Output convolution block.
118
+ class OutConv(nn.Module):
119
+ """
120
+ Final module containing one SimplifiedResidualBlock. It changes the channel
121
+ count from in_channels to out_channels without a final activation.
122
+ """
123
+ # Use two output channels by default.
124
+ def __init__(self, in_channels, out_channels=2):
125
+ super(OutConv, self).__init__()
126
+ # The final SimplifiedResidualBlock maps in_channels to out_channels.
127
+ # Disable its final activation.
128
+ self.residual_block = SimplifiedResidualBlock(in_channels, out_channels, activate_last=False)
129
+
130
+ def forward(self, x):
131
+ # Pass directly through the SimplifiedResidualBlock.
132
+ return self.residual_block(x)
133
+
134
+ # UNet with adjusted skip-channel counts in the Up blocks.
135
+ class UNet(nn.Module):
136
+ # Use two output channels by default.
137
+ def __init__(self, n_channels=3, out_channels=2, bilinear=False):
138
+ super(UNet, self).__init__()
139
+ self.n_channels = n_channels
140
+ self.out_channels = out_channels
141
+ self.bilinear = bilinear
142
+
143
+ # Encoder with three downsampling stages; each Down block uses max pooling and two residual blocks.
144
+ # The input layer is a SimplifiedResidualBlock with final activation.
145
+ self.inc = SimplifiedResidualBlock(n_channels, 64, activate_last=True)
146
+ # down1 returns both post-pooling and pre-pooling outputs.
147
+ self.down1 = Down(64, 128)
148
+ # down2 returns both post-pooling and pre-pooling outputs.
149
+ self.down2 = Down(128, 256)
150
+ # down3 returns both post-pooling and pre-pooling outputs.
151
+ self.down3 = Down(256, 512)
152
+
153
+ # Bottleneck: one SimplifiedResidualBlock with final activation.
154
+ # Its input is the post-pooling output of down3.
155
+ self.bottleneck = SimplifiedResidualBlock(512, 1024, activate_last=True)
156
+
157
+ # Decoder: each Up block upsamples, concatenates a skip connection, and applies a residual block.
158
+ # up1: bottleneck input 1024, pre-pooling down3 skip 256, output 512.
159
+ # The up1 skip connection is the 256-channel pre-pooling output of down3.
160
+ self.up1 = Up(1024, 256, 512, bilinear) # skip_channels is the actual skip width.
161
+ # up2: up1 input 512, pre-pooling down2 skip 128, output 256.
162
+ self.up2 = Up(512, 128, 256, bilinear) # skip_channels is the actual skip width.
163
+ # up3: up2 input 256, pre-pooling down1 skip 64, output 128.
164
+ self.up3 = Up(256, 64, 128, bilinear) # skip_channels is the actual skip width.
165
+ # up4: up3 input 128, inc skip 64, output 64.
166
+ self.up4 = Up(128, 64, 64, bilinear) # skip_channels is the actual skip width.
167
+
168
+ # OutConv uses one SimplifiedResidualBlock to map 64 channels to
169
+ # out_channels (two by default) without final activation.
170
+ self.outc = OutConv(64, out_channels)
171
+
172
+
173
+ def forward(self, x):
174
+ # Encoder path.
175
+ x1 = self.inc(x) # Input layer: 64 output channels for the up4 skip.
176
+ # Down blocks return post-pooling and pre-pooling outputs.
177
+ x2_out, x2_skip = self.down1(x1) # First stage: 64-channel x2_skip feeds up3.
178
+ x3_out, x3_skip = self.down2(x2_out) # Second stage: 128-channel x3_skip feeds up2.
179
+ x4_out, x4_skip = self.down3(x3_out) # Third stage: 256-channel x4_skip feeds up1.
180
+
181
+ # The bottleneck input is the 512-channel post-pooling output x4_out from down3.
182
+ x5 = self.bottleneck(x4_out) # Bottleneck output has 1024 channels.
183
+
184
+ # Decoder path.
185
+ # up1 takes 1024-channel x5 and the 256-channel pre-pooling x4_skip from down3.
186
+ x = self.up1(x5, x4_skip) # up1 outputs 512 channels.
187
+ # up2 takes the 512-channel up1 output and the 128-channel x3_skip from down2.
188
+ x = self.up2(x, x3_skip) # up2 outputs 256 channels.
189
+ # up3 takes the 256-channel up2 output and the 64-channel x2_skip from down1.
190
+ x = self.up3(x, x2_skip) # up3 outputs 128 channels.
191
+ # up4 takes the 128-channel up3 output and the 64-channel x1 output from inc.
192
+ x = self.up4(x, x1) # up4 outputs 64 channels.
193
+
194
+ # Produce a two-channel output.
195
+ outputs = self.outc(x) # OutConv maps 64 input channels to 2 outputs.
196
+
197
+ # The output-channel order is assumed to be M_mean, D_mean.
198
+ M_mean = outputs[:, 0:1]
199
+ D_mean = outputs[:, 1:2]
200
+
201
+ # Return only the means.
202
+ return {'M_mean': M_mean, 'D_mean': D_mean}
203
+
204
+
205
+ if __name__ == "__main__":
206
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
207
+ # The diagram uses 512x1024, but the training input size is 272x256.
208
+ # Use 272x256 to match training.
209
+ input_height, input_width = 272, 256
210
+ # Use two output channels for M and D.
211
+ model = UNet(n_channels=3, out_channels=2, bilinear=False).to(device)
212
+
213
+ # Print the model structure and parameter count.
214
+ # The input dimensions must match the actual data.
215
+ print(summary(model, (3, input_height, input_width)))
216
+
217
+ # Example input.
218
+ x = torch.randn(1, 3, input_height, input_width).to(device)
219
+ output = model(x)
220
+ print("output M:", output['M_mean'].shape)
221
+ print("output D:", output['D_mean'].shape)
Different networks compare(without CD-model)/ISP-Net/ISP-Net.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5fd73219250b040e49d07ae2e33ae5f6c038a9be5ffbdf9c531d08183ead0083
3
+ size 604724983
Different networks compare(without CD-model)/ISP-Net/ISP-Net.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ from torchsummary import summary
5
+
6
+ class ResidualBlock(nn.Module):
7
+ """
8
+ Dashed CNN1 residual block from Figure 5 of the paper.
9
+ Input -> Conv 1x1 -> BN -> ReLU -> Conv 3x3 -> BN -> ReLU -> Conv 1x1 -> BN -> add residual -> ReLU
10
+ """
11
+ def __init__(self, channels):
12
+ super().__init__()
13
+ self.conv_block = nn.Sequential(
14
+ nn.Conv2d(channels, channels, kernel_size=1, bias=False),
15
+ nn.BatchNorm2d(channels),
16
+ nn.ReLU(inplace=True),
17
+
18
+ nn.Conv2d(channels, channels, kernel_size=3, padding=1, bias=False),
19
+ nn.BatchNorm2d(channels),
20
+ nn.ReLU(inplace=True),
21
+
22
+ nn.Conv2d(channels, channels, kernel_size=1, bias=False),
23
+ nn.BatchNorm2d(channels)
24
+ )
25
+ self.relu = nn.ReLU(inplace=True)
26
+
27
+ def forward(self, x):
28
+ residual = x
29
+ out = self.conv_block(x)
30
+ out += residual
31
+ out = self.relu(out)
32
+ return out
33
+
34
+
35
+ class CNN1Block(nn.Module):
36
+ """
37
+ Green CNN1 feature-extraction block from Figure 5 of the paper.
38
+ Conv 3x3 (with BN and ReLU) -> one residual block -> Conv 3x3 (with BN and ReLU)
39
+ """
40
+ def __init__(self, in_channels, out_channels):
41
+ super().__init__()
42
+ self.block = nn.Sequential(
43
+ nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, bias=False),
44
+ nn.BatchNorm2d(out_channels),
45
+ nn.ReLU(inplace=True),
46
+
47
+ ResidualBlock(out_channels),
48
+
49
+ nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1, bias=False),
50
+ nn.BatchNorm2d(out_channels),
51
+ nn.ReLU(inplace=True)
52
+ )
53
+
54
+ def forward(self, x):
55
+ return self.block(x)
56
+
57
+
58
+ class Down(nn.Module):
59
+ """
60
+ Standard max-pooling downsampling module from the paper: MaxPool2d plus a feature block.
61
+ Used to compare against the stride-convolution downsampling network.
62
+ """
63
+ def __init__(self, in_channels, out_channels):
64
+ super().__init__()
65
+ self.maxpool_conv = nn.Sequential(
66
+ nn.MaxPool2d(2),
67
+ CNN1Block(in_channels, out_channels)
68
+ )
69
+
70
+ def forward(self, x):
71
+ return self.maxpool_conv(x)
72
+
73
+
74
+ class Up(nn.Module):
75
+ """
76
+ Decoder upsampling module: bilinear interpolation or transposed convolution,
77
+ skip-connection concatenation, and a feature-extraction block.
78
+ """
79
+ def __init__(self, in_channels, out_channels, bilinear=False):
80
+ super().__init__()
81
+ if bilinear:
82
+ self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
83
+ self.conv = CNN1Block(in_channels + out_channels, out_channels)
84
+ else:
85
+ self.up = nn.ConvTranspose2d(in_channels, out_channels, kernel_size=2, stride=2)
86
+ self.conv = CNN1Block(out_channels * 2, out_channels)
87
+
88
+ def forward(self, x1, x2):
89
+ x1 = self.up(x1)
90
+
91
+ diffY = x2.size()[2] - x1.size()[2]
92
+ diffX = x2.size()[3] - x1.size()[3]
93
+ x1 = F.pad(x1, [diffX // 2, diffX - diffX // 2,
94
+ diffY // 2, diffY - diffY // 2])
95
+
96
+ x = torch.cat([x2, x1], dim=1)
97
+ return self.conv(x)
98
+
99
+
100
+ class OutConv(nn.Module):
101
+ """
102
+ Output mapping: the paper uses a final 1x1 convolution to reduce 8 channels
103
+ to 2, corresponding to M_sp and D_sp.
104
+ """
105
+ def __init__(self, in_channels, out_channels=2):
106
+ super(OutConv, self).__init__()
107
+ self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1)
108
+
109
+ def forward(self, x):
110
+ return self.conv(x)
111
+
112
+
113
+ class UNet(nn.Module):
114
+ def __init__(self, n_channels=3, bilinear=False):
115
+ """
116
+ Based on Section 2.4 of the paper, CNN1 contains a complete seven-level
117
+ encoder and seven-level decoder. Channel widths match Figure 5:
118
+ 8 -> 16 -> 32 -> 64 -> 128 -> 256 -> 512.
119
+ """
120
+ super(UNet, self).__init__()
121
+ self.n_channels = n_channels
122
+ self.bilinear = bilinear
123
+
124
+ # Encoder path with seven levels.
125
+ self.inc = CNN1Block(n_channels, 16)
126
+ self.down1 = Down(16, 32)
127
+ self.down2 = Down(32, 64)
128
+ self.down3 = Down(64, 128)
129
+ self.down4 = Down(128, 256)
130
+ self.down5 = Down(256, 512)
131
+ self.down6 = Down(512, 1024)
132
+
133
+ # Symmetric decoder path.
134
+ self.up1 = Up(1024, 512, bilinear)
135
+ self.up2 = Up(512, 256, bilinear)
136
+ self.up3 = Up(256, 128, bilinear)
137
+ self.up4 = Up(128, 64, bilinear)
138
+ self.up5 = Up(64, 32, bilinear)
139
+ self.up6 = Up(32, 16, bilinear)
140
+
141
+ # Final two channels: numerator M_sp and denominator D_sp.
142
+ self.outc = OutConv(16, 2)
143
+
144
+ def forward(self, x):
145
+ # Encoder forward pass.
146
+ x1 = self.inc(x)
147
+ x2 = self.down1(x1)
148
+ x3 = self.down2(x2)
149
+ x4 = self.down3(x3)
150
+ x5 = self.down4(x4)
151
+ x6 = self.down5(x5)
152
+ x7 = self.down6(x6)
153
+
154
+ # Decoder forward pass with skip connections.
155
+ x = self.up1(x7, x6)
156
+ x = self.up2(x, x5)
157
+ x = self.up3(x, x4)
158
+ x = self.up4(x, x3)
159
+ x = self.up5(x, x2)
160
+ x = self.up6(x, x1)
161
+
162
+ # Split the output matrix to match the network interface.
163
+ outputs = self.outc(x)
164
+ M_mean = outputs[:, 0:1] # Predict the wrapped-phase numerator.
165
+ D_mean = outputs[:, 1:2] # Predict the wrapped-phase denominator.
166
+
167
+ return {'M_mean': M_mean, 'D_mean': D_mean}
168
+
169
+
170
+ if __name__ == "__main__":
171
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
172
+ # Build the model.
173
+ model = UNet(n_channels=3, bilinear=False).to(device)
174
+
175
+ # Print the parameter and architecture summary.
176
+ print(summary(model, (3, 800, 800)))
177
+
178
+ # Validate a forward pass with sample input.
179
+ x = torch.randn(1, 3, 800, 800).to(device)
180
+ output = model(x)
181
+ print("output M_mean size:", output['M_mean'].shape)
182
+ print("output D_mean size:", output['D_mean'].shape)
Different networks compare(without CD-model)/TS-U-Net/TS-U-Net.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ddf815814e8908686af0d9e91899a717a34cc3719f32139414550a518a91adc4
3
+ size 372613235
Different networks compare(without CD-model)/TS-U-Net/TS-U-Net.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ from torchsummary import summary
5
+ # Import the math module.
6
+ import math
7
+
8
+
9
+ class DoubleConv(nn.Module):
10
+ def __init__(self, in_channels, out_channels, mid_channels=None):
11
+ super().__init__()
12
+ if not mid_channels:
13
+ mid_channels = out_channels
14
+ self.double_conv = nn.Sequential(
15
+ nn.Conv2d(in_channels, mid_channels, kernel_size=3, padding=1, bias=False),
16
+ nn.BatchNorm2d(mid_channels),
17
+ nn.ReLU(inplace=True),
18
+
19
+ nn.Conv2d(mid_channels, out_channels, kernel_size=3, padding=1, bias=False),
20
+ nn.BatchNorm2d(out_channels),
21
+ nn.ReLU(inplace=True),
22
+
23
+ )
24
+
25
+ def forward(self, x):
26
+ return self.double_conv(x)
27
+
28
+
29
+ class Down(nn.Module):
30
+ def __init__(self, in_channels, out_channels):
31
+ super().__init__()
32
+ self.maxpool_conv = nn.Sequential(
33
+ nn.MaxPool2d(2),
34
+ DoubleConv(in_channels, out_channels,)
35
+ )
36
+
37
+ def forward(self, x):
38
+ return self.maxpool_conv(x)
39
+
40
+
41
+ class Up(nn.Module):
42
+ def __init__(self, in_channels, out_channels, bilinear=False):
43
+ super().__init__()
44
+ if bilinear:
45
+ self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
46
+ self.conv = DoubleConv(in_channels + in_channels // 2, out_channels)
47
+ else:
48
+ self.up = nn.ConvTranspose2d(in_channels, in_channels // 2, kernel_size=2, stride=2)
49
+ self.conv = DoubleConv(in_channels // 2 + out_channels, out_channels)
50
+
51
+ def forward(self, x1, x2):
52
+ x1 = self.up(x1)
53
+
54
+ diffY = x2.size()[2] - x1.size()[2]
55
+ diffX = x2.size()[3] - x1.size()[3]
56
+ x1 = F.pad(x1, [diffX // 2, diffX - diffX // 2,
57
+ diffY // 2, diffY - diffY // 2])
58
+ x = torch.cat([x2, x1], dim=1)
59
+ return self.conv(x)
60
+
61
+
62
+ class OutConv(nn.Module):
63
+ def __init__(self, in_channels, out_channels=2):
64
+ super(OutConv, self).__init__()
65
+ self.conv = nn.Sequential(
66
+
67
+
68
+ nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, bias=False),
69
+ )
70
+
71
+ def forward(self, x):
72
+ return self.conv(x)
73
+
74
+
75
+
76
+
77
+ class UNet(nn.Module):
78
+ def __init__(self, n_channels=3, bilinear=False):
79
+ super(UNet, self).__init__()
80
+ self.n_channels = n_channels
81
+ self.bilinear = bilinear
82
+
83
+ # Encoder.
84
+ self.inc = DoubleConv(n_channels, 64)
85
+ self.down1 = Down(64, 128)
86
+ self.down2 = Down(128, 256)
87
+ self.down3 = Down(256, 512)
88
+ self.down4 = Down(512, 1024)
89
+
90
+ # Decoder.
91
+ self.up1 = Up(1024, 512, bilinear)
92
+ self.up2 = Up(512, 256, bilinear)
93
+ self.up3 = Up(256, 128, bilinear)
94
+ self.up4 = Up(128, 64, bilinear)
95
+
96
+ self.outc = OutConv(64, 2)
97
+
98
+
99
+
100
+
101
+ def forward(self, x):
102
+ # Encoder path.
103
+ x1 = self.inc(x)
104
+ x2 = self.down1(x1)
105
+ x3 = self.down2(x2)
106
+ x4 = self.down3(x3)
107
+ x5 = self.down4(x4)
108
+
109
+ # Decoder path.
110
+ x = self.up1(x5, x4)
111
+ x = self.up2(x, x3)
112
+ x = self.up3(x, x2)
113
+
114
+ x = self.up4(x, x1)
115
+
116
+ # Predict the means.
117
+ outputs = self.outc(x)
118
+ M_mean = outputs[:, 0:1] # M mean.
119
+ D_mean = outputs[:, 1:2] # D mean.
120
+ return {'M_mean': M_mean, 'D_mean': D_mean}
121
+
122
+
123
+ if __name__ == "__main__":
124
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
125
+ model = UNet(3, bilinear=False).to(device)
126
+ print(summary(model, (3, 800, 800)))
127
+
128
+ # Example input.
129
+ x = torch.randn(1, 3, 800, 800).to(device)
130
+ output = model(x)
131
+ print("output M:", output['M_mean'].shape)
132
+ print("output D:", output['D_mean'].shape)
133
+
134
+
135
+
Different networks compare(without CD-model)/dataloader.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import random
3
+ import numpy as np
4
+ from PIL import Image
5
+ from scipy import io
6
+ import torch
7
+ from torch.utils.data import Dataset, DataLoader, Subset
8
+ from torch.utils.data.distributed import DistributedSampler
9
+ import torchvision.transforms.functional as TF
10
+
11
+ class CustomDataset(Dataset):
12
+ def __init__(self, root_dir, crop_size=None, augment=False):
13
+ """
14
+ Initialize the dataset.
15
+ Args:
16
+ root_dir: Dataset root directory.
17
+ crop_size: Crop size as an integer or a (height, width) tuple.
18
+ augment: Whether to enable data augmentation for the training set.
19
+ """
20
+ self.root_dir = root_dir
21
+ self.input_dir = os.path.join(root_dir, 'input')
22
+ self.output_dir = os.path.join(root_dir, 'output')
23
+
24
+ # Sort strictly for deterministic multi-GPU and repeated runs.
25
+ self.samples = sorted(os.listdir(self.input_dir))
26
+ self.augment = augment
27
+
28
+ # Process the crop dimensions.
29
+ if crop_size is not None:
30
+ if isinstance(crop_size, (int, float)):
31
+ self.crop_height = self.crop_width = int(crop_size)
32
+ elif isinstance(crop_size, (tuple, list)) and len(crop_size) == 2:
33
+ self.crop_height, self.crop_width = crop_size
34
+ else:
35
+ raise ValueError("crop_size should be an integer or a tuple of (height, width)")
36
+ else:
37
+ self.crop_height = self.crop_width = None
38
+
39
+ def __len__(self):
40
+ """Return the dataset size."""
41
+ return len(self.samples)
42
+
43
+ def __getitem__(self, idx):
44
+ sample_name = self.samples[idx]
45
+
46
+ # 1. Read each input image: (H, W) -> [1, H, W].
47
+ img_folder = os.path.join(self.input_dir, sample_name)
48
+ img1 = torch.from_numpy(np.array(Image.open(os.path.join(img_folder, 'image1.png')), dtype=np.float32)).unsqueeze(0)
49
+ img2 = torch.from_numpy(np.array(Image.open(os.path.join(img_folder, 'image2.png')), dtype=np.float32)).unsqueeze(0)
50
+ img3 = torch.from_numpy(np.array(Image.open(os.path.join(img_folder, 'image3.png')), dtype=np.float32)).unsqueeze(0)
51
+
52
+ # Concatenate three images into [3, H, W] so transforms remain synchronized.
53
+ input_tensor = torch.cat([img1, img2, img3], dim=0)
54
+
55
+ # 2. Read the .mat label and convert it to a [1, H, W] tensor.
56
+ label_folder = os.path.join(self.output_dir, sample_name)
57
+ mat_data = io.loadmat(os.path.join(label_folder, 'label.mat'))
58
+ M_tensor = torch.from_numpy(mat_data['M'].astype(np.float32)).unsqueeze(0)
59
+ D_tensor = torch.from_numpy(mat_data['D'].astype(np.float32)).unsqueeze(0)
60
+
61
+ # 3. Apply synchronized geometric augmentation to training data with 75% probability.
62
+ if self.augment and random.random() < 0.75:
63
+ # Use small random transforms to favor physical patterns over memorization.
64
+ angle = random.uniform(-5.0, 5.0) # Rotation: [-5, 5] degrees.
65
+ tx = random.randint(-12, 12) # X translation: [-12, 12].
66
+ ty = random.randint(-12, 12) # Y translation: [-12, 12].
67
+ scale = random.uniform(0.95, 1.05) # Scale: [0.95, 1.05].
68
+
69
+ # Apply all geometric transforms in one affine operation with bilinear interpolation.
70
+ input_tensor = TF.affine(input_tensor, angle=angle, translate=[tx, ty], scale=scale, shear=0, interpolation=TF.InterpolationMode.BILINEAR)
71
+ M_tensor = TF.affine(M_tensor, angle=angle, translate=[tx, ty], scale=scale, shear=0, interpolation=TF.InterpolationMode.BILINEAR)
72
+ D_tensor = TF.affine(D_tensor, angle=angle, translate=[tx, ty], scale=scale, shear=0, interpolation=TF.InterpolationMode.BILINEAR)
73
+
74
+ # 4. Compute sina, cosa, and the mask from the transformed physical images.
75
+ img1_t, img2_t, img3_t = input_tensor[0], input_tensor[1], input_tensor[2]
76
+
77
+ sina = -(img1_t * np.sin(2 * np.pi * 0 / 3) + img2_t * np.sin(2 * np.pi * 1 / 3) + img3_t * np.sin(2 * np.pi * 2 / 3))
78
+ cosa = (img1_t * np.cos(2 * np.pi * 0 / 3) + img2_t * np.cos(2 * np.pi * 1 / 3) + img3_t * np.cos(2 * np.pi * 2 / 3))
79
+
80
+ # Create the mask in 2D first to avoid a dimension mismatch: [H, W].
81
+ mask_2d = torch.ones_like(img1_t, dtype=torch.float32)
82
+ # Apply Boolean indexing while the mask is 2D.
83
+ mask_2d[(sina == 0) & (cosa == 0)] = 0
84
+ # Add the channel dimension after assignment to obtain [1, H, W].
85
+ mask_tensor = mask_2d.unsqueeze(0)
86
+
87
+ # 5. Center-crop the inputs, labels, and mask together.
88
+ if self.crop_height is not None and self.crop_width is not None:
89
+ _, H, W = input_tensor.shape
90
+ start_h = (H - self.crop_height) // 2
91
+ start_w = (W - self.crop_width) // 2
92
+
93
+ input_tensor = input_tensor[:, start_h:start_h + self.crop_height, start_w:start_w + self.crop_width]
94
+ M_tensor = M_tensor[:, start_h:start_h + self.crop_height, start_w:start_w + self.crop_width]
95
+ D_tensor = D_tensor[:, start_h:start_h + self.crop_height, start_w:start_w + self.crop_width]
96
+ mask_tensor = mask_tensor[:, start_h:start_h + self.crop_height, start_w:start_w + self.crop_width]
97
+
98
+ # 6. Apply consistent value normalization by dividing by 1000.
99
+ input_tensor = input_tensor / 1000.0
100
+ M_tensor = M_tensor / 1000.0
101
+ D_tensor = D_tensor / 1000.0
102
+
103
+ return input_tensor, {'M': M_tensor, 'D': D_tensor, 'mask': mask_tensor}
104
+
105
+
106
+ def seed_everything(seed=42):
107
+ """Set global seeds for reproducible results."""
108
+ random.seed(seed)
109
+ os.environ['PYTHONHASHSEED'] = str(seed)
110
+ np.random.seed(seed)
111
+ torch.manual_seed(seed)
112
+ torch.cuda.manual_seed(seed)
113
+ torch.cuda.manual_seed_all(seed)
114
+ torch.backends.cudnn.deterministic = True
115
+ torch.backends.cudnn.benchmark = False
116
+
117
+
118
+ def seed_worker(worker_id):
119
+ """Set a distinct seed for each DataLoader worker."""
120
+ worker_seed = torch.initial_seed() % 2**32
121
+ np.random.seed(worker_seed)
122
+ random.seed(worker_seed)
123
+
124
+
125
+ def create_data_loaders(
126
+ data_dir,
127
+ batch_size=4,
128
+ train_ratio=0.8,
129
+ num_workers=0,
130
+ crop_size=None,
131
+ seed=42,
132
+ distributed=False
133
+ ):
134
+ """
135
+ Create data loaders with a deterministic split and training-only augmentation.
136
+ """
137
+ seed_everything(seed)
138
+
139
+ # Enable augmentation for training while keeping validation images unchanged.
140
+ train_dataset_full = CustomDataset(data_dir, crop_size=crop_size, augment=True)
141
+ val_dataset_full = CustomDataset(data_dir, crop_size=crop_size, augment=False)
142
+
143
+ # Split deterministic indices instead of sharing random_split dataset state.
144
+ dataset_size = len(train_dataset_full)
145
+ indices = list(range(dataset_size))
146
+
147
+ np_rng = np.random.RandomState(seed)
148
+ np_rng.shuffle(indices)
149
+
150
+ train_size = int(train_ratio * dataset_size)
151
+ train_indices = indices[:train_size]
152
+ val_indices = indices[train_size:]
153
+
154
+ # Separate training and validation data with Subset.
155
+ train_dataset = Subset(train_dataset_full, train_indices)
156
+ val_dataset = Subset(val_dataset_full, val_indices)
157
+
158
+ g = torch.Generator()
159
+ g.manual_seed(seed)
160
+
161
+ if distributed:
162
+ train_sampler = DistributedSampler(train_dataset, shuffle=True, seed=seed, drop_last=True)
163
+ val_sampler = DistributedSampler(val_dataset, shuffle=False, drop_last=False)
164
+ else:
165
+ train_sampler = None
166
+ val_sampler = None
167
+
168
+ train_loader = DataLoader(
169
+ train_dataset,
170
+ batch_size=batch_size,
171
+ shuffle=(train_sampler is None),
172
+ sampler=train_sampler,
173
+ num_workers=num_workers,
174
+ pin_memory=True,
175
+ drop_last=True,
176
+ persistent_workers=(num_workers > 0),
177
+ worker_init_fn=seed_worker,
178
+ generator=g,
179
+ )
180
+
181
+ val_loader = DataLoader(
182
+ val_dataset,
183
+ batch_size=batch_size,
184
+ shuffle=False,
185
+ sampler=val_sampler,
186
+ num_workers=num_workers,
187
+ pin_memory=True,
188
+ drop_last=False, # Keep every validation sample for complete evaluation.
189
+ persistent_workers=(num_workers > 0),
190
+ worker_init_fn=seed_worker,
191
+ generator=g,
192
+ )
193
+
194
+ return train_loader, val_loader
195
+
196
+ if __name__ == "__main__":
197
+ # Basic smoke test.
198
+ print("Dataloader script is ready!")
Different networks compare(without CD-model)/predict.py ADDED
@@ -0,0 +1,503 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from PIL import Image
4
+ import os
5
+ import numpy as np
6
+ from typing import Tuple, List, Optional
7
+ import logging
8
+ # Import the model architecture used for prediction; it must match the checkpoint.
9
+ from dfppnet import DFPPNet3FrameMD
10
+ from scipy import io
11
+ import matplotlib.pyplot as plt
12
+ from scipy.ndimage import zoom
13
+ import cv2
14
+ import time
15
+
16
+
17
+ class Predictor:
18
+ """
19
+ Predictor for M and D matrices.
20
+ """
21
+
22
+ def __init__(self, model_path: str, crop_size=None, device: Optional[str] = None):
23
+ """
24
+ Initialize the predictor.
25
+ Args:
26
+ model_path: Path to the model weights.
27
+ crop_size: Crop dimensions.
28
+ device: Device to use ('cuda' or 'cpu'); select automatically when None.
29
+ """
30
+ # Configure logging.
31
+ self._setup_logger()
32
+
33
+ # Configure the device.
34
+ self.device = self._setup_device(device)
35
+ self.logger.info(f"Using device: {self.device}")
36
+
37
+ # Process the crop dimensions.
38
+ if crop_size is not None:
39
+ if isinstance(crop_size, (int, float)):
40
+ self.crop_height = self.crop_width = int(crop_size)
41
+ elif isinstance(crop_size, (tuple, list)) and len(crop_size) == 2:
42
+ self.crop_height, self.crop_width = crop_size
43
+ else:
44
+ raise ValueError("crop_size should be an integer or a tuple of (height, width)")
45
+ self.logger.info(f"Using crop size: ({self.crop_height}, {self.crop_width})")
46
+ else:
47
+ self.crop_height = self.crop_width = None
48
+ self.logger.info("Cropping disabled")
49
+
50
+ # Load the model.
51
+ try:
52
+ self.model = self._load_model(model_path)
53
+ self.logger.info("Model loaded successfully")
54
+ except Exception as e:
55
+ self.logger.error(f"Failed to load model: {str(e)}")
56
+ raise
57
+
58
+ def _setup_logger(self):
59
+ """Configure logging."""
60
+ self.logger = logging.getLogger('Predictor')
61
+ self.logger.setLevel(logging.INFO)
62
+ if not self.logger.handlers:
63
+ handler = logging.StreamHandler()
64
+ formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
65
+ handler.setFormatter(formatter)
66
+ self.logger.addHandler(handler)
67
+
68
+ def _setup_device(self, device: Optional[str]) -> torch.device:
69
+ """Configure the compute device."""
70
+ if device is None:
71
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
72
+ return torch.device(device)
73
+
74
+ def _load_model(self, model_path: str) -> nn.Module:
75
+ """Load the model."""
76
+ if not os.path.exists(model_path):
77
+ raise FileNotFoundError(f"Model file not found: {model_path}")
78
+
79
+ # Create the model.
80
+ model = DFPPNet3FrameMD(n_feat=4, stage0_align=True, stage1_align=False, stage2_align=False, return_aux=False)
81
+ checkpoint = torch.load(model_path, map_location=self.device)
82
+ model.load_state_dict(checkpoint['model_state_dict'])
83
+ model = model.to(self.device)
84
+ model.eval()
85
+ return model
86
+
87
+ def _process_images(self, img1_path: str, img2_path: str, img3_path: str) -> Tuple[torch.Tensor, Tuple[int, int]]:
88
+ """
89
+ Convert three images into network input.
90
+ Returns the processed tensor and original dimensions:
91
+ (tensor, (orig_height, orig_width)).
92
+ """
93
+ # Read the three images.
94
+ img1 = np.array(Image.open(img1_path), dtype=np.float32)
95
+ img2 = np.array(Image.open(img2_path), dtype=np.float32)
96
+ img3 = np.array(Image.open(img3_path), dtype=np.float32)
97
+
98
+ # Preserve the original dimensions.
99
+ orig_height, orig_width = img1.shape
100
+
101
+ # Calculate sina and cosa.
102
+ S = 3
103
+ sina = np.zeros_like(img1, dtype=np.float32)
104
+ cosa = np.zeros_like(img1, dtype=np.float32)
105
+
106
+ for n in range(1, S + 1):
107
+ sina -= [img1, img2, img3][n - 1] * np.sin(2 * np.pi * (n - 1) / S)
108
+ cosa += [img1, img2, img3][n - 1] * np.cos(2 * np.pi * (n - 1) / S)
109
+
110
+ # Normalize by dividing directly by 255.
111
+ # sina = sina / 1000
112
+ # cosa = cosa / 1000
113
+ img1 = img1 / 1000
114
+ img2 = img2 / 1000
115
+ img3 = img3 / 1000
116
+
117
+ # Crop when requested.
118
+ if self.crop_height is not None and self.crop_width is not None:
119
+ H, W = img1.shape
120
+ start_h = (H - self.crop_height) // 2
121
+ start_w = (W - self.crop_width) // 2
122
+ img1 = img1[start_h:start_h + self.crop_height, start_w:start_w + self.crop_width]
123
+ img2 = img2[start_h:start_h + self.crop_height, start_w:start_w + self.crop_width]
124
+ img3 = img3[start_h:start_h + self.crop_height, start_w:start_w + self.crop_width]
125
+
126
+ img1_tensor = torch.from_numpy(img1).float().unsqueeze(0) # [1, H, W]
127
+ img2_tensor = torch.from_numpy(img2).float().unsqueeze(0) # [1, H, W]
128
+ img3_tensor = torch.from_numpy(img3).float().unsqueeze(0) # [1, H, W]
129
+
130
+ input_tensor = torch.cat([img1_tensor, img2_tensor, img3_tensor], dim=0)
131
+ return input_tensor, (orig_height, orig_width)
132
+
133
+ def create_mask(self, img1_path: str, img2_path: str, img3_path: str) -> Tuple[np.ndarray, Tuple[int, int]]:
134
+ """
135
+ Create a mask that is zero where all three images have zero-valued pixels.
136
+ Returns the mask and original dimensions: (mask, (orig_height, orig_width)).
137
+ """
138
+ img1 = np.array(Image.open(img1_path))
139
+ img2 = np.array(Image.open(img2_path))
140
+ img3 = np.array(Image.open(img3_path))
141
+
142
+ # Preserve the original dimensions.
143
+ orig_height, orig_width = img1.shape
144
+
145
+ # Create the mask.
146
+ mask = np.ones_like(img1, dtype=np.float32)
147
+ mask[(img1 == 0) & (img2 == 0) & (img3 == 0)] = 0
148
+
149
+ # Crop when requested.
150
+ if self.crop_height is not None and self.crop_width is not None:
151
+ H, W = mask.shape
152
+ start_h = (H - self.crop_height) // 2
153
+ start_w = (W - self.crop_width) // 2
154
+ mask = mask[start_h:start_h + self.crop_height, start_w:start_w + self.crop_width]
155
+
156
+ return mask, (orig_height, orig_width)
157
+
158
+ def _restore_to_original_size(self, data: np.ndarray, orig_size: Tuple[int, int]) -> np.ndarray:
159
+ """
160
+ Restore cropped data to the center of the original dimensions.
161
+
162
+ Args:
163
+ data: Cropped data.
164
+ orig_size: Original dimensions as (height, width).
165
+
166
+ Returns:
167
+ Data restored to the original dimensions.
168
+ """
169
+ if self.crop_height is None or self.crop_width is None:
170
+ return data
171
+
172
+ orig_height, orig_width = orig_size
173
+ result = np.zeros((orig_height, orig_width), dtype=data.dtype)
174
+
175
+ # Calculate the placement coordinates.
176
+ start_h = (orig_height - self.crop_height) // 2
177
+ start_w = (orig_width - self.crop_width) // 2
178
+
179
+ # Place the cropped data in the center.
180
+ result[start_h:start_h + self.crop_height, start_w:start_w + self.crop_width] = data
181
+
182
+ return result
183
+
184
+ def predict_single(self, img1_path: str, img2_path: str, img3_path: str) -> Tuple[np.ndarray, np.ndarray]:
185
+ """
186
+ Predict the M and D matrices once.
187
+ """
188
+ self.logger.info("Starting single prediction...")
189
+
190
+ try:
191
+ # Process the input images.
192
+ inputs, orig_size = self._process_images(img1_path, img2_path, img3_path)
193
+ mask, _ = self.create_mask(img1_path, img2_path, img3_path)
194
+ mask = torch.from_numpy(mask).unsqueeze(0) # [1, H, W]
195
+
196
+ # Use evaluation mode during prediction to disable dropout.
197
+ self.model.eval()
198
+ with torch.no_grad():
199
+ inputs = inputs.unsqueeze(0).to(self.device) # [1, 3, H, W]
200
+ outputs= self.model(inputs)
201
+
202
+ # Process the outputs.
203
+ M = outputs['M_mean'].squeeze().cpu().numpy() # [H, W]
204
+ D = outputs['D_mean'].squeeze().cpu().numpy() # [H, W]
205
+
206
+
207
+ # Apply the mask.
208
+ M *= mask.squeeze().numpy()
209
+ D *= mask.squeeze().numpy()
210
+
211
+
212
+ # Restore the original dimensions.
213
+ M = self._restore_to_original_size(M, orig_size)
214
+ D = self._restore_to_original_size(D, orig_size)
215
+
216
+
217
+ # Create a mask with the original dimensions.
218
+ full_mask, _ = self.create_mask(img1_path, img2_path, img3_path)
219
+ if self.crop_height is not None and self.crop_width is not None:
220
+ # Reconstruct the full mask.
221
+ orig_height, orig_width = orig_size
222
+ full_mask = np.ones((orig_height, orig_width), dtype=np.float32)
223
+ full_mask[(np.array(Image.open(img1_path)) == 0) &
224
+ (np.array(Image.open(img2_path)) == 0) &
225
+ (np.array(Image.open(img3_path)) == 0)] = 0
226
+
227
+ # Apply the full mask.
228
+ M *= full_mask
229
+ D *= full_mask
230
+
231
+
232
+ self.logger.info("Single prediction completed")
233
+ return {'M': M, 'D': D}
234
+
235
+ except Exception as e:
236
+ self.logger.error(f"An error occurred during prediction: {str(e)}")
237
+ raise
238
+
239
+ def predict_with_uncertainty(self, img1_path: str, img2_path: str, img3_path: str, n_samples=50) -> dict:
240
+ """
241
+ Predict with Monte Carlo sampling, including uncertainty estimation.
242
+ """
243
+ self.logger.info(f"Starting Monte Carlo prediction (samples: {n_samples})...")
244
+
245
+ try:
246
+ # Process the input images.
247
+ inputs, orig_size = self._process_images(img1_path, img2_path, img3_path)
248
+ mask, _ = self.create_mask(img1_path, img2_path, img3_path)
249
+ mask = torch.from_numpy(mask).unsqueeze(0) # [1, H, W]
250
+
251
+ # Store Monte Carlo samples.
252
+ M_samples = []
253
+ D_samples = []
254
+ var_M_samples = []
255
+ var_D_samples = []
256
+
257
+ # Monte Carlo sampling uses training mode to enable dropout.
258
+ self.model.train()
259
+ inputs = inputs.unsqueeze(0).to(self.device) # [1, 3, H, W]
260
+ with torch.no_grad():
261
+ for _ in range(n_samples):
262
+ outputs = self.model(inputs)
263
+ M_samples.append(outputs['M_mean'].cpu().numpy())
264
+ D_samples.append(outputs['D_mean'].cpu().numpy())
265
+ var_M_samples.append(outputs['M_var'].cpu().numpy())
266
+ var_D_samples.append(outputs['D_var'].cpu().numpy())
267
+
268
+ # Convert to NumPy arrays.
269
+ M_samples = np.concatenate(M_samples, axis=0)
270
+ D_samples = np.concatenate(D_samples, axis=0)
271
+ var_M_samples = np.concatenate(var_M_samples, axis=0)
272
+ var_D_samples = np.concatenate(var_D_samples, axis=0)
273
+
274
+ # Calculate means and uncertainties.
275
+ M_mean = np.mean(M_samples, axis=0).squeeze()
276
+ D_mean = np.mean(D_samples, axis=0).squeeze()
277
+ var_M_mean = np.mean(var_M_samples, axis=0).squeeze()
278
+ var_D_mean = np.mean(var_D_samples, axis=0).squeeze()
279
+
280
+ # Calculate model and data uncertainties.
281
+ M_model_uncertainty = np.sqrt(np.mean((M_samples - M_mean) ** 2, axis=0)).squeeze()
282
+ D_model_uncertainty = np.sqrt(np.mean((D_samples - D_mean) ** 2, axis=0)).squeeze()
283
+
284
+ M_data_uncertainty = np.sqrt(np.mean(var_M_samples, axis=0)).squeeze()
285
+ D_data_uncertainty = np.sqrt(np.mean(var_D_samples, axis=0)).squeeze()
286
+
287
+
288
+ M_model_uncertainty = M_model_uncertainty
289
+ D_model_uncertainty = D_model_uncertainty
290
+ M_data_uncertainty = M_data_uncertainty
291
+ D_data_uncertainty = D_data_uncertainty
292
+ M_total_uncertainty = (M_model_uncertainty ** 2 + M_data_uncertainty ** 2)
293
+ D_total_uncertainty = (D_model_uncertainty ** 2 + D_data_uncertainty ** 2)
294
+
295
+ # Apply the mask.
296
+ mask = mask.squeeze().numpy()
297
+ M_mean *= mask
298
+ D_mean *= mask
299
+ M_model_uncertainty *= mask
300
+ D_model_uncertainty *= mask
301
+ M_data_uncertainty *= mask
302
+ D_data_uncertainty *= mask
303
+ M_total_uncertainty *= mask
304
+ D_total_uncertainty *= mask
305
+ var_M_mean *= mask
306
+ var_D_mean *= mask
307
+
308
+ # Create a mask with the original dimensions.
309
+ full_mask = np.ones(orig_size, dtype=np.float32)
310
+ full_mask[(np.array(Image.open(img1_path)) == 0) &
311
+ (np.array(Image.open(img2_path)) == 0) &
312
+ (np.array(Image.open(img3_path)) == 0)] = 0
313
+
314
+ # Restore the original dimensions.
315
+ M_mean = self._restore_to_original_size(M_mean, orig_size)
316
+ D_mean = self._restore_to_original_size(D_mean, orig_size)
317
+ M_model_uncertainty = self._restore_to_original_size(M_model_uncertainty, orig_size)
318
+ D_model_uncertainty = self._restore_to_original_size(D_model_uncertainty, orig_size)
319
+ M_data_uncertainty = self._restore_to_original_size(M_data_uncertainty, orig_size)
320
+ D_data_uncertainty = self._restore_to_original_size(D_data_uncertainty, orig_size)
321
+ M_total_uncertainty = self._restore_to_original_size(M_total_uncertainty, orig_size)
322
+ D_total_uncertainty = self._restore_to_original_size(D_total_uncertainty, orig_size)
323
+ var_M_mean = self._restore_to_original_size(var_M_mean, orig_size)
324
+ var_D_mean = self._restore_to_original_size(var_D_mean, orig_size)
325
+
326
+ # Apply the full mask to the restored results.
327
+ M_mean *= full_mask
328
+ D_mean *= full_mask
329
+ M_model_uncertainty *= full_mask
330
+ D_model_uncertainty *= full_mask
331
+ M_data_uncertainty *= full_mask
332
+ D_data_uncertainty *= full_mask
333
+ M_total_uncertainty *= full_mask
334
+ D_total_uncertainty *= full_mask
335
+ var_M_mean *= full_mask
336
+ var_D_mean *= full_mask
337
+
338
+ # Visualize uncertainty.
339
+ self._visualize_uncertainties({
340
+ 'M': M_mean,
341
+ 'D': D_mean,
342
+ 'M_model_uncertainty': M_model_uncertainty,
343
+ 'D_model_uncertainty': D_model_uncertainty,
344
+ 'M_data_uncertainty': M_data_uncertainty,
345
+ 'D_data_uncertainty': D_data_uncertainty,
346
+ 'M_total_uncertainty': M_total_uncertainty,
347
+ 'D_total_uncertainty': D_total_uncertainty
348
+ })
349
+
350
+ # Do not process the 3D sample arrays further.
351
+ self.logger.info("Monte Carlo prediction completed")
352
+ return {
353
+ 'M': M_mean,
354
+ 'D': D_mean,
355
+ 'M_var': var_M_mean,
356
+ 'D_var': var_D_mean,
357
+ 'M_model_uncertainty': M_model_uncertainty,
358
+ 'D_model_uncertainty': D_model_uncertainty,
359
+ 'M_data_uncertainty': M_data_uncertainty,
360
+ 'D_data_uncertainty': D_data_uncertainty,
361
+ 'M_total_uncertainty':M_total_uncertainty,
362
+ 'D_total_uncertainty':D_total_uncertainty
363
+ }
364
+
365
+ except Exception as e:
366
+ self.logger.error(f"An error occurred during prediction: {str(e)}")
367
+ raise
368
+ finally:
369
+ # Return to evaluation mode after sampling.
370
+ self.model.eval()
371
+
372
+ def _visualize_uncertainties(self, results: dict, save_dir: str = 'uncertainty_analysis'):
373
+ """
374
+ Visualize the uncertainty-analysis results.
375
+ Args:
376
+ results: Value returned by predict_with_uncertainty.
377
+ save_dir: Output directory.
378
+ """
379
+ os.makedirs(save_dir, exist_ok=True)
380
+
381
+ plt.figure(figsize=(20, 10))
382
+
383
+ # M prediction and uncertainty.
384
+ plt.subplot(2, 4, 1)
385
+ plt.imshow(results['M'])
386
+ plt.colorbar()
387
+ plt.title('Predicted M')
388
+
389
+ plt.subplot(2, 4, 2)
390
+ plt.imshow(results['M_model_uncertainty'])
391
+ plt.colorbar()
392
+ plt.title('Model Uncertainty (M)')
393
+
394
+ plt.subplot(2, 4, 3)
395
+ plt.imshow(results['M_data_uncertainty'])
396
+ plt.colorbar()
397
+ plt.title('Data Uncertainty (M)')
398
+
399
+ plt.subplot(2, 4, 4)
400
+ total_M = results['M_total_uncertainty']
401
+ plt.imshow(total_M)
402
+ plt.colorbar()
403
+ plt.title('Total Uncertainty (M)')
404
+
405
+ # D prediction and uncertainty.
406
+ plt.subplot(2, 4, 5)
407
+ plt.imshow(results['D'])
408
+ plt.colorbar()
409
+ plt.title('Predicted D')
410
+
411
+ plt.subplot(2, 4, 6)
412
+ plt.imshow(results['D_model_uncertainty'])
413
+ plt.colorbar()
414
+ plt.title('Model Uncertainty (D)')
415
+
416
+ plt.subplot(2, 4, 7)
417
+ plt.imshow(results['D_data_uncertainty'])
418
+ plt.colorbar()
419
+ plt.title('Data Uncertainty (D)')
420
+
421
+ plt.subplot(2, 4, 8)
422
+ total_D = results['D_total_uncertainty']
423
+ plt.imshow(total_D)
424
+ plt.colorbar()
425
+ plt.title('Total Uncertainty (D)')
426
+
427
+ plt.tight_layout()
428
+ plt.savefig(os.path.join(save_dir, 'uncertainty_analysis.png'))
429
+ plt.close()
430
+
431
+ self.logger.info(f"Uncertainty analysis plot saved to: {save_dir}")
432
+
433
+ def save_prediction(self, results, save_path: str, mode='single'):
434
+ """
435
+ Save prediction results to a .mat file.
436
+ Args:
437
+ results: Prediction results as a tuple or dictionary.
438
+ save_path: Output path.
439
+ mode: Prediction mode, either 'single' or 'mc'.
440
+ """
441
+ try:
442
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
443
+
444
+ if mode == 'single':
445
+ io.savemat(save_path, results)
446
+ else: # mode == 'mc'
447
+ io.savemat(save_path, results)
448
+
449
+ self.logger.info(f"Prediction results saved to: {save_path}")
450
+ except Exception as e:
451
+ self.logger.error(f"Failed to save results: {str(e)}")
452
+ raise
453
+
454
+
455
+ if __name__ == "__main__":
456
+ # Create the predictor and set the checkpoint used for inference.
457
+ predictor = Predictor(
458
+ model_path="path/to/your/model_weights.pth",
459
+ crop_size=(1360,672),
460
+ device='cuda'
461
+ )
462
+
463
+ # Set paths to the three input frames.
464
+ img1_path = 'path/to/your/input/image1.png'
465
+ img2_path = 'path/to/your/input/image2.png'
466
+ img3_path = 'path/to/your/input/image3.png'
467
+
468
+ # Single-prediction example.
469
+ try:
470
+ result = predictor.predict_single(img1_path, img2_path, img3_path)
471
+ predictor.save_prediction(result, 'pre_dfpp/single_result.mat', mode='single')
472
+ except Exception as e:
473
+ print(f"Single prediction failed: {str(e)}")
474
+
475
+ # Display the mask.
476
+ mask, orig_size = predictor.create_mask(img1_path, img2_path, img3_path)
477
+
478
+ # Restore the mask to its original dimensions when cropping is enabled.
479
+ if predictor.crop_height is not None and predictor.crop_width is not None:
480
+ full_mask = np.ones(orig_size, dtype=np.float32)
481
+ full_mask[(np.array(Image.open(img1_path)) == 0) &
482
+ (np.array(Image.open(img2_path)) == 0) &
483
+ (np.array(Image.open(img3_path)) == 0)] = 0
484
+ mask_to_save = full_mask
485
+ else:
486
+ mask_to_save = mask
487
+
488
+ # Save the mask as an image.
489
+ cv2.imwrite('pre_dfpp/mask.png', mask_to_save*255)
490
+ # Save the mask as a .mat file.
491
+ io.savemat('pre_dfpp/mask.mat', {'mask':mask_to_save})
492
+ plt.imshow(mask_to_save)
493
+
494
+ # Monte Carlo sampling example.
495
+ # try:
496
+ # results = predictor.predict_with_uncertainty(img1_path, img2_path, img3_path, n_samples=50)
497
+ # print("\nMonte Carlo prediction result shapes:")
498
+ # for key, value in results.items():
499
+ # print(f"{key}: {value.shape}")
500
+ # predictor.save_prediction(results, 'pre_dfpp/mc_result.mat', mode='mc')
501
+ # predictor._visualize_uncertainties(results)
502
+ # except Exception as e:
503
+ # print(f"Monte Carlo prediction failed: {str(e)}")
Different networks compare(without CD-model)/train.py ADDED
@@ -0,0 +1,457 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.optim as optim
4
+ from torch.utils.data import DataLoader
5
+ from tqdm import tqdm
6
+ import matplotlib.pyplot as plt
7
+ import matplotlib
8
+ matplotlib.use('Agg') # Force a non-interactive backend.
9
+ import matplotlib.pyplot as plt
10
+ import numpy as np
11
+ import os
12
+ from dataloader import CustomDataset, create_data_loaders
13
+ # Import the model architecture selected for training; replace this import to use another model.
14
+ from dfppnet import DFPPNet3FrameMD
15
+ import torch.nn.functional as F
16
+ import cv2
17
+ import torch.distributed as dist
18
+ from torch.nn.parallel import DistributedDataParallel as DDP
19
+ from torch.utils.data.distributed import DistributedSampler
20
+ import random
21
+
22
+
23
+ # Use this masking method for real data.
24
+ class BNNLoss(nn.Module):
25
+ def __init__(self, alpha=0.000001):
26
+ super(BNNLoss, self).__init__()
27
+ self.modelalpha = alpha
28
+ # Define a cross-shaped convolution kernel.
29
+ self.kernel = torch.tensor([
30
+ [0, 1, 0],
31
+ [1, 1, 1],
32
+ [0, 1, 0]
33
+ ], dtype=torch.float32).unsqueeze(0).unsqueeze(0)
34
+
35
+ def forward(self, outputs, targets, mask):
36
+ M_mean = outputs['M_mean']
37
+ D_mean = outputs['D_mean']
38
+
39
+
40
+ M_true = targets['M']
41
+ D_true = targets['D']
42
+
43
+ # Generate the mask with convolution.
44
+ self.kernel = self.kernel.to(mask.device)
45
+ # rect_mask = (F.conv2d(mask, self.kernel, padding=1) == 5).float()
46
+ rect_mask=mask
47
+
48
+ # Calculate the MSE loss.
49
+ mse_M = F.mse_loss(M_mean * rect_mask, M_true * rect_mask, reduction='sum') / (rect_mask.sum() + 1e-8)
50
+ mse_D = F.mse_loss(D_mean * rect_mask, D_true * rect_mask, reduction='sum') / (rect_mask.sum() + 1e-8)
51
+ total_loss = (mse_M + mse_D)
52
+ return total_loss, mse_M, mse_D
53
+
54
+
55
+
56
+
57
+ class EarlyStopping:
58
+ def __init__(self, patience=10, min_delta=0, verbose=True):
59
+ self.patience = patience
60
+ self.min_delta = min_delta
61
+ self.verbose = verbose
62
+ self.counter = 0
63
+ self.best_loss = None
64
+ self.early_stop = False
65
+
66
+ def __call__(self, val_loss):
67
+ if self.best_loss is None:
68
+ self.best_loss = val_loss
69
+ elif val_loss > self.best_loss - self.min_delta:
70
+ self.counter += 1
71
+ if self.verbose:
72
+ print(f'EarlyStopping counter: {self.counter} out of {self.patience}')
73
+ if self.counter >= self.patience:
74
+ self.early_stop = True
75
+ else:
76
+ self.best_loss = val_loss
77
+ self.counter = 0
78
+
79
+
80
+ class Trainer:
81
+ def __init__(self, model, train_loader, val_loader, optimizer, scheduler,
82
+ num_epochs, device, save_dir='checkpoints', patience=10, alpha=0.000001,
83
+ local_rank=-1):
84
+ self.local_rank = local_rank
85
+ self.device = device
86
+ self.model = model.to(device)
87
+
88
+ # Wrap the model with DDP.
89
+ if local_rank != -1:
90
+ self.model = DDP(self.model,device_ids=[local_rank],find_unused_parameters=True)
91
+
92
+ self.train_loader = train_loader
93
+ self.val_loader = val_loader
94
+ self.optimizer = optimizer
95
+ self.scheduler = scheduler
96
+ self.num_epochs = num_epochs
97
+ self.save_dir = save_dir
98
+ self.early_stopping = EarlyStopping(patience=patience)
99
+ self.criterion = BNNLoss(alpha=alpha)
100
+
101
+ if self.local_rank <= 0: # Create the output directory only in the main process.
102
+ os.makedirs(save_dir, exist_ok=True)
103
+
104
+ self.alpha = alpha
105
+ self.train_losses = []
106
+ self.train_total_loss2 = []
107
+ self.val_total_loss2 = []
108
+ self.val_losses = []
109
+ self.reg_losses = []
110
+ self.learning_rates = []
111
+ self.last_five_checkpoints = []
112
+ self.dropout_rates_history = []
113
+
114
+ def plot_results(self):
115
+ """Plot results only in the main process."""
116
+ if self.local_rank > 0:
117
+ return
118
+
119
+ plt.figure(figsize=(15, 5))
120
+
121
+ # Plot the total-loss curves.
122
+ plt.subplot(1, 3, 1)
123
+ plt.plot(self.train_losses, label='Train Loss')
124
+ plt.plot(self.val_losses, label='Val Loss')
125
+ plt.title('Total Loss')
126
+ plt.xlabel('Epoch')
127
+ plt.ylabel('Loss')
128
+ plt.legend()
129
+ plt.grid(True)
130
+
131
+ plt.tight_layout()
132
+ plt.savefig(f'{self.save_dir}/training_metrics.png')
133
+ plt.close()
134
+
135
+
136
+ def train(self):
137
+ best_val_loss = float('inf')
138
+ total_batches = len(self.train_loader)
139
+
140
+ for epoch in range(self.num_epochs):
141
+ # Set the epoch on the data sampler.
142
+ if isinstance(self.train_loader.sampler, DistributedSampler):
143
+ self.train_loader.sampler.set_epoch(epoch)
144
+
145
+ self.model.train()
146
+ train_loss = 0.0
147
+ train_mse_loss_M = 0.0
148
+ train_mse_loss_D = 0.0
149
+
150
+ if self.local_rank <= 0: # Show the progress bar only in the main process.
151
+ train_pbar = tqdm(self.train_loader,
152
+ desc=f'Epoch [{epoch + 1}/{self.num_epochs}]',
153
+ total=total_batches,
154
+ ncols=150)
155
+ else:
156
+ train_pbar = self.train_loader
157
+
158
+ for batch_idx, (inputs, labels) in enumerate(train_pbar):
159
+ inputs = inputs.to(self.device)
160
+ labels = {k: v.to(self.device) for k, v in labels.items()}
161
+ mask = labels['mask']
162
+
163
+ outputs = self.model(inputs)
164
+ prediction_loss, mse_loss_M,mse_loss_D = self.criterion(outputs, labels, mask)
165
+
166
+ total_loss = prediction_loss
167
+
168
+ self.optimizer.zero_grad()
169
+ total_loss.backward()
170
+ self.optimizer.step()
171
+
172
+ train_loss += total_loss.item()
173
+ train_mse_loss_M += mse_loss_M.item()
174
+ train_mse_loss_D += mse_loss_D.item()
175
+
176
+
177
+
178
+ if self.local_rank <= 0: # Update the progress bar only in the main process.
179
+ train_pbar.set_postfix({
180
+ 'total_loss': f'{total_loss.item():.4f}',
181
+ 'mse_loss_M': f'{mse_loss_M.item():.4f}',
182
+ 'mse_loss_D': f'{mse_loss_D.item():.4f}',
183
+
184
+ })
185
+
186
+ # Synchronize losses across all processes.
187
+ if dist.is_initialized():
188
+ dist.all_reduce(torch.tensor([train_loss]).to(self.device))
189
+ dist.all_reduce(torch.tensor([train_mse_loss_M]).to(self.device))
190
+ dist.all_reduce(torch.tensor([train_mse_loss_D]).to(self.device))
191
+
192
+
193
+ train_loss /= (total_batches * dist.get_world_size() if dist.is_initialized() else total_batches)
194
+ train_mse_loss_M /= (total_batches * dist.get_world_size() if dist.is_initialized() else total_batches)
195
+ train_mse_loss_D /= (total_batches * dist.get_world_size() if dist.is_initialized() else total_batches)
196
+
197
+
198
+ # Validation stage.
199
+ self.model.eval()
200
+ val_loss = 0.0
201
+ val_mse_loss_M = 0.0
202
+ val_mse_loss_D = 0.0
203
+
204
+ with torch.no_grad():
205
+ for inputs, labels in self.val_loader:
206
+ inputs = inputs.to(self.device)
207
+ labels = {k: v.to(self.device) for k, v in labels.items()}
208
+ mask = labels['mask']
209
+
210
+ outputs = self.model(inputs)
211
+ prediction_loss, mse_loss_M, mse_loss_D = self.criterion(outputs, labels, mask)
212
+ total_loss = prediction_loss
213
+
214
+ val_loss += total_loss.item()
215
+ val_mse_loss_M += mse_loss_M.item()
216
+ val_mse_loss_D += mse_loss_D.item()
217
+
218
+ # Synchronize validation losses across all processes.
219
+ if dist.is_initialized():
220
+ dist.all_reduce(torch.tensor([val_loss]).to(self.device))
221
+ dist.all_reduce(torch.tensor([val_mse_loss_M]).to(self.device))
222
+ dist.all_reduce(torch.tensor([val_mse_loss_D]).to(self.device))
223
+
224
+ val_loss /= (len(self.val_loader) * dist.get_world_size() if dist.is_initialized() else len(self.val_loader))
225
+ val_mse_loss_M /= (len(self.val_loader) * dist.get_world_size() if dist.is_initialized() else len(self.val_loader))
226
+ val_mse_loss_D /= (len(self.val_loader) * dist.get_world_size() if dist.is_initialized() else len(self.val_loader))
227
+
228
+
229
+ if self.local_rank <= 0: # Run the following operations only in the main process.
230
+
231
+ # Update the learning rate.
232
+ if isinstance(self.scheduler, optim.lr_scheduler.ReduceLROnPlateau):
233
+ self.scheduler.step(val_loss)
234
+ else:
235
+ self.scheduler.step()
236
+
237
+ current_lr = self.optimizer.param_groups[0]['lr']
238
+ self.learning_rates.append(current_lr)
239
+
240
+ # Record training metrics.
241
+ self.train_losses.append(train_loss)
242
+ self.val_losses.append(val_loss)
243
+
244
+
245
+
246
+ # Print training information.
247
+ print(f'\nEpoch {epoch + 1}/{self.num_epochs}:')
248
+ print(
249
+ f'Train - Total Loss: {train_loss:.4f}, MSE Loss M: {train_mse_loss_M:.4f}, MSE Loss D: {train_mse_loss_D:.4f} '
250
+ )
251
+ print(f'Val - Total Loss: {val_loss:.4f},Val_mse_loss_M:{val_mse_loss_M:.4f},Val_mse_loss_D:{val_mse_loss_D:.4f}')
252
+
253
+ # Save model parameters after every epoch.
254
+ checkpoint_path = f'{self.save_dir}/checkpoint_epoch_{epoch + 1}.pth'
255
+ torch.save({
256
+ 'epoch': epoch,
257
+ 'model_state_dict': self.model.module.state_dict() if isinstance(self.model, DDP) else self.model.state_dict(),
258
+ 'optimizer_state_dict': self.optimizer.state_dict(),
259
+ 'scheduler_state_dict': self.scheduler.state_dict(),
260
+ 'train_losses': self.train_losses,
261
+ 'val_losses': self.val_losses,
262
+ 'learning_rates': self.learning_rates,
263
+ }, checkpoint_path)
264
+ self.last_five_checkpoints.append(checkpoint_path)
265
+
266
+ # Keep model parameters from only the five most recent epochs.
267
+ if len(self.last_five_checkpoints) > 5:
268
+ oldest_checkpoint = self.last_five_checkpoints.pop(0)
269
+ if os.path.exists(oldest_checkpoint):
270
+ os.remove(oldest_checkpoint)
271
+ print(f'Removed oldest checkpoint: {oldest_checkpoint}')
272
+
273
+ # Save an additional checkpoint every five epochs.
274
+ if (epoch + 1) % 10 == 0:
275
+ checkpoint_path = f'{self.save_dir}/checkpoint_epoch1_{epoch + 1}.pth'
276
+ torch.save({
277
+ 'epoch': epoch,
278
+ 'model_state_dict': self.model.module.state_dict() if isinstance(self.model, DDP) else self.model.state_dict(),
279
+ 'optimizer_state_dict': self.optimizer.state_dict(),
280
+ 'scheduler_state_dict': self.scheduler.state_dict(),
281
+ 'train_losses': self.train_losses,
282
+ 'val_losses': self.val_losses,
283
+ 'learning_rates': self.learning_rates,
284
+ }, checkpoint_path)
285
+ print(f'Saved checkpoint at epoch {epoch + 1}')
286
+
287
+ # Save the best model.
288
+ if val_loss < best_val_loss:
289
+ best_val_loss = val_loss
290
+ torch.save({
291
+ 'epoch': epoch,
292
+ 'model_state_dict': self.model.module.state_dict() if isinstance(self.model, DDP) else self.model.state_dict(),
293
+ 'optimizer_state_dict': self.optimizer.state_dict(),
294
+ 'scheduler_state_dict': self.scheduler.state_dict(),
295
+ 'best_val_loss': best_val_loss,
296
+ 'train_losses': self.train_losses,
297
+ 'val_losses': self.val_losses,
298
+ 'learning_rates': self.learning_rates,
299
+ }, f'{self.save_dir}/best_model.pth')
300
+ print('Saved best model!')
301
+
302
+ # Check early stopping.
303
+ self.early_stopping(val_loss)
304
+ if self.early_stopping.early_stop:
305
+ print("Early stopping triggered")
306
+ break
307
+
308
+ # Plot the results.
309
+ self.plot_results()
310
+
311
+ def init_distributed():
312
+ """Initialize distributed training."""
313
+ if 'LOCAL_RANK' in os.environ:
314
+ local_rank = int(os.environ['LOCAL_RANK'])
315
+ torch.cuda.set_device(local_rank)
316
+ dist.init_process_group(backend='nccl')
317
+ return local_rank
318
+ return -1
319
+
320
+ def setup_distributed_training(rank):
321
+ """Set random seeds for distributed training."""
322
+ torch.manual_seed(42)
323
+ torch.cuda.manual_seed(42)
324
+ np.random.seed(42)
325
+ random.seed(42)
326
+
327
+ # Ensure that each process uses a distinct random seed.
328
+ if rank != -1:
329
+ torch.manual_seed(42 + rank)
330
+ torch.cuda.manual_seed(42 + rank)
331
+ np.random.seed(42 + rank)
332
+ random.seed(42 + rank)
333
+
334
+ # Configure CUDA options for performance.
335
+ if torch.cuda.is_available():
336
+ torch.backends.cudnn.benchmark = True
337
+ torch.backends.cudnn.deterministic = False
338
+
339
+ if __name__ == "__main__":
340
+ # Initialize distributed training.
341
+ local_rank = init_distributed()
342
+
343
+ # Set random seeds and other training parameters.
344
+ setup_distributed_training(local_rank)
345
+
346
+ # Configure the device.
347
+ device = torch.device(f'cuda:{local_rank}' if local_rank != -1 else 'cuda' if torch.cuda.is_available() else 'cpu')
348
+
349
+ # Print process information.
350
+ if dist.is_initialized():
351
+ print(f"\nDistributed training information:")
352
+ print(f"Current process local_rank: {local_rank}")
353
+ print(f"Total processes: {dist.get_world_size()}")
354
+ print(f"Current device: {device}")
355
+ print("-" * 50)
356
+ else:
357
+ print("\nNon-distributed training mode")
358
+ print(f"Current device: {device}")
359
+ print("-" * 50)
360
+
361
+ if local_rank <= 0:
362
+ print(f"Using device: {device}")
363
+
364
+ # Configure training parameters.
365
+ data_dir = "path/to/your/dataset" # Set the dataset root directory.
366
+ batch_size = 2
367
+ train_ratio = 0.8
368
+ crop_size = (1360,672)
369
+ num_workers = 16
370
+ num_epochs = 300
371
+ learning_rate = 0.0001
372
+ patience = 20
373
+ reg_weight = 0.01
374
+
375
+ # Create data loaders with DistributedSampler when distributed training is active.
376
+ train_loader, val_loader = create_data_loaders(
377
+ data_dir=data_dir,
378
+ batch_size=batch_size,
379
+ train_ratio=train_ratio,
380
+ num_workers=num_workers,
381
+ crop_size=crop_size,
382
+ distributed=(local_rank != -1)
383
+ )
384
+
385
+ # Create the model and optimizer.
386
+ model = DFPPNet3FrameMD(n_feat=4,
387
+ stage0_align=True,
388
+ stage1_align=False,
389
+ stage2_align=False,
390
+ return_aux=False)
391
+
392
+ pretrained_path = "path/to/your/pretrained_weights.pth" # Set the initialization checkpoint.
393
+ checkpoint = torch.load(pretrained_path, map_location='cpu')
394
+ model.load_state_dict(checkpoint['model_state_dict'], strict=True)
395
+ if local_rank <= 0:
396
+ print(f"Loaded pretrained model from: {pretrained_path}")
397
+ optimizer = optim.Adam(model.parameters(), lr=learning_rate, weight_decay=0.00001)
398
+
399
+ # Create the learning-rate scheduler.
400
+ scheduler = optim.lr_scheduler.ReduceLROnPlateau(
401
+ optimizer,
402
+ mode='min',
403
+ factor=0.1,
404
+ patience=10,
405
+ min_lr=1e-8,
406
+ threshold=0.0001,
407
+ threshold_mode='abs',
408
+ cooldown=5,
409
+ )
410
+
411
+ # Create the trainer.
412
+ trainer = Trainer(
413
+ model=model,
414
+ train_loader=train_loader,
415
+ val_loader=val_loader,
416
+ optimizer=optimizer,
417
+ scheduler=scheduler,
418
+ num_epochs=num_epochs,
419
+ device=device,
420
+ save_dir='dfppnetall',
421
+ patience=patience,
422
+ alpha=4,
423
+ local_rank=local_rank
424
+ )
425
+
426
+ # Start training.
427
+ try:
428
+ if local_rank <= 0:
429
+ print("\nStarting training...")
430
+ print(f"Training with {len(train_loader.dataset)} samples")
431
+ print(f"Validating with {len(val_loader.dataset)} samples")
432
+ print(f"Batch size: {batch_size}")
433
+ print(f"Input size: {crop_size}")
434
+ print(f"Initial learning rate: {learning_rate}")
435
+ print(f"Early stopping patience: {patience}")
436
+ print(f"Regularization weight: {reg_weight}")
437
+ print("-" * 50)
438
+
439
+ trainer.train()
440
+
441
+ if local_rank <= 0:
442
+ print("\nTraining completed successfully!")
443
+
444
+ except KeyboardInterrupt:
445
+ if local_rank <= 0:
446
+ print("\nTraining interrupted by user")
447
+ except Exception as e:
448
+ if local_rank <= 0:
449
+ print(f"\nError during training: {str(e)}")
450
+ raise e
451
+ finally:
452
+ if local_rank <= 0:
453
+ print("\nTraining process finished")
454
+
455
+ # Clean up the distributed process group.
456
+ if dist.is_initialized():
457
+ dist.destroy_process_group()