Skip to content

random_crop excludes the last valid spatial origin #142

Open

Description

@ktz03

When more than one crop origin is possible, random_crop never chooses the last valid origin along a spatial axis. For example, cropping a 3-by-3 patch from a 4-by-4 image with zero margins always starts at (0, 0), so the final row and column are never included.

import numpy as np
from batchgenerators.augmentations.crop_and_pad_augmentations import random_crop

image = np.arange(1, 17).reshape(1, 1, 4, 4)
np.random.seed(0)
seen = {
    int(random_crop(image, crop_size=3, margins=0)[0][0, 0, -1, -1])
    for _ in range(64)
}
print(seen)  # {11}; the bottom-right crop should also allow 16

In get_lbs_for_random_crop, the exclusive upper bound passed to np.random.randint is data_shape[i+2] - crop_size[i] - margins[i]. That origin is still legal: it leaves exactly the requested margin on the upper side. Adding one to the sampling upper bound includes it.

The same boundary is missing for 3D inputs and positive or negative margins. The existing centered fallback for a single feasible origin or an oversized crop can stay unchanged.

Reproduced on current master (12a397217f95f62b706dd1be86b7b0f50cf24d1d), Windows, Python 3.12.14, NumPy 2.5.4 and SciPy 1.18.1. No training or performance benchmark was run.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions