{"id":7427,"library":"monai","title":"MONAI: Medical Open Network for AI","description":"MONAI (Medical Open Network for AI) is a PyTorch-based, open-source framework providing domain-optimized foundational capabilities for deep learning in healthcare imaging. It offers standardized, efficient, and reproducible components like data loaders, transforms, networks, and metrics, specifically designed for medical applications. The current version is 1.5.2, with regular minor and patch releases, typically multiple times per year.","status":"active","version":"1.5.2","language":"en","source_language":"en","source_url":"https://github.com/Project-MONAI/MONAI","tags":["AI","Healthcare","Medical Imaging","Deep Learning","PyTorch","Computer Vision","Radiology"],"install":[{"cmd":"pip install monai","lang":"bash","label":"Install MONAI (ensure PyTorch is installed first, compatible with your CUDA version)"}],"dependencies":[{"reason":"Core deep learning framework (users install separately for CUDA configuration)","package":"torch"},{"reason":"Fundamental library for numerical operations on arrays","package":"numpy"},{"reason":"Image loading and processing utilities","package":"pillow"},{"reason":"Image processing utilities, used by some transforms","package":"scikit-image"},{"reason":"Scientific computing utilities, especially for image interpolation and processing","package":"scipy"},{"reason":"Progress bars for iterations and loops","package":"tqdm"},{"reason":"Provides a high-level engine and event-handler system for training loops","package":"pytorch-ignite"},{"reason":"Required for reading/writing NIfTI and other neuroimaging file formats","package":"nibabel","optional":true},{"reason":"For data visualization and plotting","package":"matplotlib","optional":true},{"reason":"For logging metrics, visualizations, and debugging models","package":"tensorboard","optional":true},{"reason":"For loading configuration files","package":"pyyaml","optional":true}],"imports":[{"symbol":"Compose","correct":"from monai.transforms import Compose"},{"note":"LoadNifti and similar format-specific loaders were replaced by LoadImaged (dictionary) or LoadImaget (tuple) for generality, typically from v0.9.0 onwards.","wrong":"from monai.transforms import LoadNifti","symbol":"LoadImaged","correct":"from monai.transforms import LoadImaged"},{"note":"Import path for Dataset objects moved directly under `monai.data` from v0.6.0.","wrong":"from monai.data.dataset import CacheDataset","symbol":"CacheDataset","correct":"from monai.data import CacheDataset"},{"symbol":"UNet","correct":"from monai.networks.nets import UNet"},{"note":"The sliding_window_inference utility was moved from `monai.data` to `monai.inferers` starting from v0.9.0, deprecated in `monai.data` in v1.0.0.","wrong":"from monai.data import sliding_window_inference","symbol":"sliding_window_inference","correct":"from monai.inferers import sliding_window_inference"}],"quickstart":{"code":"import torch\nimport numpy as np\nfrom monai.transforms import Compose, LoadImaged, EnsureChannelFirstd, ScaleIntensityRanged, Orientationd, Spacingd\nimport os\nimport nibabel as nib\n\n# Create dummy image file for demonstration\ndummy_image_path = \"dummy_image.nii.gz\"\nif not os.path.exists(dummy_image_path):\n    print(f\"Creating dummy NIfTI image at {dummy_image_path}...\")\n    dummy_data = np.random.rand(10, 10, 10).astype(np.float32)\n    affine = np.diag([1, 1, 1, 1])\n    nifti_img = nib.Nifti1Image(dummy_data, affine)\n    nib.save(nifti_img, dummy_image_path)\n\n# 1. Define a transform pipeline for dictionary-based data\nkeys = [\"image\"] # working with dictionary data, key for the image\ntransform = Compose(\n    [\n        LoadImaged(keys=keys), # Load medical image data\n        EnsureChannelFirstd(keys=keys), # Ensure channel dimension is first\n        ScaleIntensityRanged(keys=keys, a_min=0, a_max=1, b_min=0.0, b_max=1.0, clip=True), # Normalize intensity\n        Orientationd(keys=keys, axcodes=\"RAS\"), # Reorient image to standard anatomical space\n        Spacingd(keys=keys, pixdim=(1.5, 1.5, 2.0), mode=\"bilinear\"), # Resample to desired spacing\n    ]\n)\n\n# 2. Create dummy data list (mimicking a dataset of file paths)\ndata = [{\n    \"image\": dummy_image_path\n}] * 2 # Two dummy items for batching effect\n\n# 3. Apply transforms (typically done within a Dataset/DataLoader)\ntransformed_data = [transform(item) for item in data]\n\nprint(f\"Original image path: {data[0]['image']}\")\nprint(f\"Transformed image shape: {transformed_data[0]['image'].shape}\")\nprint(f\"Transformed image dtype: {transformed_data[0]['image'].dtype}\")\n\n# Clean up dummy file\nif os.path.exists(dummy_image_path):\n    os.remove(dummy_image_path)\n    print(f\"Cleaned up dummy NIfTI image: {dummy_image_path}\")","lang":"python","description":"This quickstart demonstrates a basic MONAI transform pipeline using dictionary-based transforms (suffixed with 'd'). It loads a dummy NIfTI image, applies several common preprocessing steps like channel reordering, intensity scaling, orientation standardization, and spatial resampling, then prints the shape and data type of the transformed image. This setup mirrors typical medical imaging data workflows."},"warnings":[{"fix":"For custom transforms, change method name from `apply` to `__call__` and ensure it accepts and returns data consistent with MONAI's transform interface.","message":"The `apply` method for custom transforms was removed in v1.0.0. Custom transforms should override the `__call__` method.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"Update import statements from `from monai.data import sliding_window_inference` to `from monai.inferers import sliding_window_inference`.","message":"The `sliding_window_inference` utility was moved from `monai.data` to `monai.inferers`.","severity":"breaking","affected_versions":">=0.9.0"},{"fix":"Replace `LoadNifti(...)` with `LoadImaged(keys=..., reader='NibabelReader')` or `LoadImaget(...)`, specifying `reader` if needed.","message":"Format-specific image loaders like `LoadNifti` or `LoadDICOM` were deprecated/removed in favor of `LoadImaged` (for dictionary-based inputs) or `LoadImaget` (for tuple-based inputs).","severity":"breaking","affected_versions":">=0.9.0"},{"fix":"Ensure the keys in your input data dictionary (e.g., `{'image': 'path/to/img.nii.gz', 'label': 'path/to/label.nii.gz'}`) exactly match the `keys` argument provided to the transform (e.g., `LoadImaged(keys=['image', 'label'])`).","message":"Dictionary-based transforms (e.g., `LoadImaged`, `ScaleIntensityRanged`) operate on specific keys. Mismatching keys between your input dictionary and the transform's `keys` argument will result in a `KeyError`.","severity":"gotcha","affected_versions":"all"},{"fix":"Consult the MONAI documentation for recommended PyTorch versions. Install PyTorch separately, ensuring the correct CUDA-enabled version for your hardware, before installing MONAI.","message":"MONAI heavily relies on PyTorch. Users must ensure their PyTorch version is compatible with the installed MONAI version and their CUDA setup to avoid `RuntimeError` or performance issues.","severity":"gotcha","affected_versions":"all"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"Reduce the `batch_size`, crop input images to smaller dimensions, or enable mixed precision training (`torch.cuda.amp.autocast()`) if your model supports it.","cause":"The model, batch size, or image dimensions exceed the available VRAM on the GPU.","error":"RuntimeError: CUDA out of memory. Tried to allocate X GiB (GPU Y)"},{"fix":"Before converting a GPU tensor to a NumPy array, first move it to the CPU using `.cpu()`: `my_tensor.cpu().numpy()`.","cause":"Attempting to call `.numpy()` directly on a PyTorch tensor residing on the GPU.","error":"TypeError: can't convert CUDA tensor to numpy. Use .cpu().numpy() instead if you want to transfer the tensor to CPU"},{"fix":"Verify that your input dictionary contains all the keys specified in the `keys` argument of the transform. For example, if `LoadImaged(keys=['data_key'])`, ensure your input dictionary has `{'data_key': ...}`.","cause":"A dictionary-based transform (e.g., `LoadImaged`) cannot find one of the specified `keys` in the input dictionary.","error":"KeyError: 'image' (or 'label', etc.)"},{"fix":"For built-in transforms, simply call them directly. For custom transforms, ensure you have overridden the `__call__` method instead of `apply`.","cause":"Attempting to use the `apply` method on a transform. This method was removed in MONAI v1.0.0.","error":"AttributeError: 'Dataset' object has no attribute 'apply'"},{"fix":"Consult the official MONAI documentation for the exact import path corresponding to your installed MONAI version. For `UNet`, the correct path is `from monai.networks.nets import UNet`.","cause":"Incorrect import path for a specific symbol, or an older version of MONAI where the symbol's location was different.","error":"ImportError: cannot import name 'UNet' from 'monai.networks.nets'"}]}