Skip to content

Issue with RandCropByPosNegLabeld #7688

@tararelan

Description

@tararelan

Describe the bug
I'm trying to check the images after they've been loaded using the following code:

train_transforms = Compose(
    [
        LoadImaged(keys=["image", "label"]),
        EnsureChannelFirstd(keys=["image", "label"]),
        ScaleIntensityRanged(
            keys=["image"],
            a_min=-57,
            a_max=164,
            b_min=0.0,
            b_max=1.0,
            clip=True,
        ),
        CropForegroundd(keys=["image", "label"], source_key="image"),
        Orientationd(keys=["image", "label"], axcodes="RAS"),
        Spacingd(keys=["image", "label"], pixdim=(1.5, 1.5, 2.0), mode=("bilinear", "nearest")),
        RandCropByPosNegLabeld(
            keys=["image", "label"],
            label_key="label",
            spatial_size=(96, 96, 96),
            pos=1,
            neg=1,
            num_samples=4,
            image_key="image",
            image_threshold=0,
            allow_smaller=True,
        ),
        ResizeWithPadOrCrop(spatial_size=(96, 96, 96)),
    ]
)

class ColonCT_Dataset(Dataset):
    def __init__(self, dataset_path, transform=None):
        self.data=dataset_path
        self.transform=transform

    def __len__(self):
        return len(self.data)

    def __getitem__(self, idx):
        data_dict = self.data[idx]
        if self.transform:
            data_dict = self.transform(data_dict)
        return data_dict

train_ds = ColonCT_Dataset(train_data_dicts, train_transforms)
train_loader = DataLoader(train_ds, batch_size=1, shuffle=True, collate_fn=pad_list_data_collate)

check_iter = iter(train_loader)
print(train_loader.dataset.data[0]['image'])
check_data = next(check_iter)

image, label = check_data["image"].squeeze().numpy(), check_data["label"].squeeze().numpy()
print(f"image shape: {image.shape}, label shape: {label.shape}")

for i in range(image.shape[3]):
    plt.subplot(1, 2, 1)
    plt.title("Image - Slice {}".format(i))
    plt.imshow(image[0, :, :, i], cmap="gray")

    plt.subplot(1, 2, 2)
    plt.title("Label - Slice {}".format(i))
    plt.imshow(label[0, :, :, i])

    plt.show()

However, I receive the following error:

RuntimeError Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/monai/transforms/transform.py in apply_transform(transform, data, map_items, unpack_items, log_stats, lazy, overrides)
140 return [_apply_transform(transform, item, unpack_items, lazy, overrides, log_stats) for item in data]
--> 141 return _apply_transform(transform, data, unpack_items, lazy, overrides, log_stats)
142 except Exception as e:

15 frames
RuntimeError: The size of tensor a (7663256) must match the size of tensor b (4919040) at non-singleton dimension 0

The above exception was the direct cause of the following exception:

RuntimeError Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/monai/transforms/transform.py in apply_transform(transform, data, map_items, unpack_items, log_stats, lazy, overrides)
169 else:
170 _log_stats(data=data)
--> 171 raise RuntimeError(f"applying transform {transform}") from e
172
173

RuntimeError: applying transform <monai.transforms.croppad.dictionary.RandCropByPosNegLabeld object at 0x7c03133b0fa0>

Expected behavior
I expect to get images of each slice of the CT scan.

Environment

2024-04-21 12:41:30.215041: E external/local_xla/xla/stream_executor/cuda/cuda_dnn.cc:9261] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered
2024-04-21 12:41:30.215128: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:607] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered
2024-04-21 12:41:30.217856: E external/local_xla/xla/stream_executor/cuda/cuda_blas.cc:1515] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered
2024-04-21 12:41:31.763248: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT
================================
Printing MONAI config...
================================
MONAI version: 1.3.0
Numpy version: 1.25.2
Pytorch version: 2.2.1+cu121
MONAI flags: HAS_EXT = False, USE_COMPILED = False, USE_META_DICT = False
MONAI rev id: 865972f7a791bf7b42efbcd87c8402bd865b329e
MONAI __file__: /usr/local/lib/python3.10/dist-packages/monai/__init__.py

Optional dependencies:
Pytorch Ignite version: NOT INSTALLED or UNKNOWN VERSION.
ITK version: NOT INSTALLED or UNKNOWN VERSION.
Nibabel version: 4.0.2
scikit-image version: 0.19.3
scipy version: 1.11.4
Pillow version: 9.4.0
Tensorboard version: 2.15.2
gdown version: 4.7.3
TorchVision version: 0.17.1+cu121
tqdm version: 4.66.2
lmdb version: NOT INSTALLED or UNKNOWN VERSION.
psutil version: 5.9.5
pandas version: 2.0.3
einops version: NOT INSTALLED or UNKNOWN VERSION.
transformers version: 4.38.2
mlflow version: NOT INSTALLED or UNKNOWN VERSION.
pynrrd version: NOT INSTALLED or UNKNOWN VERSION.
clearml version: NOT INSTALLED or UNKNOWN VERSION.

For details about installing the optional dependencies, please visit:
    https://docs.monai.io/en/latest/installation.html#installing-the-recommended-dependencies


================================
Printing system config...
================================
System: Linux
Linux version: Ubuntu 22.04.3 LTS
Platform: Linux-6.1.58+-x86_64-with-glibc2.35
Processor: x86_64
Machine: x86_64
Python version: 3.10.12
Process name: python3
Command: ['python3', '-c', 'import monai; monai.config.print_debug_info()']
Open files: []
Num physical CPUs: 4
Num logical CPUs: 8
Num usable CPUs: 8
CPU usage (%): [29.0, 7.8, 5.9, 6.2, 10.4, 69.4, 11.7, 14.8]
CPU freq. (MHz): 2200
Load avg. in last 1, 5, 15 mins (%): [7.8, 7.3, 6.0]
Disk usage (%): 55.7
Avg. sensor temp. (Celsius): UNKNOWN for given OS
Total physical memory (GB): 51.0
Available memory (GB): 47.8
Used memory (GB): 2.6

================================
Printing GPU config...
================================
Num GPUs: 0
Has CUDA: False
cuDNN enabled: True
NVIDIA_TF32_OVERRIDE: None
TORCH_ALLOW_TF32_CUBLAS_OVERRIDE: None
cuDNN version: 8902

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions