-
Notifications
You must be signed in to change notification settings - Fork 374
(UNETR) : Add predict label function and custom dataloader which can train with own data . #420
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
tylin7111095022
wants to merge
7
commits into
Project-MONAI:main
Choose a base branch
from
tylin7111095022:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
b5b33e1
1. Add customDatasetLoader 2. Add predict function in test.py
tylin7111095022 832618e
Update README.md
tylin7111095022 f0b3dc4
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 9a75007
fix: Resolve issue #420 in the workflow of predict
tylin7111095022 18d35a9
merge commit of remote and local side
tylin7111095022 4b366df
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 30bc5b1
Make pairing robust: filter by extension and intersect filenames acro…
tylin7111095022 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| NIFTI_DATA_ROOT = 'data/images' # nifti image directory | ||
| NIFTI_LABEL_ROOT = 'data/labels' # nifti label directory | ||
| PREDICT_DATA_ROOT = 'data/predict' # predict image directory |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,126 @@ | ||
| import os | ||
| from torch.utils.data import DataLoader | ||
| from monai.data import Dataset | ||
| import monai.transforms as transforms | ||
| import torch | ||
|
|
||
| from config import NIFTI_DATA_ROOT, NIFTI_LABEL_ROOT, PREDICT_DATA_ROOT | ||
|
|
||
| def _get_collate_fn(isTrain:bool): | ||
| def collate_fn(batch): | ||
| '''collate function''' | ||
| images = [] | ||
| labels = [] | ||
| if isTrain: | ||
| for p in batch: # [ {"image": (C, H, W ,D), "label": (C, H, W ,D)} , ...] | ||
| for i in range(len(p)): # list, RandCropByPosNegLabeld will produce multiple samples | ||
| images.append(p[i]['image']) | ||
| labels.append(p[i]['label']) | ||
| else: | ||
| for p in batch: | ||
| images.append(p['image']) | ||
| labels.append(p['label']) | ||
|
|
||
| images = torch.stack(images, dim=0) | ||
| labels = torch.stack(labels, dim=0) | ||
| # keep images float and labels long for loss functions | ||
| return [images.float(), labels.long()] | ||
|
|
||
| return collate_fn | ||
|
|
||
| def getDatasetLoader(args): | ||
| exts = (".nii", ".nii.gz") | ||
| img_names = {f for f in os.listdir(NIFTI_DATA_ROOT) if f.endswith(exts) and os.path.isfile(os.path.join(NIFTI_DATA_ROOT, f))} | ||
| lbl_names = {f for f in os.listdir(NIFTI_LABEL_ROOT) if f.endswith(exts) and os.path.isfile(os.path.join(NIFTI_LABEL_ROOT, f))} | ||
| common = sorted(img_names & lbl_names) | ||
| if not common: | ||
| raise RuntimeError(f"No matching image/label pairs found in {NIFTI_DATA_ROOT} and {NIFTI_LABEL_ROOT}") | ||
| dataDicts = [{"image": os.path.join(NIFTI_DATA_ROOT, f), "label": os.path.join(NIFTI_LABEL_ROOT, f)} for f in common] | ||
|
|
||
| trainDicts, valDicts = _splitList(dataDicts) | ||
|
|
||
| train_transform = transforms.Compose( | ||
| [ | ||
| transforms.LoadImaged(keys=["image", "label"]), | ||
| transforms.EnsureChannelFirstd(keys=["image", "label"]), | ||
| transforms.Orientationd(keys=["image", "label"], axcodes="RAS"), | ||
| transforms.Spacingd( | ||
| keys=["image", "label"], pixdim=(args.space_x, args.space_y, args.space_z), mode=("bilinear", "nearest") | ||
| ), | ||
| transforms.ScaleIntensityRanged( | ||
| keys=["image"], a_min=args.a_min, a_max=args.a_max, b_min=args.b_min, b_max=args.b_max, clip=True | ||
| ), | ||
| transforms.CropForegroundd(keys=["image", "label"], source_key="image", allow_smaller=True), | ||
| transforms.RandCropByPosNegLabeld( | ||
| keys=["image", "label"], | ||
| label_key="label", | ||
| spatial_size=(args.roi_x, args.roi_y, args.roi_z), | ||
| pos=1, | ||
| neg=1, | ||
| num_samples=4, | ||
| image_key="image", | ||
| image_threshold=0, | ||
| ), | ||
| transforms.RandFlipd(keys=["image", "label"], prob=args.RandFlipd_prob, spatial_axis=0), | ||
| transforms.RandFlipd(keys=["image", "label"], prob=args.RandFlipd_prob, spatial_axis=1), | ||
| transforms.RandFlipd(keys=["image", "label"], prob=args.RandFlipd_prob, spatial_axis=2), | ||
| transforms.RandRotate90d(keys=["image", "label"], prob=args.RandRotate90d_prob, max_k=3), | ||
| transforms.RandScaleIntensityd(keys="image", factors=0.1, prob=args.RandScaleIntensityd_prob), | ||
| transforms.RandShiftIntensityd(keys="image", offsets=0.1, prob=args.RandShiftIntensityd_prob), | ||
| transforms.ToTensord(keys=["image", "label"]), | ||
| ] | ||
| ) | ||
|
|
||
| val_transform = transforms.Compose( | ||
| [ | ||
| transforms.LoadImaged(keys=["image", "label"]), | ||
| transforms.EnsureChannelFirstd(keys=["image", "label"]), | ||
| transforms.Orientationd(keys=["image", "label"], axcodes="RAS"), | ||
| transforms.Spacingd( | ||
| keys=["image", "label"], pixdim=(args.space_x, args.space_y, args.space_z), mode=("bilinear", "nearest") | ||
| ), | ||
| transforms.ScaleIntensityRanged( | ||
| keys=["image"], a_min=args.a_min, a_max=args.a_max, b_min=args.b_min, b_max=args.b_max, clip=True | ||
| ), | ||
| transforms.CropForegroundd(keys=["image", "label"], source_key="image", allow_smaller=True), | ||
| transforms.ToTensord(keys=["image", "label"]), | ||
| ] | ||
| ) | ||
|
|
||
| trainDataset = Dataset(data=trainDicts, transform=train_transform) | ||
| valDataset = Dataset(data=valDicts, transform=val_transform) | ||
| trainLoader = DataLoader(trainDataset,batch_size=args.batch_size,shuffle=True,num_workers=args.workers, collate_fn=_get_collate_fn(isTrain=True)) | ||
| valLoader = DataLoader(valDataset,batch_size=args.batch_size,shuffle=False,num_workers=args.workers, collate_fn=_get_collate_fn(isTrain=False)) | ||
| loader = [trainLoader, valLoader] | ||
|
|
||
| return loader | ||
|
|
||
| def _splitList(l, trainRatio:float = 0.8): | ||
| totalNum = len(l) | ||
| splitIdx = int(totalNum * trainRatio) | ||
|
|
||
| return l[:splitIdx], l[splitIdx :] | ||
|
|
||
| def getPredictLoader(args): | ||
| dataName = [d for d in os.listdir(PREDICT_DATA_ROOT)] | ||
| dataDicts = [{"image": f"{os.path.join(PREDICT_DATA_ROOT, d)}" } for d in dataName] | ||
|
|
||
| preTransform = transforms.Compose( | ||
| [ | ||
| transforms.LoadImaged(keys=["image"]), | ||
| transforms.EnsureChannelFirstd(keys=["image"]), | ||
| transforms.Orientationd(keys=["image"], axcodes="RAS"), | ||
| transforms.Spacingd( | ||
| keys=["image"], pixdim=(args.space_x, args.space_y, args.space_z), mode=("bilinear") | ||
| ), | ||
| transforms.ScaleIntensityRanged( | ||
| keys=["image"], a_min=args.a_min, a_max=args.a_max, b_min=args.b_min, b_max=args.b_max, clip=True | ||
| ), | ||
| transforms.CropForegroundd(keys=["image"], source_key="image", allow_smaller=True), | ||
| transforms.EnsureTyped(keys=["image"], track_meta=True), | ||
| ] | ||
| ) | ||
| valDataset = Dataset(data=dataDicts, transform=preTransform) | ||
| valLoader = DataLoader(valDataset,batch_size=args.batch_size,shuffle=False,num_workers=args.workers) | ||
|
|
||
| return valLoader, preTransform | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Filter predict files to NIfTI and validate presence.
Unfiltered os.listdir may include non-NIfTI files (.DS_Store, JSON, etc.) and will break LoadImaged.
📝 Committable suggestion
🤖 Prompt for AI Agents