Computes `n_samples` of random patch sampling locations, given the sampling weight map `w` and patch `spatial_size`. Args: spatial_size: length of each spatial dimension of the patch. w: weight map, the weights must be non-negative. each element denotes a sampling weight of
(
spatial_size: int | Sequence[int],
w: NdarrayOrTensor,
n_samples: int = 1,
r_state: np.random.RandomState | None = None,
)
| 545 | |
| 546 | |
| 547 | def weighted_patch_samples( |
| 548 | spatial_size: int | Sequence[int], |
| 549 | w: NdarrayOrTensor, |
| 550 | n_samples: int = 1, |
| 551 | r_state: np.random.RandomState | None = None, |
| 552 | ) -> list: |
| 553 | """ |
| 554 | Computes `n_samples` of random patch sampling locations, given the sampling weight map `w` and patch `spatial_size`. |
| 555 | |
| 556 | Args: |
| 557 | spatial_size: length of each spatial dimension of the patch. |
| 558 | w: weight map, the weights must be non-negative. each element denotes a sampling weight of the spatial location. |
| 559 | 0 indicates no sampling. |
| 560 | The weight map shape is assumed ``(spatial_dim_0, spatial_dim_1, ..., spatial_dim_n)``. |
| 561 | n_samples: number of patch samples |
| 562 | r_state: a random state container |
| 563 | |
| 564 | Returns: |
| 565 | a list of `n_samples` N-D integers representing the spatial sampling location of patches. |
| 566 | |
| 567 | """ |
| 568 | check_non_lazy_pending_ops(w, name="weighted_patch_samples") |
| 569 | if w is None: |
| 570 | raise ValueError("w must be an ND array, got None.") |
| 571 | if r_state is None: |
| 572 | r_state = np.random.RandomState() |
| 573 | img_size = np.asarray(w.shape, dtype=int) |
| 574 | win_size = np.asarray(fall_back_tuple(spatial_size, img_size), dtype=int) |
| 575 | |
| 576 | s = tuple(slice(w // 2, m - w + w // 2) if m > w else slice(m // 2, m // 2 + 1) for w, m in zip(win_size, img_size)) |
| 577 | v = w[s] # weight map in the 'valid' mode |
| 578 | v_size = v.shape |
| 579 | v = ravel(v) # always copy |
| 580 | if (v < 0).any(): |
| 581 | v -= v.min() # shifting to non-negative |
| 582 | v = cumsum(v) |
| 583 | if not v[-1] or not isfinite(v[-1]) or v[-1] < 0: # uniform sampling |
| 584 | idx = r_state.randint(0, len(v), size=n_samples) |
| 585 | else: |
| 586 | r_samples = r_state.random(n_samples) |
| 587 | r, *_ = convert_to_dst_type(r_samples, v, dtype=r_samples.dtype) |
| 588 | idx = searchsorted(v, r * v[-1], right=True) # type: ignore |
| 589 | idx, *_ = convert_to_dst_type(idx, v, dtype=torch.int) # type: ignore |
| 590 | # compensate 'valid' mode |
| 591 | diff = np.minimum(win_size, img_size) // 2 |
| 592 | diff, *_ = convert_to_dst_type(diff, v) # type: ignore |
| 593 | return [unravel_index(i, v_size) + diff for i in idx] |
| 594 | |
| 595 | |
| 596 | def correct_crop_centers( |
no test coverage detected
searching dependent graphs…