r"""grid_sample_3d for NCDHW layout
(
data: np.ndarray,
grid: np.ndarray,
method="bilinear",
layout="NCDHW",
padding_mode="zeros",
align_corners=True,
)
| 231 | |
| 232 | |
| 233 | def grid_sample_3d( |
| 234 | data: np.ndarray, |
| 235 | grid: np.ndarray, |
| 236 | method="bilinear", |
| 237 | layout="NCDHW", |
| 238 | padding_mode="zeros", |
| 239 | align_corners=True, |
| 240 | ): |
| 241 | r"""grid_sample_3d for NCDHW layout""" |
| 242 | |
| 243 | assert method in ("bilinear", "nearest"), f"{method} is not supported" |
| 244 | assert layout == "NCDHW" |
| 245 | assert padding_mode in ("zeros", "border", "reflection"), f"{padding_mode} is not supported" |
| 246 | assert len(data.shape) == len(grid.shape) == 5 |
| 247 | |
| 248 | batch, channel = data.shape[:2] |
| 249 | in_depth, in_height, in_width = data.shape[2:] |
| 250 | out_depth, out_height, out_width = grid.shape[2:] |
| 251 | out_shape = [batch, channel, out_depth, out_height, out_width] |
| 252 | out = np.zeros(out_shape) |
| 253 | |
| 254 | def _get_pixel(b, c, d, h, w): |
| 255 | if 0 <= d <= in_depth - 1 and 0 <= h <= in_height - 1 and 0 <= w <= in_width - 1: |
| 256 | return data[b, c, d, h, w] |
| 257 | return 0 |
| 258 | |
| 259 | def _unnormalize(d, h, w): |
| 260 | if align_corners: |
| 261 | new_d = (d + 1) * (in_depth - 1) / 2 |
| 262 | new_h = (h + 1) * (in_height - 1) / 2 |
| 263 | new_w = (w + 1) * (in_width - 1) / 2 |
| 264 | else: |
| 265 | new_d = -0.5 + (d + 1) * in_depth / 2 |
| 266 | new_h = -0.5 + (h + 1) * in_height / 2 |
| 267 | new_w = -0.5 + (w + 1) * in_width / 2 |
| 268 | return (new_d, new_h, new_w) |
| 269 | |
| 270 | def _clip_coordinates(x, size): |
| 271 | return min(max(x, 0), size - 1) |
| 272 | |
| 273 | def _reflect_coordinates(i, size): |
| 274 | def __refelection(i, size, corner_start): |
| 275 | def __reflect(index, size, corner_start): |
| 276 | index_align_corner = abs(corner_start - index) |
| 277 | size_times = index_align_corner // size |
| 278 | even = size_times % 2 == 0 |
| 279 | extra = index_align_corner - size_times * size |
| 280 | return extra + corner_start if even else size - extra + corner_start |
| 281 | |
| 282 | if corner_start <= i <= size + corner_start: |
| 283 | new_i = i |
| 284 | else: |
| 285 | new_i = __reflect(i, size, corner_start) |
| 286 | return new_i |
| 287 | |
| 288 | if align_corners: |
| 289 | x = __refelection(i, size - 1, 0) |
| 290 | else: |
nothing calls this directly
no test coverage detected
searching dependent graphs…