Giter Site home page Giter Site logo

black0017 / medicalzoopytorch Goto Github PK

View Code? Open in Web Editor NEW
1.6K 34.0 292.0 62.87 MB

A pytorch-based deep learning framework for multi-modal 2D/3D medical image segmentation

License: MIT License

Python 90.35% Dockerfile 0.07% Jupyter Notebook 9.58%
segmentation deep-learning pytorch medical-imaging medical-image-processing medical-image-segmentation 3d-convolutional-network brats2019 brats2018 densenet

medicalzoopytorch's Introduction

A 3D multi-modal medical image segmentation library in PyTorch

Contributors Forks Stargazers Issues Open In Colab

We strongly believe in open and reproducible deep learning research. Our goal is to implement an open-source medical image segmentation library of state of the art 3D deep neural networks in PyTorch. We also implemented a bunch of data loaders of the most common medical image datasets. This project started as an MSc Thesis and is currently under further development. Although this work was initially focused on 3D multi-modal brain MRI segmentation we are slowly adding more architectures and data-loaders.

Top priorities 21-07

[Update] 21-07 We have just received a brand new GPU. The project developedment was postponed due to lack of computational resources. We will be back with more updates. Please Watch our Github repository for releases to be notified. We are always looking for passionate open-source contributos. Full credits will be given.

  • Project restructure, API/CLI design ++
  • Minimal test prediction example with pre-trained models
  • Overlapping and non-overlapping inference
  • Finalize preprocessing on Brats datasets
  • Save produced 3d-total-segmentation as nifty files
  • Medical image decathlon dataloaders
  • StructSeg 2019 challenge dataloaders
  • More options for 2D architectures
  • Rewrite manual
  • New notebooks with google colab support

Quick Start

  • If you want to quickly understand the fundamental concepts for deep learning in medical imaging, we strongly advice to check our blog post. We provide a general high-level overview of all the aspects of medical image segmentation and deep learning. For a broader overview on MRI applications find my latest review article.

  • To grasp more fundamental medical imaging concepts, check out our post on coordinate systems and DICOM images.

  • For a more holistic approach on Deep Learning in MRI you may advice my thesis this.

  • Alternatively, you can create a virtual environment and install the requirements. Check the installation folder for more instructions.

  • You can also take a quick glance at the manual.

  • If you do not have a capable environment or device to run this projects then you could give Google Colab a try. It allows you to run the project using a GPU device, free of charge. You may try our Colab demo using this notebook:Open In Colab

Implemented architectures

  • U-Net3D Learning Dense Volumetric Segmentation from Sparse Annotation Learning Dense Volumetric Segmentation from Sparse Annotation

  • V-net Fully Convolutional Neural Networks for Volumetric Medical Image Segmentation

  • ResNet3D-VAE 3D MRI brain tumor segmentation using auto-encoder regularization

  • U-Net Convolutional Networks for Biomedical Image Segmentation

  • SkipDesneNet3D 3D Densely Convolutional Networks for Volumetric Segmentation

  • HyperDense-Net A hyper-densely connected CNN for multi-modal image segmentation

  • multi-stream Densenet3D A hyper-densely connected CNN for multi-modal image segmentation

  • DenseVoxelNet Automatic 3D Cardiovascular MR Segmentation with Densely-Connected Volumetric ConvNets

  • MED3D Transfer learning for 3D medical image analysis

  • HighResNet3D On the Compactness, Efficiency, and Representation of 3D Convolutional Networks: Brain Parcellation as a Pretext Task

Implemented medical imaging data-loaders

Task Data Info/ Modalities Train/Test Volume size Classes Dataset size (GB)
Iseg 2017 T1, T2 10 / 10 144x192x256 4 0.72
Iseg 2019 T1, T2 10 / 13 144x192x256 4 0.75
MICCAI BraTs2018 FLAIR, T1w, T1gd,T2w 285 / - 240x240x155 9 or 4 2.4
MICCAI BraTs2019 FLAIR, T1w, T1gd,T2w 335 / 125 240x240x155 9 or 4 4
Mrbrains 2018 FLAIR, T1w, T1gd,T2w 8 240x240x48 9 or 4 0.5
IXI brain development Dataset T1,T2 no labels 581 (110~150)x256x256 - 8.7
MICCAI Gleason 2019 Challenge 2D pathology images ~250 5K x 5K - 2.5

Preliminary results

Visual results on Iseg-2017

Iseg and Mr-brains

Model # Params (M) MACS(G) Iseg 2017 DSC (%) Mr-brains 4 classes DSC (%)
Unet3D 17 M 0.9 93.84 88.61
Vnet 45 M 12 87.21 84.09
DenseNet3D 3 M 5.1 81.65 79.85
SkipDenseNet3D 1.5 M 31 - -
DenseVoxelNet 1.8 M 8 - -
HyperDenseNet 10.4 M 5.8 - -

Usage

How to train your model

  • For Iseg-2017 :
python ./examples/train_iseg2017_new.py --args
  • For MR brains 2018 (4 classes)
python ./examples/train_mrbrains_4_classes.py --args
  • For MR brains 2018 (8 classes)
python ./examples/train_mrbrains_9_classes.py --args
  • For MICCAI 2019 Gleason Challenge
python ./examples/test_miccai_2019.py --args
  • The arguments that you can modify are extensively listed in the manual.

Inference

How to test your trained model in a medical image

python ./tests/inference.py --args

Covid-19 segmentation and classification

We provide some implementations around Covid-19 for humanitarian purposes. In detail:

Classification model

  • COVID-Net A Tailored Deep Convolutional Neural Network Design for Detection of COVID-19 Cases from Chest Radiography Images

Datasets

Classification from 2D images:

3D COVID-19 segmentation dataset

Latest features (06/2020)

  • On the fly 3D total volume visualization
  • Tensorboard and PyTorch 1.4+ support to track training progress
  • Code cleanup and packages creation
  • Offline sub-volume generation
  • Add Hyperdensenet, 3DResnet-VAE, DenseVoxelNet
  • Fix mrbrains,Brats2018,Brats2019, Iseg2019, IXI,MICCAI 2019 gleason challenge dataloaders
  • Add confusion matrix support for understanding training dynamics
  • Some Visualizations

Support

If you really like this repository and find it useful, please consider (★) starring it, so that it can reach a broader audience of like-minded people. It would be highly appreciated :) !

Contributing to Medical ZOO

If you find a bug, create a GitHub issue, or even better, submit a pull request. Similarly, if you have questions, simply post them as GitHub issues. More info on the contribute directory.

Current team

License , citation and acknowledgements

Please advice the LICENSE.md file. For usage of third party libraries and repositories please advise the respective distributed terms. It would be nice to cite the original models and datasets. If you want, you can also cite this work as:

@MastersThesis{adaloglou2019MRIsegmentation,
author = {Adaloglou Nikolaos},
title={Deep learning in medical image analysis: a comparative analysis of
multi-modal brain-MRI segmentation with 3D deep neural networks},
school = {University of Patras},
note="\url{https://github.com/black0017/MedicalZooPytorch}",
year = {2019},
organization={Nemertes}}

Acknowledgements

In general, in the open source community recognizing third party utilities increases the credibility of your software. In deep learning, academics tend to skip acknowledging third party repos for some reason. In essence, we used whatever resource we needed to make this project self-complete, that was nicely written. However, modifications were performed to match the project structure and requirements. Here is the list of the top-based works: HyperDenseNet model. Most of the segmentation losses from here. 3D-SkipDenseNet model from here. 3D-ResNet base model from here. Abstract model class from MimiCry project. Trainer and Writer class from PyTorch template. Covid-19 implementation based on our previous work from here. MICCAI 2019 Gleason challenge data-loaders based on our previous work from here. Basic 2D Unet implementation from here.Vnet model from here

medicalzoopytorch's People

Contributors

black0017 avatar glennmatlin avatar iliasprc avatar pyushkevich avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

medicalzoopytorch's Issues

full_volume.shape ==> "None type has no attribute shape"

Does anyone has solution to this

Data: brats2018 dataset

A bug in tests.test_vizual.py
Line: 37: visualize_3D_no_overlap_new(args, full_volume, affine, model, 10, args.dim)
This leads to lib/visual3D_temp/[viz.py]
Line 111: modalities, slices, height, width = full_volume.shape

"None type has no attribute shape"
pppp

Low validation DSC when training on Brats2018

Hello, First of all, thanks for the amazing work.
Question: I tried to train the Unet3D model on bratS 2018 dataset using the 'train_brats_2018_new.py'. but I got lower validation DSC and higher validation loss, I think the model is facing some trouble on validation set:
image

pretrained models for COVID-19 CT segmentation

Hi @black0017 ,

Thanks for your great work.

I notice that you are also working on pre-trained models on public datasets.

Here is a benchmark for lung and infection segmentation in COVID-19 CT scans.

Are you interested in including this COVID-19 segmentation dataset for pre-trained models?

Best regards,
Jun

RuntimeError: Expected 5-dimensional input for 5-dimensional weight 8 4 3 3, but got 4-dimensional input of size [4, 256, 64, 64] instead

Can you tell me why cone to it and how to solve it?
Traceback (most recent call last):
File "train_brats2018_new.py", line 75, in
main()
File "train_brats2018_new.py", line 33, in main
trainer.training()
File "/data/Disk_A/guoyang/mqp/MedicalZooPytorch-master/lib/train/trainer.py", line 38, in training
self.validate_epoch(epoch)
File "/data/Disk_A/guoyang/mqp/MedicalZooPytorch-master/lib/train/trainer.py", line 83, in validate_epoch
output = self.model(input_tensor)
File "/data/Disk_A/guoyang/.conda/envs/pt041/lib/python3.6/site-packages/torch/nn/modules/module.py", line 547, in call
result = self.forward(*input, **kwargs)
File "/data/Disk_A/guoyang/mqp/MedicalZooPytorch-master/lib/medzoo/Unet3D.py", line 114, in forward
out = self.conv3d_c1_1(x)
File "/data/Disk_A/guoyang/.conda/envs/pt041/lib/python3.6/site-packages/torch/nn/modules/module.py", line 547, in call
result = self.forward(*input, **kwargs)
File "/data/Disk_A/guoyang/.conda/envs/pt041/lib/python3.6/site-packages/torch/nn/modules/conv.py", line 478, in forward
self.padding, self.dilation, self.groups)
RuntimeError: Expected 5-dimensional input for 5-dimensional weight 8 4 3 3, but got 4-dimensional input of size [4, 256, 64, 64] instead

'Namespace' object has no attribute 'samples_train'

command:
!python test_miccai_2019.py --dataset_name MICCAI_2019_pathology_challenge --nEpochs 2 --opt adam --model UNET2D

output:

2020-05-01 07:37:33.986079: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1
Traceback (most recent call last):
  File "test_miccai_2019.py", line 86, in <module>
    main()
  File "test_miccai_2019.py", line 34, in main
    path='.././datasets')
  File "/content/MedicalZooPytorch/lib/medloaders/__init__.py", line 17, in generate_datasets
    samples_train = args.samples_train
AttributeError: 'Namespace' object has no attribute 'samples_train'

updated command :
!python test_miccai_2019.py --dataset_name MICCAI_2019_pathology_challenge --nEpochs 2 --opt adam --model UNET2D --samples_train 10

ouput:

usage: test_miccai_2019.py [-h] [--batchSz BATCHSZ]
                           [--dataset_name DATASET_NAME] [--nEpochs NEPOCHS]
                           [--dim DIM [DIM ...]] [--classes CLASSES]
                           [--inChannels INCHANNELS]
                           [--inModalities INMODALITIES] [--fold_id FOLD_ID]
                           [--lr LR] [--cuda] [--resume PATH]
                           [--model {VNET,VNET2,UNET3D,DENSENET1,DENSENET2,DENSENET3,HYPERDENSENET,UNET2D}]
                           [--opt {sgd,adam,rmsprop}]
test_miccai_2019.py: error: unrecognized arguments: --samples_train 10

Other way around by altering the test_miccai_2019.py code:

medical_loaders.generate_datasets(args, path='.././datasets',samples_train=samples_train,
samples_val=samples_val)

Adding samples_train and Samples_val ,rises error in generate_dataset()

question about train

When I used the mrbrains18 dataset for training, the following error occurred
Traceback (most recent call last):
File "./train_mrbrains_9_classes.py", line 81, in
main()
File "./train_mrbrains_9_classes.py", line 26, in main
path='/home/zwj/MedicalZooPytorch-master/datasets/mrbrains_2018/training')
File "/home/zwj/MedicalZooPytorch-master/lib/medloaders/init.py", line 50, in generate_datasets
split_id=0, samples=samples_train, load=args.loadData)
AttributeError: 'Namespace' object has no attribute 'loadData'

RuntimeError: Expected 5-dimensional input for 5-dimensional weight 8 4 3 3 3, but got 4-dimensional input of size [4, 256, 64, 64] instead

Hi,
When I want to train on BraTS2018, I use this command line
"python train_brats2018_new.py"

It shows this problem

Summary train Epoch 1: Loss:0.7025 DSC:29.7528 Background : 0.8263 NCR/NET : 0.0612 ED : 0.2336 ET : 0.0689
Traceback (most recent call last):
File "train_brats2018_new.py", line 75, in
main()
File "train_brats2018_new.py", line 33, in main
trainer.training()
File "/content/drive/My Drive/MedicalZooPytorch/lib/train/trainer.py", line 38, in training
self.validate_epoch(epoch)
File "/content/drive/My Drive/MedicalZooPytorch/lib/train/trainer.py", line 83, in validate_epoch
output = self.model(input_tensor)
File "/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py", line 532, in call
result = self.forward(*input, **kwargs)
File "/content/drive/My Drive/MedicalZooPytorch/lib/medzoo/Vnet.py", line 150, in forward
out16 = self.in_tr(x)
File "/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py", line 532, in call
result = self.forward(*input, **kwargs)
File "/content/drive/My Drive/MedicalZooPytorch/lib/medzoo/Vnet.py", line 58, in forward
out = self.conv1(x)
File "/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py", line 532, in call
result = self.forward(*input, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/torch/nn/modules/conv.py", line 480, in forward
self.padding, self.dilation, self.groups)
RuntimeError: Expected 5-dimensional input for 5-dimensional weight 16 4 5 5 5, but got 4-dimensional input of size [4, 256, 64, 64] instead

Could you help me solve that?

Version 1.0

TODO:

  • Restructure project
  • Base classes
    • Base dataset class
    • Base augment class
  • Inference with pretrained models
  • Configuration systems
    • basic infrastructure
    • wire up with all medloaders/datasets and remove parse arg
  • Logging
    • Create logger and inject everywhere
    • add more logging in the coder
  • API
    • create a medzoo train
    • create a medzoo infer (we don't have inference yet)
  • API docs
    • Sphinx setup
    • Update docstrings everywhere
  • Medzoo documentation site
    • Create static site and wire up with API
    • Write docs content
    • Publish
  • Package
    • setup.py
    • publish in pypi

The error message "Expected 5-dimensional input for 5-dimensional weight [8, 3, 3, 3, 3], but got 4-dimensional input of size [4, 384, 128, 48] instead" indicates that there is a mismatch between the expected input dimensions (5-dimensional) and the actual input dimensions provided (4-dimensional).

After replacing the getitem method in line 77 of the file lib->medloaders>mrbrains2018.py with the following code, the error disappears and the training can proceed normally.

def __getitem__(self, index):
    t1_path, ir_path, flair_path, seg_path = self.list[index]
    t1_data, ir_data, flair_data, seg_data = np.load(t1_path), np.load(ir_path), np.load(flair_path), np.load(
        seg_path)

    return torch.FloatTensor(t1_data.copy()).unsqueeze(0), torch.FloatTensor(ir_data.copy()).unsqueeze(0), \
        torch.FloatTensor(flair_data.copy()).unsqueeze(0), torch.FloatTensor(seg_data.copy())

20240221150317
20240221150516

Data directory structure

Hi,

How to perform 3D segmentation to the custom dataset with 3D volume and corresponding segmentation.
A dataset file structure might be helpful for iseg_2017 example.

Thanks

About img_nii shape in method 'load_medical_image'

When I read MRbrainS18 data and use 'load_medical_image' to get volume, I find that the shape of the volume is (240, 240, 48) -> (width, height, slice). However, the shape of the crop is (slice, width, height), Is it a bug?

 def load_medical_image(path, type=None, resample=None,
                       viz3d=False, to_canonical=False, rescale=None, normalization='full_volume_mean',
                       clip_intenisty=True, crop_size=(0, 0, 0), crop=(0, 0, 0), ):
    img_nii = nib.load(path)

    if to_canonical:
        img_nii = nib.as_closest_canonical(img_nii)

    if resample is not None:
        img_nii = resample_to_output(img_nii, voxel_sizes=resample)

    img_np = np.squeeze(img_nii.get_fdata(dtype=np.float32))

    if viz3d:
 >       return torch.from_numpy(img_np) # shape:(240,240,48), whether it is a bug?

Data size into the model

Hi,
I would like to train using my own data. I have volume x,y,z and corresponding 1 segmentation with 99 classes. what is the data size that feeded into the model. since I don't have access into the data example, what is the size of data example used?

The OutputTransition of the VNet model exists with one more than Conv3D

According to the structure diagram of the paper, the final OutputTransition should look like the following:

class OutputTransition(nn.Module):
    def __init__(self, in_channels, classes, elu):
        super(OutputTransition, self).__init__()
        self.classes = classes
        # self.conv1 = nn.Conv3d(in_channels, classes, kernel_size=5, padding=2)    # 修改
        self.conv1 = nn.Conv3d(in_channels, classes, kernel_size=1)
        self.bn1 = torch.nn.BatchNorm3d(classes)

        self.conv2 = nn.Conv3d(classes, classes, kernel_size=1)
        self.relu1 = ELUCons(elu, classes)

    def forward(self, x):
        out = self.relu1(self.bn1(self.conv1(x)))
        # out = self.conv2(out) # 修改
        return out

We simply use the only 111 convolutional layer to make the number of channels the same as the classes.

AttributeError: 'Namespace' object has no attribute 'loadData'

Hi,

When trying to do inference using iseg2017 model.
I am getting below error

File "inference.py", line 80, in <module> main() File "inference.py", line 24, in main training_generator, val_generator, full_volume, affine = medical_loaders.generate_datasets(args, File "/mnt/nas02/Sampledata_BrainVolumetry/brain_try/MedicalZoo/MedicalZooPytorch/lib/medloaders/__init__.py", line 28, in generate_datasets split_id=split_idx, samples=samples_train, load=args.loadData) AttributeError: 'Namespace' object has no attribute 'loadData'

When I check inference.py file its not taking any input argument for loadData

About the format of using my own data

I would like to ask about the format of using your own data set, including how many bits of data it is and what data must be included in the folder

Something trouble with inference.py

Hello!
I have trained a segmentation model using my own datasets,there is nothing wrong with my valuation dataset and the dice is high.But when I use the 'non_overlap_padding' fuction in the inference.py ,the dice score is very low.I have tried to output the prediction image (image bellow),there might something wrong with the patches index.Would you mind help me to fix this problem?Thank you very much !

13

ValueError: low >= high

!python test_covid_ct.py --dataset_name covid_seg

2020-05-01 11:52:26.733364: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1
COVID SEGMENTATION DATASET
0
Mode: train Subvolume samples to generate:  10  Volumes:  0
Traceback (most recent call last):
  File "test_covid_ct.py", line 76, in <module>
    main()
  File "test_covid_ct.py", line 27, in main
    path='.././datasets')
  File "/content/MedicalZooPytorch/lib/medloaders/__init__.py", line 79, in generate_datasets
    fold=args.fold_id, samples=samples_train, save=True)
  File "/content/MedicalZooPytorch/lib/medloaders/Covid_Segmentation_dataset.py", line 70, in __init__
    self.create_sub_volumes()
  File "/content/MedicalZooPytorch/lib/medloaders/Covid_Segmentation_dataset.py", line 96, in create_sub_volumes
    random_index = np.random.randint(total)
  File "mtrand.pyx", line 743, in numpy.random.mtrand.RandomState.randint
  File "_bounded_integers.pyx", line 1260, in numpy.random._bounded_integers._rand_int64
ValueError: low >= high

IO format

Hello,

How do I perform multi class semantic (instance) segmentation over my set of 2D PNG/TIF grayscale images and their corresponding masks file (NPY numpy array, TIF or any other) matrix representation with # channels corresponding to the classes?
Do I need to use NIFTI_interface? If so, how do I convert my PNG/TIF/NPY files to this format?

Thank you

Hi, How to get this kind of results using highresnet?

Describe the bug
A clear and concise description of what the bug is.

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.
image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.