Anirudh Bhalekar commited on
Commit
1316be2
·
1 Parent(s): f129f93

reqs added

Browse files
__pycache__/app.cpython-311.pyc ADDED
Binary file (891 Bytes). View file
 
__pycache__/inference.cpython-311.pyc ADDED
Binary file (4.02 kB). View file
 
__pycache__/models_Facies.cpython-311.pyc ADDED
Binary file (22.1 kB). View file
 
__pycache__/models_Fault.cpython-311.pyc ADDED
Binary file (15.7 kB). View file
 
app.py CHANGED
@@ -4,5 +4,10 @@ import numpy as np
4
  import requests
5
  from PIL import Image
6
  import torch
 
7
 
8
-
 
 
 
 
 
4
  import requests
5
  from PIL import Image
6
  import torch
7
+ from inference import predict, random_sample
8
 
9
+
10
+ def main():
11
+ gr.Interface(fn=predict,
12
+ inputs=gr.Image(type="pil"),
13
+ outputs=gr.Image(type="pil"),).launch()
requirements.txt ADDED
Binary file (9.65 kB). View file
 
util/__pycache__/datasets.cpython-311.pyc CHANGED
Binary files a/util/__pycache__/datasets.cpython-311.pyc and b/util/__pycache__/datasets.cpython-311.pyc differ
 
util/__pycache__/variable_pos_embed.cpython-311.pyc ADDED
Binary file (5.7 kB). View file
 
util/skeletonize.py DELETED
@@ -1,486 +0,0 @@
1
- """
2
- Courtesy of Martin Mentan:
3
-
4
- Works Cited
5
- Menten, Martin J., et al. ‘A Skeletonization Algorithm for Gradient-Based Optimization’.
6
- Proceedings of the IEEE/CVF International Conference on Computer Vision (ICCV), 2023.
7
-
8
- """
9
-
10
- import torch
11
- import torch.nn as nn
12
- import torch.nn.functional as F
13
-
14
-
15
- class Skeletonize(torch.nn.Module):
16
- """
17
- Class based on PyTorch's Module class to skeletonize two- or three-dimensional input images
18
- while being fully compatible with PyTorch's autograd automatic differention engine as proposed in [1].
19
-
20
- Attributes:
21
- propabilistic: a Boolean that indicates whether the input image should be binarized using
22
- the reparametrization trick and straight-through estimator.
23
- It should always be set to True if non-binary inputs are being provided.
24
- beta: scale of added logistic noise during the reparametrization trick. If too small, there will not be any learning via
25
- gradient-based optimization; if too large, the learning is very slow.
26
- tau: Boltzmann temperature for reparametrization trick.
27
- simple_point_detection: decides whether simple points should be identified using Boolean characterization of their 26-neighborhood (Boolean) [2]
28
- or by checking whether the Euler characteristic changes under their deletion (EulerCharacteristic) [3].
29
- num_iter: number of iterations that each include one end-point check, eight checks for simple points and eight subsequent deletions.
30
- The number of iterations should be tuned to the type of input image.
31
-
32
- [1] Martin J. Menten et al. A skeletonization algorithm for gradient-based optimization.
33
- Proceedings of the IEEE/CVF International Conference on Computer Vision (ICCV), 2023.
34
- [2] Gilles Bertrand. A boolean characterization of three- dimensional simple points.
35
- Pattern recognition letters, 17(2):115-124, 1996.
36
- [3] Steven Lobregt et al. Three-dimensional skeletonization:principle and algorithm.
37
- IEEE Transactions on pattern analysis and machine intelligence, 2(1):75-77, 1980.
38
- """
39
-
40
- def __init__(self, probabilistic=True, beta=0.33, tau=1.0, simple_point_detection='Boolean', num_iter=5):
41
-
42
- super(Skeletonize, self).__init__()
43
-
44
- self.probabilistic = probabilistic
45
- self.tau = tau
46
- self.beta = beta
47
-
48
- self.num_iter = num_iter
49
- self.endpoint_check = self._single_neighbor_check
50
- if simple_point_detection == 'Boolean':
51
- self.simple_check = self._boolean_simple_check
52
- elif simple_point_detection == 'EulerCharacteristic':
53
- self.simple_check = self._euler_characteristic_simple_check
54
- else:
55
- raise Exception()
56
-
57
-
58
- def forward(self, img):
59
-
60
- img = self._prepare_input(img)
61
-
62
- if self.probabilistic:
63
- img = self._stochastic_discretization(img)
64
-
65
- for current_iter in range(self.num_iter):
66
-
67
- # At each iteration create a new map of the end-points
68
- is_endpoint = self.endpoint_check(img)
69
-
70
- # Sub-iterate through eight different subfields
71
- x_offsets = [0, 1, 0, 1, 0, 1, 0, 1]
72
- y_offsets = [0, 0, 1, 1, 0, 0, 1, 1]
73
- z_offsets = [0, 0, 0, 0, 1, 1, 1, 1]
74
-
75
- for x_offset, y_offset, z_offset in zip(x_offsets, y_offsets, z_offsets):
76
-
77
- # At each sub-iteration detect all simple points and delete all simple points that are not end-points
78
- is_simple = self.simple_check(img[:, :, x_offset:, y_offset:, z_offset:])
79
- deletion_candidates = is_simple * (1 - is_endpoint[:, :, x_offset::2, y_offset::2, z_offset::2])
80
- img[:, :, x_offset::2, y_offset::2, z_offset::2] = torch.min(img[:, :, x_offset::2, y_offset::2, z_offset::2].clone(), 1 - deletion_candidates)
81
-
82
- img = self._prepare_output(img)
83
-
84
- return img
85
-
86
-
87
-
88
- def _prepare_input(self, img):
89
- """
90
- Function to check that the input image is compatible with the subsequent calculations.
91
- Only two- and three-dimensional images with values between 0 and 1 are supported.
92
- If the input image is two-dimensional then it is converted into a three-dimensional one for further processing.
93
- """
94
-
95
- if img.dim() == 5:
96
- self.expanded_dims = False
97
- elif img.dim() == 4:
98
- self.expanded_dims = True
99
- img = img.unsqueeze(2)
100
- else:
101
- raise Exception("Only two-or three-dimensional images (tensor dimensionality of 4 or 5) are supported as input.")
102
-
103
- if img.shape[2] == 2 or img.shape[3] == 2 or img.shape[4] == 2 or img.shape[3] == 1 or img.shape[4] == 1:
104
- raise Exception()
105
-
106
- if img.min() < 0.0 or img.max() > 1.0:
107
- raise Exception("Image values must lie between 0 and 1.")
108
-
109
- img = F.pad(img, (1, 1, 1, 1, 1, 1), value=0)
110
-
111
- return img
112
-
113
-
114
- def _stochastic_discretization(self, img):
115
- """
116
- Function to binarize the image so that it can be processed by our skeletonization method.
117
- In order to remain compatible with backpropagation we utilize the reparameterization trick and a straight-through estimator.
118
- """
119
-
120
- alpha = (img + 1e-8) / (1.0 - img + 1e-8)
121
-
122
- uniform_noise = torch.rand_like(img)
123
- uniform_noise = torch.empty_like(img).uniform_(1e-8, 1 - 1e-8)
124
- logistic_noise = (torch.log(uniform_noise) - torch.log(1 - uniform_noise))
125
-
126
- img = torch.sigmoid((torch.log(alpha) + logistic_noise * self.beta) / self.tau)
127
- img = (img.detach() > 0.5).float() - img.detach() + img
128
-
129
- return img
130
-
131
-
132
- def _single_neighbor_check(self, img):
133
- """
134
- Function that characterizes points as endpoints if they have a single neighbor or no neighbor at all.
135
- """
136
-
137
- img = F.pad(img, (1, 1, 1, 1, 1, 1))
138
-
139
- # Check that number of ones in twentysix-neighborhood is exactly 0 or 1
140
- K = torch.tensor([[[1.0, 1.0, 1.0],
141
- [1.0, 1.0, 1.0],
142
- [1.0, 1.0, 1.0]],
143
- [[1.0, 1.0, 1.0],
144
- [1.0, 0.0, 1.0],
145
- [1.0, 1.0, 1.0]],
146
- [[1.0, 1.0, 1.0],
147
- [1.0, 1.0, 1.0],
148
- [1.0, 1.0, 1.0]]], device=img.device).view(1, 1, 3, 3, 3)
149
-
150
- num_twentysix_neighbors = F.conv3d(img, K)
151
- condition1 = F.hardtanh(-(num_twentysix_neighbors - 2), min_val=0, max_val=1) # 1 or fewer neigbors
152
-
153
- return condition1
154
-
155
-
156
- def _boolean_simple_check(self, img):
157
- """
158
- Function that identifies simple points using Boolean conditions introduced by Bertrand et al. [1].
159
- Each Boolean conditions can be assessed via convolutions with a limited number of pre-defined kernels.
160
- It total, four conditions are checked. If any one is fulfilled, the point is deemed simple.
161
-
162
- [1] Gilles Bertrand. A boolean characterization of three- dimensional simple points.
163
- Pattern recognition letters, 17(2):115-124, 1996.
164
- """
165
-
166
- img = F.pad(img, (1, 1, 1, 1, 1, 1), value=0)
167
-
168
- # Condition 1: number of zeros in the six-neighborhood is exactly 1
169
- K_N6 = torch.tensor([[[0.0, 0.0, 0.0],
170
- [0.0, 1.0, 0.0],
171
- [0.0, 0.0, 0.0]],
172
- [[0.0, 1.0, 0.0],
173
- [1.0, 0.0, 1.0],
174
- [0.0, 1.0, 0.0]],
175
- [[0.0, 0.0, 0.0],
176
- [0.0, 1.0, 0.0],
177
- [0.0, 0.0, 0.0]]], device=img.device).view(1, 1, 3, 3, 3)
178
-
179
- num_six_neighbors = F.conv3d(1 - img, K_N6, stride=2)
180
-
181
- subcondition1a = F.hardtanh(num_six_neighbors, min_val=0, max_val=1) # 1 or more neighbors
182
- subcondition1b = F.hardtanh(-(num_six_neighbors - 2), min_val=0, max_val=1) # 1 or fewer neighbors
183
-
184
- condition1 = subcondition1a * subcondition1b
185
-
186
-
187
- # Condition 2: number of ones in twentysix-neighborhood is exactly 1
188
- K_N26 = torch.tensor([[[1.0, 1.0, 1.0],
189
- [1.0, 1.0, 1.0],
190
- [1.0, 1.0, 1.0]],
191
- [[1.0, 1.0, 1.0],
192
- [1.0, 0.0, 1.0],
193
- [1.0, 1.0, 1.0]],
194
- [[1.0, 1.0, 1.0],
195
- [1.0, 1.0, 1.0],
196
- [1.0, 1.0, 1.0]]], device=img.device).view(1, 1, 3, 3, 3)
197
-
198
- num_twentysix_neighbors = F.conv3d(img, K_N26, stride=2)
199
-
200
- subcondition2a = F.hardtanh(num_twentysix_neighbors, min_val=0, max_val=1) # 1 or more neighbors
201
- subcondition2b = F.hardtanh(-(num_twentysix_neighbors - 2), min_val=0, max_val=1) # 1 or fewer neigbors
202
-
203
- condition2 = subcondition2a * subcondition2b
204
-
205
-
206
- # Condition 3: Number of ones in eighteen-neigborhood exactly 1...
207
- K_N18 = torch.tensor([[[0.0, 1.0, 0.0],
208
- [1.0, 1.0, 1.0],
209
- [0.0, 1.0, 0.0]],
210
- [[1.0, 1.0, 1.0],
211
- [1.0, 0.0, 1.0],
212
- [1.0, 1.0, 1.0]],
213
- [[0.0, 1.0, 0.0],
214
- [1.0, 1.0, 1.0],
215
- [0.0, 1.0, 0.0]]], device=img.device).view(1, 1, 3, 3, 3)
216
-
217
- num_eighteen_neighbors = F.conv3d(img, K_N18, stride=2)
218
-
219
- subcondition3a = F.hardtanh(num_eighteen_neighbors, min_val=0, max_val=1) # 1 or more neighbors
220
- subcondition3b = F.hardtanh(-(num_eighteen_neighbors - 2), min_val=0, max_val=1) # 1 or fewer neigbors
221
-
222
- # ... and cell configration B26 does not exist
223
- K_B26 = torch.tensor([[[1.0, -1.0, 0.0],
224
- [-1.0, -1.0, 0.0],
225
- [0.0, 0.0, 0.0]],
226
- [[-1.0, -1.0, 0.0],
227
- [-1.0, 0.0, 0.0],
228
- [0.0, 0.0, 0.0]],
229
- [[0.0, 0.0, 0.0],
230
- [0.0, 0.0, 0.0],
231
- [0.0, 0.0, 0.0]]], device=img.device).view(1, 1, 3, 3, 3)
232
-
233
- B26_1_present = F.relu(F.conv3d(2.0 * img - 1.0, K_B26, stride=2) - 6)
234
- B26_2_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.flip(K_B26, dims=[2]), stride=2) - 6)
235
- B26_3_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.flip(K_B26, dims=[3]), stride=2) - 6)
236
- B26_4_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.flip(K_B26, dims=[4]), stride=2) - 6)
237
- B26_5_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.flip(K_B26, dims=[2, 3]), stride=2) - 6)
238
- B26_6_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.flip(K_B26, dims=[2, 4]), stride=2) - 6)
239
- B26_7_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.flip(K_B26, dims=[3, 4]), stride=2) - 6)
240
- B26_8_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.flip(K_B26, dims=[2, 3, 4]), stride=2) - 6)
241
- num_B26_cells = B26_1_present + B26_2_present + B26_3_present + B26_4_present + B26_5_present + B26_6_present + B26_7_present + B26_8_present
242
-
243
- subcondition3c = F.hardtanh(-(num_B26_cells - 1), min_val=0, max_val=1)
244
-
245
- condition3 = subcondition3a * subcondition3b * subcondition3c
246
-
247
-
248
- # Condition 4: cell configuration A6 does not exist...
249
- K_A6 = torch.tensor([[[0.0, 1.0, 0.0],
250
- [1.0, -1.0, 1.0],
251
- [0.0, 1.0, 0.0]],
252
- [[0.0, 0.0, 0.0],
253
- [0.0, 0.0, 0.0],
254
- [0.0, 0.0, 0.0]],
255
- [[0.0, 0.0, 0.0],
256
- [0.0, 0.0, 0.0],
257
- [0.0, 0.0, 0.0]]], device=img.device).view(1, 1, 3, 3, 3)
258
-
259
- A6_1_present = F.relu(F.conv3d(2.0 * img - 1.0, K_A6, stride=2) - 4)
260
- A6_2_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.rot90(K_A6, dims=[2, 3]), stride=2) - 4)
261
- A6_3_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.rot90(K_A6, dims=[2, 4]), stride=2) - 4)
262
- A6_4_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.flip(K_A6, dims=[2]), stride=2) - 4)
263
- A6_5_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.rot90(torch.flip(K_A6, dims=[2]), dims=[2, 3]), stride=2) - 4)
264
- A6_6_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.rot90(torch.flip(K_A6, dims=[2]), dims=[2, 4]), stride=2) - 4)
265
- num_A6_cells = A6_1_present + A6_2_present + A6_3_present + A6_4_present + A6_5_present + A6_6_present
266
-
267
- subcondition4a = F.hardtanh(-(num_A6_cells - 1), min_val=0, max_val=1)
268
-
269
- # ... and cell configuration B26 does not exist...
270
- K_B26 = torch.tensor([[[1.0, -1.0, 0.0],
271
- [-1.0, -1.0, 0.0],
272
- [0.0, 0.0, 0.0]],
273
- [[-1.0, -1.0, 0.0],
274
- [-1.0, 0.0, 0.0],
275
- [0.0, 0.0, 0.0]],
276
- [[0.0, 0.0, 0.0],
277
- [0.0, 0.0, 0.0],
278
- [0.0, 0.0, 0.0]]], device=img.device).view(1, 1, 3, 3, 3)
279
-
280
- B26_1_present = F.relu(F.conv3d(2.0 * img - 1.0, K_B26, stride=2) - 6)
281
- B26_2_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.flip(K_B26, dims=[2]), stride=2) - 6)
282
- B26_3_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.flip(K_B26, dims=[3]), stride=2) - 6)
283
- B26_4_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.flip(K_B26, dims=[4]), stride=2) - 6)
284
- B26_5_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.flip(K_B26, dims=[2, 3]), stride=2) - 6)
285
- B26_6_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.flip(K_B26, dims=[2, 4]), stride=2) - 6)
286
- B26_7_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.flip(K_B26, dims=[3, 4]), stride=2) - 6)
287
- B26_8_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.flip(K_B26, dims=[2, 3, 4]), stride=2) - 6)
288
- num_B26_cells = B26_1_present + B26_2_present + B26_3_present + B26_4_present + B26_5_present + B26_6_present + B26_7_present + B26_8_present
289
-
290
- subcondition4b = F.hardtanh(-(num_B26_cells - 1), min_val=0, max_val=1)
291
-
292
- # ... and cell configuration B18 does not exist...
293
- K_B18 = torch.tensor([[[0.0, 1.0, 0.0],
294
- [-1.0, -1.0, -1.0],
295
- [0.0, 0.0, 0.0]],
296
- [[-1.0, -1.0, -1.0],
297
- [-1.0, 0.0, -1.0],
298
- [0.0, 0.0, 0.0]],
299
- [[0.0, 0.0, 0.0],
300
- [0.0, 0.0, 0.0],
301
- [0.0, 0.0, 0.0]]], device=img.device).view(1, 1, 3, 3, 3)
302
-
303
- B18_1_present = F.relu(F.conv3d(2.0 * img - 1.0, K_B18, stride=2) - 8)
304
- B18_2_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.rot90(K_B18, dims=[2, 4]), stride=2) - 8)
305
- B18_3_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.rot90(K_B18, dims=[2, 4], k=2), stride=2) - 8)
306
- B18_4_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.rot90(K_B18, dims=[2, 4], k=3), stride=2) - 8)
307
- B18_5_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.rot90(K_B18, dims=[3, 4]), stride=2) - 8)
308
- B18_6_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.rot90(torch.rot90(K_B18, dims=[3, 4]), dims=[2, 4]), stride=2) - 8)
309
- B18_7_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.rot90(torch.rot90(K_B18, dims=[3, 4]), dims=[2, 4], k=2), stride=2) - 8)
310
- B18_8_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.rot90(torch.rot90(K_B18, dims=[3, 4]), dims=[2, 4], k=3), stride=2) - 8)
311
- B18_9_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.rot90(K_B18, dims=[3, 4], k=2), stride=2) - 8)
312
- B18_10_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.rot90(torch.rot90(K_B18, dims=[3, 4], k=2), dims=[2, 4]), stride=2) - 8)
313
- B18_11_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.rot90(torch.rot90(K_B18, dims=[3, 4], k=2), dims=[2, 4], k=2), stride=2) - 8)
314
- B18_12_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.rot90(torch.rot90(K_B18, dims=[3, 4], k=2), dims=[2, 4], k=3), stride=2) - 8)
315
- num_B18_cells = B18_1_present + B18_2_present + B18_3_present + B18_4_present + B18_5_present + B18_6_present + B18_7_present + B18_8_present + B18_9_present + B18_10_present + B18_11_present + B18_12_present
316
-
317
- subcondition4c = F.hardtanh(-(num_B18_cells - 1), min_val=0, max_val=1)
318
-
319
- # ... and the number of zeros in the six-neighborhood minus the number of A18 cell configurations plus the number of A26 cell configurations is exactly one
320
- K_N6 = torch.tensor([[[0.0, 0.0, 0.0],
321
- [0.0, 1.0, 0.0],
322
- [0.0, 0.0, 0.0]],
323
- [[0.0, 1.0, 0.0],
324
- [1.0, 0.0, 1.0],
325
- [0.0, 1.0, 0.0]],
326
- [[0.0, 0.0, 0.0],
327
- [0.0, 1.0, 0.0],
328
- [0.0, 0.0, 0.0]]], device=img.device).view(1, 1, 3, 3, 3)
329
-
330
- num_six_neighbors = F.conv3d(1-img, K_N6, stride=2)
331
-
332
- K_A18 = torch.tensor([[[0.0, -1.0, 0.0],
333
- [0.0, -1.0, 0.0],
334
- [0.0, 0.0, 0.0]],
335
- [[0.0, -1.0, 0.0],
336
- [0.0, 0.0, 0.0],
337
- [0.0, 0.0, 0.0]],
338
- [[0.0, 0.0, 0.0],
339
- [0.0, 0.0, 0.0],
340
- [0.0, 0.0, 0.0]]], device=img.device).view(1, 1, 3, 3, 3)
341
-
342
- A18_1_present = F.relu(F.conv3d(2.0 * img - 1.0, K_A18, stride=2) - 2)
343
- A18_2_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.rot90(K_A18, dims=[2, 4]), stride=2) - 2)
344
- A18_3_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.rot90(K_A18, dims=[2, 4], k=2), stride=2) - 2)
345
- A18_4_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.rot90(K_A18, dims=[2, 4], k=3), stride=2) - 2)
346
- A18_5_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.rot90(K_A18, dims=[3, 4]), stride=2) - 2)
347
- A18_6_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.rot90(torch.rot90(K_A18, dims=[3, 4]), dims=[2, 4]), stride=2) - 2)
348
- A18_7_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.rot90(torch.rot90(K_A18, dims=[3, 4]), dims=[2, 4], k=2), stride=2) - 2)
349
- A18_8_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.rot90(torch.rot90(K_A18, dims=[3, 4]), dims=[2, 4], k=3), stride=2) - 2)
350
- A18_9_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.rot90(K_A18, dims=[3, 4], k=2), stride=2) - 2)
351
- A18_10_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.rot90(torch.rot90(K_A18, dims=[3, 4], k=2), dims=[2, 4]), stride=2) - 2)
352
- A18_11_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.rot90(torch.rot90(K_A18, dims=[3, 4], k=2), dims=[2, 4], k=2), stride=2) - 2)
353
- A18_12_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.rot90(torch.rot90(K_A18, dims=[3, 4], k=2), dims=[2, 4], k=3), stride=2) - 2)
354
- num_A18_cells = A18_1_present + A18_2_present + A18_3_present + A18_4_present + A18_5_present + A18_6_present + A18_7_present + A18_8_present + A18_9_present + A18_10_present + A18_11_present + A18_12_present
355
-
356
- K_A26 = torch.tensor([[[-1.0, -1.0, 0.0],
357
- [-1.0, -1.0, 0.0],
358
- [0.0, 0.0, 0.0]],
359
- [[-1.0, -1.0, 0.0],
360
- [-1.0, 0.0, 0.0],
361
- [0.0, 0.0, 0.0]],
362
- [[0.0, 0.0, 0.0],
363
- [0.0, 0.0, 0.0],
364
- [0.0, 0.0, 0.0]]], device=img.device).view(1, 1, 3, 3, 3)
365
-
366
- A26_1_present = F.relu(F.conv3d(2.0 * img - 1.0, K_A26, stride=2) - 6)
367
- A26_2_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.flip(K_A26, dims=[2]), stride=2) - 6)
368
- A26_3_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.flip(K_A26, dims=[3]), stride=2) - 6)
369
- A26_4_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.flip(K_A26, dims=[4]), stride=2) - 6)
370
- A26_5_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.flip(K_A26, dims=[2, 3]), stride=2) - 6)
371
- A26_6_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.flip(K_A26, dims=[2, 4]), stride=2) - 6)
372
- A26_7_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.flip(K_A26, dims=[3, 4]), stride=2) - 6)
373
- A26_8_present = F.relu(F.conv3d(2.0 * img - 1.0, torch.flip(K_A26, dims=[2, 3, 4]), stride=2) - 6)
374
- num_A26_cells = A26_1_present + A26_2_present + A26_3_present + A26_4_present + A26_5_present + A26_6_present + A26_7_present + A26_8_present
375
-
376
- subcondition4d = F.hardtanh(num_six_neighbors - num_A18_cells + num_A26_cells, min_val=0, max_val=1) # 1 or more configurations
377
- subcondition4e = F.hardtanh(-(num_six_neighbors - num_A18_cells + num_A26_cells - 2), min_val=0, max_val=1) # 1 or fewer configurations
378
-
379
- condition4 = subcondition4a * subcondition4b * subcondition4c * subcondition4d * subcondition4e
380
-
381
- # If any of the four conditions is fulfilled the point is simple
382
- combined = torch.cat([condition1, condition2, condition3, condition4], dim=1)
383
- is_simple = torch.amax(combined, dim=1, keepdim=True)
384
-
385
- return is_simple
386
-
387
-
388
- # Specifically designed to be used with the eight-subfield iterative scheme from above.
389
- def _euler_characteristic_simple_check(self, img):
390
- """
391
- Function that identifies simple points by assessing whether the Euler characteristic changes when deleting it [1].
392
- In order to calculate the Euler characteristic, the amount of vertices, edges, faces and octants are counted using convolutions with pre-defined kernels.
393
- The function is meant to be used in combination with the subfield-based iterative scheme employed in the forward function.
394
-
395
- [1] Steven Lobregt et al. Three-dimensional skeletonization:principle and algorithm.
396
- IEEE Transactions on pattern analysis and machine intelligence, 2(1):75-77, 1980.
397
- """
398
-
399
- img = F.pad(img, (1, 1, 1, 1, 1, 1), value=0)
400
-
401
- # Create masked version of the image where the center of 26-neighborhoods is changed to zero
402
- mask = torch.ones_like(img)
403
- mask[:, :, 1::2, 1::2, 1::2] = 0
404
- masked_img = img.clone() * mask
405
-
406
- # Count vertices
407
- vertices = F.relu(-(2.0 * img - 1.0))
408
- num_vertices = F.avg_pool3d(vertices, (3, 3, 3), stride=2) * 27
409
-
410
- masked_vertices = F.relu(-(2.0 * masked_img - 1.0))
411
- num_masked_vertices = F.avg_pool3d(masked_vertices, (3, 3, 3), stride=2) * 27
412
-
413
- # Count edges
414
- K_ud_edge = torch.tensor([0.5, 0.5], device=img.device).view(1, 1, 2, 1, 1)
415
- K_ns_edge = torch.tensor([0.5, 0.5], device=img.device).view(1, 1, 1, 2, 1)
416
- K_we_edge = torch.tensor([0.5, 0.5], device=img.device).view(1, 1, 1, 1, 2)
417
-
418
- ud_edges = F.relu(F.conv3d(-(2.0 * img - 1.0), K_ud_edge))
419
- num_ud_edges = F.avg_pool3d(ud_edges, (2, 3, 3), stride=2) * 18
420
- ns_edges = F.relu(F.conv3d(-(2.0 * img - 1.0), K_ns_edge))
421
- num_ns_edges = F.avg_pool3d(ns_edges, (3, 2, 3), stride=2) * 18
422
- we_edges = F.relu(F.conv3d(-(2.0 * img - 1.0), K_we_edge))
423
- num_we_edges = F.avg_pool3d(we_edges, (3, 3, 2), stride=2) * 18
424
- num_edges = num_ud_edges + num_ns_edges + num_we_edges
425
-
426
- masked_ud_edges = F.relu(F.conv3d(-(2.0 * masked_img - 1.0), K_ud_edge))
427
- num_masked_ud_edges = F.avg_pool3d(masked_ud_edges, (2, 3, 3), stride=2) * 18
428
- masked_ns_edges = F.relu(F.conv3d(-(2.0 * masked_img - 1.0), K_ns_edge))
429
- num_masked_ns_edges = F.avg_pool3d(masked_ns_edges, (3, 2, 3), stride=2) * 18
430
- masked_we_edges = F.relu(F.conv3d(-(2.0 * masked_img - 1.0), K_we_edge))
431
- num_masked_we_edges = F.avg_pool3d(masked_we_edges, (3, 3, 2), stride=2) * 18
432
- num_masked_edges = num_masked_ud_edges + num_masked_ns_edges + num_masked_we_edges
433
-
434
- # Count faces
435
- K_ud_face = torch.tensor([[0.25, 0.25], [0.25, 0.25]], device=img.device).view(1, 1, 1, 2, 2)
436
- K_ns_face = torch.tensor([[0.25, 0.25], [0.25, 0.25]], device=img.device).view(1, 1, 2, 1, 2)
437
- K_we_face = torch.tensor([[0.25, 0.25], [0.25, 0.25]], device=img.device).view(1, 1, 2, 2, 1)
438
-
439
- ud_faces = F.relu(F.conv3d(-(2.0 * img - 1.0), K_ud_face) - 0.5) * 2
440
- num_ud_faces = F.avg_pool3d(ud_faces, (3, 2, 2), stride=2) * 12
441
- ns_faces = F.relu(F.conv3d(-(2.0 * img - 1.0), K_ns_face) - 0.5) * 2
442
- num_ns_faces = F.avg_pool3d(ns_faces, (2, 3, 2), stride=2) * 12
443
- we_faces = F.relu(F.conv3d(-(2.0 * img - 1.0), K_we_face) - 0.5) * 2
444
- num_we_faces = F.avg_pool3d(we_faces, (2, 2, 3), stride=2) * 12
445
- num_faces = num_ud_faces + num_ns_faces + num_we_faces
446
-
447
- masked_ud_faces = F.relu(F.conv3d(-(2.0 * masked_img - 1.0), K_ud_face) - 0.5) * 2
448
- num_masked_ud_faces = F.avg_pool3d(masked_ud_faces, (3, 2, 2), stride=2) * 12
449
- masked_ns_faces = F.relu(F.conv3d(-(2.0 * masked_img - 1.0), K_ns_face) - 0.5) * 2
450
- num_masked_ns_faces = F.avg_pool3d(masked_ns_faces, (2, 3, 2), stride=2) * 12
451
- masked_we_faces = F.relu(F.conv3d(-(2.0 * masked_img - 1.0), K_we_face) - 0.5) * 2
452
- num_masked_we_faces = F.avg_pool3d(masked_we_faces, (2, 2, 3), stride=2) * 12
453
- num_masked_faces = num_masked_ud_faces + num_masked_ns_faces + num_masked_we_faces
454
-
455
- # Count octants
456
- K_octants = torch.tensor([[[0.125, 0.125], [0.125, 0.125]], [[0.125, 0.125], [0.125, 0.125]]], device=img.device).view(1, 1, 2, 2, 2)
457
-
458
- octants = F.relu(F.conv3d(-(2.0 * img - 1.0), K_octants) - 0.75) * 4
459
- num_octants = F.avg_pool3d(octants, (2, 2, 2), stride=2) * 8
460
-
461
- masked_octants = F.relu(F.conv3d(-(2.0 * masked_img - 1.0), K_octants) - 0.75) * 4
462
- num_masked_octants = F.avg_pool3d(masked_octants, (2, 2, 2), stride=2) * 8
463
-
464
- # Combined number of vertices, edges, faces and octants to calculate the euler characteristic
465
- euler_characteristic = num_vertices - num_edges + num_faces - num_octants
466
- masked_euler_characteristic = num_masked_vertices - num_masked_edges + num_masked_faces - num_masked_octants
467
-
468
- # If the Euler characteristic is unchanged after switching a point from 1 to 0 this indicates that the point is simple
469
- euler_change = F.hardtanh(torch.abs(masked_euler_characteristic - euler_characteristic), min_val=0, max_val=1)
470
- is_simple = 1 - euler_change
471
- is_simple = (is_simple.detach() > 0.5).float() - is_simple.detach() + is_simple
472
-
473
- return is_simple
474
-
475
-
476
- def _prepare_output(self, img):
477
- """
478
- Function that removes the padding and dimensions added by _prepare_input function.
479
- """
480
-
481
- img = img[:, :, 1:-1, 1:-1, 1:-1]
482
-
483
- if self.expanded_dims:
484
- img = torch.squeeze(img, dim=2)
485
-
486
- return img
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
util/tools.py DELETED
@@ -1,143 +0,0 @@
1
- '''
2
- Author: Jintao Li
3
- Date: 2022-05-30 16:42:14
4
- LastEditors: Jintao Li
5
- LastEditTime: 2022-07-11 23:05:53
6
- 2022 by CIG.
7
- '''
8
-
9
- import os, shutil
10
- import yaml, argparse
11
- from sklearn.metrics import confusion_matrix
12
- import numpy as np
13
- import torch
14
-
15
-
16
- def accuracy(output, target):
17
- '''
18
- output: [N, num_classes, ...], torch.float
19
- target: [N, ...], torch.int
20
- '''
21
- output = output.argmax(dim=1).flatten().detach().cpu().numpy()
22
- target = target.flatten().detach().cpu().numpy()
23
- return pixel_acc(output, target), _miou(output, target)
24
-
25
-
26
- def pixel_acc(output, target):
27
- r"""
28
- 计算像素准确率 (Pixel Accuracy, PA)
29
- $$ PA = \frac{\sum_{i=0}^k p_{ii}}
30
- {\sum_{i=0}^k \sum_{j=0}^k p_{ij}} $$ and
31
- $n_class = k+1$
32
- Parameters:
33
- -----------
34
- shape: [N, ], (use flatten() function)
35
- return:
36
- ----------
37
- - PA
38
- """
39
- assert output.shape == target.shape, "shapes must be same"
40
- cm = confusion_matrix(target, output)
41
- return np.diag(cm).sum() / cm.sum()
42
-
43
-
44
- def _miou(output, target):
45
- r"""
46
- 计算均值交并比 MIoU (Mean Intersection over Union)
47
- $$ MIoU = \frac{1}{k+1} \sum_{i=0}^k \frac{p_{ii}}
48
- {\sum_{j=0}^k p_{ij} + \sum_{j=0}^k p_{ji} - p_{ii}} $$
49
- Parameters:
50
- output, target: [N, ]
51
- return:
52
- MIoU
53
- """
54
- assert output.shape == target.shape, "shapes must be same"
55
- cm = confusion_matrix(target, output)
56
- intersection = np.diag(cm)
57
- union = np.sum(cm, 1) + np.sum(cm, 0) - np.diag(cm)
58
- iou = intersection / union
59
- miou = np.nanmean(iou)
60
-
61
- return miou
62
-
63
-
64
- def yaml_config_hook(config_file: str) -> argparse.Namespace:
65
- """
66
- 加载yaml文件里面的参数配置, 并生成argparse形式的参数集合
67
- """
68
- with open(config_file) as f:
69
- cfg = yaml.safe_load(f)
70
- for d in cfg.get("defaults", []):
71
- config_dir, cf = d.popitem()
72
- cf = os.path.join(os.path.dirname(config_file), config_dir,
73
- cf + ".yaml")
74
- with open(cf) as f:
75
- l = yaml.safe_load(f)
76
- cfg.update(l)
77
-
78
- if "defaults" in cfg.keys():
79
- del cfg["defaults"]
80
-
81
- parser = argparse.ArgumentParser()
82
- for k, v in cfg.items():
83
- parser.add_argument(f"--{k}", default=v, type=type(v))
84
- args = parser.parse_args()
85
-
86
- return args
87
-
88
-
89
- def backup_code(work_dir, back_dir, exceptions=[], include=[]):
90
- r"""
91
- 备份本次运行的代码到指定目录下, 并排除某些文件和目录
92
-
93
- Args:
94
- work_dir: 工作目录, i.e. 需要备份的代码
95
- back_dir: 目标目录.备份代码放置的目录
96
- exception (list): 被排除的目录和以指定后缀结尾的文件, 默认的有
97
- ["__pycache__", ".pyc", ".dat", "backup", ".vscode"]
98
- include (list): 某些必须被备份的文件,该文件可能在exception里面
99
- """
100
- _exp = [
101
- "*__pycache__*", "*.pyc", "*.dat", "backup", ".vscode", "*.log",
102
- "*log*"
103
- ]
104
- exceptions = exceptions + _exp
105
-
106
- # if not os.path.exists(back_dir):
107
- os.makedirs(back_dir, exist_ok=True)
108
-
109
- shutil.copytree(work_dir,
110
- back_dir + 'code/',
111
- ignore=shutil.ignore_patterns(*exceptions),
112
- dirs_exist_ok=True)
113
-
114
- for f in include:
115
- shutil.copyfile(os.path.join(work_dir, f),
116
- os.path.join(back_dir + 'code', f))
117
-
118
-
119
- def list_files(path, full=False):
120
- r"""
121
- 递归列出目录下所有的文件,包括子目录下的文件
122
- """
123
- out = []
124
- for f in os.listdir(path):
125
- fname = os.path.join(path, f)
126
- if os.path.isdir(fname):
127
- fname = list_files(fname)
128
- out += [os.path.join(f, i) for i in fname]
129
- else:
130
- out.append(f)
131
- if full:
132
- out = [os.path.join(path, i) for i in out]
133
- return out
134
-
135
-
136
- if __name__ == "__main__":
137
- output = torch.randn(4, 2, 6, 6)
138
- target = torch.randn(4, 2, 6, 6)
139
- # output = output.cuda()
140
- # target = target.cuda()
141
- target = target.argmax(1)
142
-
143
- accuracy(output, target)