How to confirm the correct shape after image transforms #1000
-
Thank you monaillabel for providing a good training environment and tools, I am a little confused in the custom app training results. The original shape of my image is (height, width, dimensions), but I encountered some problems during the training. I have no problem with the test transforms shape. How can I test the correctness of the transforms in monailabel training? version from docker: monailabel code and datasets link. The base transforms test: from typing import Dict, Hashable, Mapping
import numpy as np
import torch
from monai.config import KeysCollection
from monai.transforms.transform import MapTransform
from monai.data import MetaTensor
from monai.transforms import *
from monai.data import DataLoader, Dataset
class NormalizeLabelsInDatasetd(MapTransform):
def __init__(self, keys: KeysCollection, label_names=None, allow_missing_keys: bool = False):
super().__init__(keys, allow_missing_keys)
self.label_names = label_names
def __call__(self, data: Mapping[Hashable, np.ndarray]) -> Dict[Hashable, np.ndarray]:
d: Dict = dict(data)
for key in self.key_iterator(d):
# Dictionary containing new label numbers
new_label_names = {}
label = MetaTensor(torch.zeros_like(d[key]))
# Making sure the range values and number of labels are the same
for idx, (key_label, val_label) in enumerate(self.label_names.items(), start=1):
if key_label != "background":
new_label_names[key_label] = idx
label[d[key] == val_label] = idx
if key_label == "background":
new_label_names["background"] = 0
d["label_names"] = new_label_names
d[key] = label
return d
_trans = Compose([
LoadImaged(keys=['image','label'], reader="ITKReader"),
NormalizeLabelsInDatasetd(keys='label', label_names={'labels1':1}),
EnsureChannelFirstd(keys=['image','label']),
Orientationd(keys=['image','label'], axcodes='RAS'),
Spacingd(keys=['image','label'], pixdim=(3.32, 3.32, 2.17), mode=('bilinear', 'nearest')),
ScaleIntensityd(keys=['image']),
CropForegroundd(keys=['image','label'],
source_key='image',
select_fn=lambda x:x>0.005,
margin=0,
return_coords=False),
SpatialPadd(keys=['image','label'], spatial_size=(196,196,128))
])
with open('HNC-datasets/cvDataSets/trainCV1.json', 'r') as file:
train_ds = json.load(file)
with open('HNC-datasets/cvDataSets/testCV1.json', 'r') as file:
val_ds = json.load(file)
train_ds.extend(val_ds)
for data in DataLoader(Dataset(train_ds, _trans), batch_size=1):
print(data['image'].shape) Test Results:
Show result: import matplotlib.pyplot as plt
from ipywidgets import interact
def plotImg(img, idx):
fig=plt.figure(figsize=(12,8))
ax=fig.add_subplot(111)
ax.imshow(img[idx], cmap=plt.cm.gray, vmax=img[idx,:,:].max(), vmin=img[idx,:,:].min())
ax.set_axis_off()
outimg = data['image'].squeeze().permute(2,0,1)
interact(lambda idx: plotImg(outimg, idx), idx=(0, outimg.shape[0]-1)) Results of training at monailabel:
If I add RandSpatialCropd(
keys=['image', 'label'],
roi_size=(160, 160, 96),
random_size=False,
random_center=True) According to the display of tensorboard, it feels that his axis has changed. By the way, how can I set the internal parameters of Thanks in advance! Update: |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 14 replies
-
Hi @Minxiangliu , based on your logs, I saw there is spatial padding but no cropping operation. I guess all test images are smaller than dimension of (196, 196, 128), then padding works to keep all images dimension consistent. And adding RandSpatialCropd to dimension roi_size=(160, 160, 96) will decrease ROI resulting the "strange" visualization. I would recommend first padding to (196, 196, 128), all image will have at least this size, then crop to (196, 196, 128) for maintaining ROI. |
Beta Was this translation helpful? Give feedback.
-
For passing dataset type you can refer here in the train task: |
Beta Was this translation helpful? Give feedback.
-
Hi @tangy5 , The title on tensorboard means Finally, I added the transformation of the modified axis in the pre-transformation, converted the Lambdad(keys=['image','label'], func=lambda x:np.moveaxis(x,-1,1)), I think there are some axis transformations when outputting the log, which will cause the problem that the shape is not the same. |
Beta Was this translation helpful? Give feedback.
For passing dataset type you can refer here in the train task:
MONAILabel/monailabel/tasks/train/basic_train.py
Line 75 in d5a8805