Project-MONAI / MONAI

AI Toolkit for Healthcare Imaging
https://monai.io/
Apache License 2.0
5.5k stars 1.01k forks source link

RandCropByPosNegLabeld wrong output format #7817

Closed alegiuppy closed 3 weeks ago

alegiuppy commented 4 weeks ago

I'm trying to load my validation set. Initially, I was using CenterSpatialCropd in my set of transformations and everything worked well. Then, I tried to substitute this transform with RandCropByPosNegLabeld, since it fits my work better, but now, instead of having a list of dictionaries when I define the dataset, I have a list of lists. Below is the code for the definition of the transforms:

val_transforms=transforms.Compose([
    transforms.LoadImaged(keys=["image","label"]), 
    transforms.EnsureChannelFirstd(keys=["image","label"]), 
    transforms.EnsureTyped(keys=["image", "label"]),
    transforms.Orientationd(keys=["image","label"], axcodes="RAS"),
    transforms.Spacingd(keys=["image","label"],pixdim=(1.0,1.0,1.0),mode=("bilinear","nearest")),
    transforms.RandCropByPosNegLabeld(keys=["image","label"],label_key="label",spatial_size=(128,128,128),pos=1,neg=1,num_samples=1,image_key="image",image_threshold=0),
    transforms.ScaleIntensityRangePercentilesd(keys="image",lower=0,upper=99.5,b_min=0,b_max=1),
    transforms.CenterSpatialCropd(keys=["image","label"],roi_size=(128,128,1)),
    transforms.Lambdad(keys=["image","label"], func=lambda x:x.squeeze(-1)),
])

val_data=[train_data_paths[i] for i in val_ind]

val_dataset=CacheDataset(
    data=val_data, 
    transform=val_transforms,
    cache_rate=float(torch.cuda.device_count()) / 4.0,
    num_workers=8,
    progress=True,
)

print(f"Length of validation data: {len(val_dataset)}") 
print(f'Validation image shape {val_dataset[0]["image"].shape}') 
print(f'Validation label shape {val_dataset[0]["label"].shape}')

And here the error

print(f'Validation image shape {val_dataset[0]["image"].shape}') # dimensione prima immagine
TypeError: list indices must be integers or slices, not str
KumoLiu commented 3 weeks ago

Hi @alegiuppy, it will return a list for each data, please try: val_dataset[0][0]["image"].shape

hope it helps, thanks.