├── .gitattributes ├── .github ├── ISSUE_TEMPLATE │ └── niftynet-issue-template.md └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── .gitlab-ci.yml ├── .gitlab ├── issue_templates │ └── Bug.md └── merge_request_templates │ └── Pull_request.md ├── .readthedocs.yml ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── ci ├── bundlewheel.sh ├── findwheel.sh └── utils.sh ├── config ├── GAN_demo_train_config.ini ├── README.md ├── deepmedic_config.ini ├── default_eval_config.ini ├── default_monomodal_regression.ini ├── default_monomodal_regression_eval.ini ├── default_multimodal_segmentation.ini ├── default_multimodal_segmentation_eval.ini ├── default_segmentation.ini ├── default_segmentation_bf.ini ├── densevnet_config.ini ├── highres3dnet_config.ini ├── holisticnet_config.ini ├── label_driven_registration.ini ├── scalenet_config.ini ├── unet_config.ini ├── vae_config.ini ├── vnet_config.ini └── weighted_sample_regression.ini ├── data ├── IXI_autoencoder │ └── .gitignore ├── PROMISE12 │ └── setup.py └── us_simulator_gan │ └── .gitignore ├── demos ├── BRATS17 │ ├── README.md │ ├── __init__.py │ ├── example_outputs │ │ ├── ave_prob.png │ │ ├── label.png │ │ └── original.png │ └── rename_crop_BRATS.py ├── GAN │ └── README.md ├── Learning_Rate_Decay │ ├── Demo_applications │ │ ├── decay_lr_comparison_application.py │ │ └── no_decay_lr_comparison_application.py │ ├── Demo_for_learning_rate_decay_application.ipynb │ ├── README.md │ ├── decay_lr_application.py │ └── learning_rate_demo_train_config.ini ├── PROMISE12 │ ├── PROMISE12_Demo_Notebook.ipynb │ ├── README.md │ ├── promise12_balanced_train_config.ini │ ├── promise12_demo_inference_config.ini │ └── promise12_demo_train_config.ini ├── PyTorchNiftyNet │ ├── README.md │ ├── libs │ │ ├── __init__.py │ │ ├── dataset_niftynet.py │ │ ├── loss.py │ │ └── model.py │ └── segmentation.py ├── README.md ├── brain_parcellation │ ├── README.md │ └── example_outputs │ │ └── screenshot.png ├── crf_as_rnn │ └── crf_as_rnn_inference_demo.ipynb ├── module_examples │ ├── FullCSVReaderDemo.ipynb │ ├── ImageReader.ipynb │ ├── ImageSampler.ipynb │ ├── ParallelCSVReaderDemo.ipynb │ ├── README.md │ ├── mapping.txt │ └── visualise_coordinates.py ├── unet │ ├── HeLa.ini │ ├── README.md │ ├── U-Net_Demo.ipynb │ ├── U373.ini │ ├── file_sorter.py │ ├── generate_run_commands.py │ ├── make_cell_weights.py │ └── unet_demo_utils.py ├── unet_histology │ ├── config.ini │ ├── data_in_itksnap_scaled.png │ ├── tensorboard_scaled.png │ └── unet_histology_training.md └── variational_autoencoder │ ├── README.md │ ├── example_outputs │ ├── 1037.png │ ├── 464.png │ └── interpolation.gif │ └── vae_config.ini ├── doc ├── Makefile ├── make.bat ├── requirements.txt └── source │ ├── _static │ ├── .gitkeep │ ├── 3d_sampling.jpg │ ├── custom.css │ ├── grid.png │ ├── grid_cropped_50_12.png │ ├── grid_overlay.png │ ├── grid_pad_50.png │ ├── grid_pad_50_12.png │ ├── image.png │ ├── image_pad_50.png │ ├── uniform.png │ ├── uniform_pad_50.png │ └── uniform_pad_50_12.png │ ├── _templates │ ├── badge.html │ ├── globaltoc.html │ └── layout.html │ ├── buffer_queue.md │ ├── conf.py │ ├── config_spec.md │ ├── contributing.md │ ├── extending_app.md │ ├── extending_event_handler.md │ ├── extending_net.md │ ├── filename_matching.md │ ├── index.rst │ ├── installation.rst │ ├── introductory.md │ ├── list_modules.rst │ ├── model_zoo.md │ ├── transfer_learning.md │ ├── versioneer.rst │ └── window_sizes.rst ├── net_autoencoder.py ├── net_classify.py ├── net_download.py ├── net_gan.py ├── net_regress.py ├── net_run.py ├── net_segment.py ├── niftynet-logo.png ├── niftynet ├── __init__.py ├── application │ ├── __init__.py │ ├── autoencoder_application.py │ ├── base_application.py │ ├── classification_application.py │ ├── gan_application.py │ ├── label_driven_registration.py │ ├── regression_application.py │ └── segmentation_application.py ├── contrib │ ├── __init__.py │ ├── checkpoint_tools │ │ ├── __init__.py │ │ └── rename_checkpoint_to_partial.py │ ├── csv_reader │ │ ├── __init__.py │ │ ├── applications_maybe │ │ │ ├── __init__.py │ │ │ ├── autoencoder_application.py │ │ │ ├── gan_application.py │ │ │ ├── label_driven_registration.py │ │ │ ├── regression_application.py │ │ │ └── segmentation_application.py │ │ ├── class_seg_finnet.py │ │ ├── classification_application.py │ │ ├── csv_reader.py │ │ ├── default_segmentation_csvsampler.ini │ │ ├── default_segmentation_multitask.ini │ │ ├── highres3dnet_features.py │ │ ├── multitask_classifseg_application.py │ │ ├── sampler_balanced_v2_csv.py │ │ ├── sampler_csv_rows.py │ │ ├── sampler_csvpatch.py │ │ ├── sampler_grid_v2_csv.py │ │ ├── sampler_linear_interpolate_v2_csv.py │ │ ├── sampler_random_vector_v2_csv.py │ │ ├── sampler_resize_v2_csv.py │ │ ├── sampler_uniform_v2_csv.py │ │ ├── sampler_weighted_v2_csv.py │ │ ├── segmentation_application_patchsampler.py │ │ └── toynet_features.py │ ├── deep_boosted_regression │ │ ├── README.md │ │ ├── __init__.py │ │ ├── net_DBR.ini │ │ └── regression_rec_application.py │ ├── evaluation │ │ ├── __init__.py │ │ ├── classification_evaluations.py │ │ ├── regression_evaluations.py │ │ └── segmentation_evaluations.py │ ├── layer │ │ ├── __init__.py │ │ └── resampler_optional_niftyreg.py │ ├── learning_rate_schedule │ │ ├── README.md │ │ ├── __init__.py │ │ └── decay_lr_application.py │ ├── multi_output │ │ ├── __init__.py │ │ └── multi_output_test.py │ ├── niftyreg_image_resampling │ │ ├── .gitignore │ │ ├── LICENSE │ │ ├── README.md │ │ ├── __init__.py │ │ ├── niftyreg_gpu_resampler │ │ │ ├── CMakeLists.txt │ │ │ ├── _reg_common_cuda.cu │ │ │ ├── _reg_common_cuda.h │ │ │ ├── _reg_maths.cpp │ │ │ ├── _reg_maths.h │ │ │ ├── _reg_maths_eigen.cpp │ │ │ ├── _reg_maths_eigen.h │ │ │ ├── _reg_resampling.cpp │ │ │ ├── _reg_resampling.h │ │ │ ├── _reg_resampling_gpu.cu │ │ │ ├── _reg_resampling_gpu.h │ │ │ ├── _reg_tools.cpp │ │ │ ├── _reg_tools.h │ │ │ ├── cmake │ │ │ │ └── modules │ │ │ │ │ ├── FindNumPy.cmake │ │ │ │ │ └── FindTensorflow.cmake │ │ │ ├── interpolations.h │ │ │ ├── interpolations.tpp │ │ │ ├── nifti │ │ │ │ ├── LICENSE │ │ │ │ ├── nifti1.h │ │ │ │ ├── nifti1_io.c │ │ │ │ ├── nifti1_io.h │ │ │ │ ├── znzlib.c │ │ │ │ └── znzlib.h │ │ │ ├── niftyreg_cpu_resample_gradient_op.cpp │ │ │ ├── niftyreg_cpu_resample_gradient_op.h │ │ │ ├── niftyreg_cpu_resample_image_gradient_op.cpp │ │ │ ├── niftyreg_cpu_resample_image_gradient_op.h │ │ │ ├── niftyreg_cpu_resample_op.cpp │ │ │ ├── niftyreg_cpu_resample_op.h │ │ │ ├── niftyreg_gpu_resample_gradient_op.cu │ │ │ ├── niftyreg_gpu_resample_gradient_op.h │ │ │ ├── niftyreg_gpu_resample_op.cu │ │ │ ├── niftyreg_gpu_resample_op.h │ │ │ ├── niftyreg_resample_op.h │ │ │ ├── niftyreg_resample_op.tpp │ │ │ ├── resampleKernel.cu │ │ │ ├── resampleKernel.h │ │ │ ├── resampler_boundary.h │ │ │ └── resampler_boundary.tpp │ │ ├── niftyreg_image_resampling.py │ │ ├── niftyreg_module_loader.py.in │ │ ├── setup.py │ │ └── tests │ │ │ ├── __init__.py │ │ │ ├── test_python_wrapper.py │ │ │ └── test_resampler.py │ ├── preprocessors │ │ ├── __init__.py │ │ └── preprocessing.py │ ├── regression_weighted_sampler │ │ ├── README.md │ │ ├── __init__.py │ │ └── isample_regression.py │ ├── sampler_pairwise │ │ ├── __init__.py │ │ ├── sampler_pairwise_resize.py │ │ ├── sampler_pairwise_resize_csv.py │ │ ├── sampler_pairwise_uniform.py │ │ └── sampler_pairwise_uniform_csv.py │ ├── segmentation_bf_aug │ │ ├── __init__.py │ │ └── segmentation_application_bfaug.py │ ├── segmentation_selective_sampler │ │ ├── README.md │ │ ├── __init__.py │ │ ├── sampler_selective.py │ │ ├── selective_seg.ini │ │ ├── ss_app.py │ │ └── test_sampler_selective.py │ └── ultrasound_simulator_gan │ │ ├── README.md │ │ ├── __init__.py │ │ └── ultrasound_simulator_gan.py ├── engine │ ├── README.md │ ├── __init__.py │ ├── application_driver.py │ ├── application_factory.py │ ├── application_initializer.py │ ├── application_iteration.py │ ├── application_optimiser.py │ ├── application_variables.py │ ├── handler_console.py │ ├── handler_early_stopping.py │ ├── handler_gradient.py │ ├── handler_model.py │ ├── handler_network_output.py │ ├── handler_performance.py │ ├── handler_sampler.py │ ├── handler_tensorboard.py │ ├── image_window.py │ ├── image_window_dataset.py │ ├── sampler_balanced_v2.py │ ├── sampler_grid_v2.py │ ├── sampler_linear_interpolate_v2.py │ ├── sampler_random_vector_v2.py │ ├── sampler_resize_v2.py │ ├── sampler_uniform_v2.py │ ├── sampler_weighted_v2.py │ ├── signal.py │ ├── windows_aggregator_base.py │ ├── windows_aggregator_grid.py │ ├── windows_aggregator_identity.py │ └── windows_aggregator_resize.py ├── evaluation │ ├── __init__.py │ ├── base_evaluations.py │ ├── base_evaluator.py │ ├── classification_evaluations.py │ ├── classification_evaluator.py │ ├── evaluation_application_driver.py │ ├── pairwise_measures.py │ ├── region_properties.py │ ├── regression_evaluations.py │ ├── regression_evaluator.py │ ├── segmentation_evaluations.py │ └── segmentation_evaluator.py ├── io │ ├── __init__.py │ ├── image_loader.py │ ├── image_reader.py │ ├── image_sets_partitioner.py │ ├── image_type.py │ └── misc_io.py ├── layer │ ├── README.md │ ├── __init__.py │ ├── activation.py │ ├── additive_upsample.py │ ├── affine_augmentation.py │ ├── approximated_smoothing.py │ ├── base_layer.py │ ├── binary_masking.py │ ├── bn.py │ ├── channel_sparse_convolution.py │ ├── convolution.py │ ├── crf.py │ ├── crop.py │ ├── deconvolution.py │ ├── dilatedcontext.py │ ├── discrete_label_normalisation.py │ ├── downsample.py │ ├── downsample_res_block.py │ ├── elementwise.py │ ├── figures │ │ ├── elu_eq.pdf │ │ ├── elu_img.png │ │ ├── prelu_eq.pdf │ │ ├── prelu_img.png │ │ ├── relu_eq.pdf │ │ ├── relu_img.png │ │ ├── sigmoid_eq.pdf │ │ ├── sigmoid_img.png │ │ ├── softplus_eq.pdf │ │ ├── softplus_img.png │ │ ├── softsign_eq.pdf │ │ ├── softsign_img.png │ │ ├── tanh_eq.pdf │ │ └── tanh_img.png │ ├── fully_connected.py │ ├── gan_blocks.py │ ├── gn.py │ ├── grid_warper.py │ ├── histogram_normalisation.py │ ├── layer_util.py │ ├── linear_resize.py │ ├── loss_autoencoder.py │ ├── loss_classification.py │ ├── loss_classification_multi.py │ ├── loss_gan.py │ ├── loss_regression.py │ ├── loss_segmentation.py │ ├── mean_variance_normalisation.py │ ├── pad.py │ ├── post_processing.py │ ├── rand_bias_field.py │ ├── rand_elastic_deform.py │ ├── rand_flip.py │ ├── rand_rotation.py │ ├── rand_spatial_scaling.py │ ├── resampler.py │ ├── residual_unit.py │ ├── rgb_histogram_equilisation.py │ ├── spatial_gradient.py │ ├── spatial_transformer.py │ ├── squeeze_excitation.py │ ├── subpixel.py │ ├── upsample.py │ └── upsample_res_block.py ├── network │ ├── README.md │ ├── __init__.py │ ├── base_net.py │ ├── deepmedic.py │ ├── dense_vnet.py │ ├── highres3dnet.py │ ├── highres3dnet_large.py │ ├── highres3dnet_small.py │ ├── holistic_net.py │ ├── interventional_affine_net.py │ ├── interventional_dense_net.py │ ├── interventional_hybrid_net.py │ ├── no_new_net.py │ ├── resnet.py │ ├── scalenet.py │ ├── se_resnet.py │ ├── simple_gan.py │ ├── simulator_gan.py │ ├── toynet.py │ ├── unet.py │ ├── unet_2d.py │ ├── vae.py │ └── vnet.py └── utilities │ ├── __init__.py │ ├── decorators.py │ ├── download.py │ ├── filename_matching.py │ ├── histogram_standardisation.py │ ├── niftynet_global_config.py │ ├── niftynet_launch_config.py │ ├── restore_initializer.py │ ├── user_parameters_custom.py │ ├── user_parameters_default.py │ ├── user_parameters_helper.py │ ├── user_parameters_parser.py │ ├── user_parameters_regex.py │ ├── util_common.py │ ├── util_csv.py │ ├── util_import.py │ ├── versioneer_version.py │ └── versioning.py ├── requirements.txt ├── run_test.sh ├── setup.cfg ├── setup.py ├── tests ├── README.md ├── __init__.py ├── activation_test.py ├── additive_upsample_test.py ├── affine_augmentation_test.py ├── application_driver_test.py ├── application_factory_test.py ├── approximated_smoothing_test.py ├── binary_masking_test.py ├── bn_test.py ├── channel_sparse_convolution_test.py ├── classification_evaluator_test.py ├── convolution_test.py ├── crf_test.py ├── crop_test.py ├── deconvolution_test.py ├── deepmedic_test.py ├── dense_vnet_test.py ├── dilatedcontext_test.py ├── download_test.py ├── downsample_res_block_test.py ├── downsample_test.py ├── driver_partitioner_test.py ├── elementwise_test.py ├── entry_point_test.py ├── evaluation_test.py ├── filename_matching_test.py ├── fully_connected_test.py ├── get_gpu_index.py ├── gn_test.py ├── gradient_collector_test.py ├── grid_warper_test.py ├── handler_console_test.py ├── handler_early_stopping_test.py ├── handler_network_output_test.py ├── handler_performance_test.py ├── highres3dnet_test.py ├── highresblock_test.py ├── histogram_normalisation_test.py ├── holistic_net_test.py ├── image_loader_test.py ├── image_reader_test.py ├── image_sets_partitioner_test.py ├── image_type_test.py ├── image_window_dataset_generator_test.py ├── image_window_dataset_test.py ├── image_window_test.py ├── interventional_affine_net_test.py ├── interventional_dense_net_test.py ├── interventional_hybrid_net_test.py ├── linear_resize_test.py ├── loss_classification_multi_test.py ├── loss_classification_test.py ├── loss_regression_test.py ├── loss_segmentation_test.py ├── mean_variance_normalisation_test.py ├── niftynet_global_config_test.py ├── niftynet_testcase.py ├── output_collector_test.py ├── pad_test.py ├── post_processing_test.py ├── pylintrc ├── rand_bias_field_test.py ├── rand_elastic_deformation_test.py ├── rand_flip_test.py ├── rand_rotation_test.py ├── rand_spatial_scaling_test.py ├── reader_modular_test.py ├── resampler_batch_test.py ├── resampler_grid_warper_test.py ├── resampler_optional_niftyreg_test.py ├── resampler_test.py ├── residual_unit_test.py ├── residual_upsample_test.py ├── resnet_test.py ├── restorer_test.py ├── rgb_histogram_equilisation_test.py ├── run_vars_test.py ├── sampler_balanced_v2_test.py ├── sampler_csvpatch_v2_test.py ├── sampler_grid_v2_test.py ├── sampler_linear_interpolate_v2_test.py ├── sampler_random_vector_v2_test.py ├── sampler_resize_v2_test.py ├── sampler_uniform_v2_test.py ├── sampler_weighted_v2_test.py ├── scaleblock_test.py ├── scalenet_test.py ├── se_resnet_test.py ├── segmentation_evaluator_test.py ├── simple_gan_test.py ├── spatial_gradient_test.py ├── spatial_transformer_test.py ├── squeeze_excitation_test.py ├── subpixel_test.py ├── test_model_zoo.py ├── toy_application.py ├── toynet_test.py ├── unet_2d_test.py ├── unet_test.py ├── unetblock_test.py ├── upsample_res_block_test.py ├── upsample_test.py ├── user_parameters_default_test.py ├── user_parameters_regex_test.py ├── util_import_test.py ├── versioning_test.py ├── vnet_test.py ├── vnetblock_test.py ├── windows_aggregator_grid_v2_test.py ├── windows_aggregator_identity_v2_test.py └── windows_aggregator_resize_v2_test.py ├── train_modality_classification.ini └── versioneer.py /.gitattributes: -------------------------------------------------------------------------------- 1 | niftynet/utilities/versioneer_version.py export-subst 2 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/niftynet-issue-template.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: niftynet issue template 3 | about: template for reporting bugs/requesting new features 4 | 5 | --- 6 | 7 | Before filing your issue, please note that it might be more appropriate for Stack Overflow, using the `niftynet` tag: 8 | https://stackoverflow.com/questions/tagged/niftynet 9 | 10 | Read the following to decide whether to file an issue here or ask a question on Stack Overflow: 11 | 12 | **Issue** → **Action** 13 | - How do I ...? → Stack Overflow 14 | - I got this error, why? → Stack Overflow 15 | - I got this error and I'm sure it's a bug → Delete this template and file an issue here 16 | - I have an idea/request → Delete this template and file an issue here 17 | 18 | If you post your question on Stack Overflow, please explain: 19 | 20 | 1. What you were trying to do (and why) 21 | 2. What happened (include command output) 22 | 3. What you expected to happen 23 | 4. Step-by-step reproduction instructions 24 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## Status 2 | **READY/WORK IN PROGRESS/HOLD** 3 | 4 | ## Description 5 | A few sentences describing the overall goals of the pull request's commits. 6 | 7 | ## Types of changes 8 | 9 | - [ ] Bug fix (non-breaking change which fixes an issue) 10 | - [ ] New feature (non-breaking change which adds functionality) 11 | - [ ] Breaking change (fix or feature that would cause existing functionality to change) 12 | - [ ] My code follows the code style of this project. 13 | - [ ] I have added tests to cover my changes. 14 | - [ ] All new and existing tests passed. 15 | 16 | 17 | ## Todos 18 | - [ ] Tests 19 | - [ ] Documentation 20 | 21 | 22 | ## Impacted Areas in Application 23 | List general components of the application that this PR will affect: 24 | * 25 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[cod] 2 | *$py.class 3 | __pycache__/ 4 | .idea/ 5 | *.pkl 6 | models/ 7 | output/ 8 | seg_output* 9 | user/ 10 | emerald_* 11 | example_volumes* 12 | .coverage* 13 | testing_data* 14 | *.nii.gz 15 | *.nii 16 | *.tar.gz 17 | *.csv 18 | *.swp 19 | data/brain_parcellation/OASIS 20 | data/u-net 21 | data/csv_data 22 | data/._csv_data 23 | dist 24 | build 25 | *.egg-info 26 | *.zip 27 | *.mhd 28 | *.raw 29 | doc/source/niftynet* 30 | doc/source/modules.rst 31 | .vscode/ 32 | .ipynb_checkpoints 33 | demos/unet/run_U373.sh 34 | demos/unet/run_hela.sh 35 | 36 | -------------------------------------------------------------------------------- /.gitlab/issue_templates/Bug.md: -------------------------------------------------------------------------------- 1 | ## Expected behavior 2 | 3 | 4 | ## Actual behavior 5 | 6 | 7 | ## Steps to reproduce the behavior 8 | -------------------------------------------------------------------------------- /.gitlab/merge_request_templates/Pull_request.md: -------------------------------------------------------------------------------- 1 | ## Status 2 | **READY/IN DEVELOPMENT/HOLD** 3 | 4 | ## Description 5 | A few sentences describing the overall goals of the pull request's commits. 6 | 7 | ## Types of changes 8 | 9 | - [ ] Bug fix (non-breaking change which fixes an issue) 10 | - [ ] New feature (non-breaking change which adds functionality) 11 | - [ ] Breaking change (fix or feature that would cause existing functionality to change) 12 | - [ ] My code follows the code style of this project. 13 | - [ ] I have added tests to cover my changes. 14 | - [ ] All new and existing tests passed. 15 | 16 | 17 | ## Todos 18 | - [ ] Tests 19 | - [ ] Documentation 20 | 21 | 22 | ## Impacted Areas in Application 23 | List general components of the application that this PR will affect: 24 | * 25 | -------------------------------------------------------------------------------- /.readthedocs.yml: -------------------------------------------------------------------------------- 1 | # Don't build any extra formats 2 | formats: 3 | - none 4 | 5 | requirements_file: doc/requirements.txt 6 | -------------------------------------------------------------------------------- /ci/bundlewheel.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # remove existing installers 4 | rm -f $niftynet_dir/dist/*.whl 5 | 6 | # bundle installer 7 | python setup.py bdist_wheel 8 | 9 | # inform other scripts of wheel's location 10 | export niftynet_wheel=$(ls $niftynet_dir/dist/*.whl) # there will be only one file! 11 | -------------------------------------------------------------------------------- /ci/findwheel.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | export niftynet_wheel=$(ls $niftynet_dir/dist/*.whl) # there will be only one file! 4 | 5 | -------------------------------------------------------------------------------- /ci/utils.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # so that CI script will fail when e.g. previous command succeeds: 4 | function fail_on_success 5 | { 6 | exit_status=$? 7 | if [[ "$exit_status" -eq "0" ]]; then 8 | echo "Build failed due to last exit status being $exit_status" 9 | exit 1 10 | fi 11 | } 12 | -------------------------------------------------------------------------------- /config/GAN_demo_train_config.ini: -------------------------------------------------------------------------------- 1 | ############################ input configuration sections 2 | [usimage] 3 | csv_file= 4 | path_to_search = ./example_volumes/gan_test_data 5 | filename_contains = frame,img 6 | filename_not_contains = 7 | spatial_window_size = (128, 128, 1) 8 | interp_order = 3 9 | 10 | [conditioningX] 11 | path_to_search = ./example_volumes/gan_test_data 12 | filename_contains = frame,coordX 13 | spatial_window_size = (128, 128, 1) 14 | 15 | [conditioningY] 16 | path_to_search = ./example_volumes/gan_test_data 17 | filename_contains = frame,coordY 18 | spatial_window_size = (128, 128, 1) 19 | 20 | [conditioningZ] 21 | path_to_search = ./example_volumes/gan_test_data 22 | filename_contains = frame,coordZ 23 | spatial_window_size = (128, 128, 1) 24 | 25 | [SYSTEM] 26 | cuda_devices = "" 27 | num_threads = 10 28 | num_gpus = 1 29 | model_dir = ./models/model_us_simulator_gan_demo 30 | queue_length = 20 31 | 32 | [NETWORK] 33 | #name = simulator_gan 34 | name = niftynet.network.simulator_gan.SimulatorGAN 35 | activation_function = prelu 36 | batch_size = 36 37 | #decay = 1e-7 38 | reg_type = L2 39 | 40 | histogram_ref_file = ./example_volumes/monomodal_parcellation/standardisation_models.txt 41 | norm_type = percentile 42 | cutoff = (0.01, 0.99) 43 | 44 | [TRAINING] 45 | sample_per_volume = 1 46 | #rotation_angle = (-10.0, 10.0) 47 | #scaling_percentage = (-10.0, 10.0) 48 | lr = 0.0001 49 | loss_type = CrossEntropy 50 | starting_iter = 0 51 | save_every_n = 2000 52 | max_iter = 10000 53 | max_checkpoints = 20 54 | 55 | [INFERENCE] 56 | #inference_iter = 5000 57 | save_seg_dir = ./output/us_simulator_gan_demo 58 | 59 | [GAN] 60 | image=usimage 61 | conditioning=conditioningX,conditioningY,conditioningZ 62 | noise_size = 100 63 | n_interpolations=10 64 | -------------------------------------------------------------------------------- /config/README.md: -------------------------------------------------------------------------------- 1 | # Configuration file 2 | *[This folder](../config) presents a few examples of configuration files for NiftyNet 3 | [applications](#../niftynet/application/).* 4 | 5 | Please check out the configuration specifications at 6 | 7 | [http://niftynet.readthedocs.io/en/dev/config_spec.html](http://niftynet.readthedocs.io/en/dev/config_spec.html) 8 | -------------------------------------------------------------------------------- /config/deepmedic_config.ini: -------------------------------------------------------------------------------- 1 | [T1] 2 | path_to_search = ./example_volumes/monomodal_parcellation 3 | filename_contains = T1 4 | filename_not_contains = 5 | spatial_window_size = (57, 57, 57) 6 | pixdim = (1.0, 1.0, 1.0) 7 | axcodes=(A, R, S) 8 | interp_order = 3 9 | 10 | [parcellation] 11 | path_to_search = ./example_volumes/monomodal_parcellation 12 | filename_contains = Label 13 | filename_not_contains = 14 | spatial_window_size = (9, 9, 9) 15 | pixdim = (1.0, 1.0, 1.0) 16 | axcodes=(A, R, S) 17 | interp_order = 0 18 | 19 | ############################## system configuration sections 20 | [SYSTEM] 21 | cuda_devices = "" 22 | num_threads = 2 23 | num_gpus = 1 24 | model_dir = ./models/model_deepmedic 25 | 26 | [NETWORK] 27 | name = deepmedic 28 | activation_function = prelu 29 | batch_size = 128 30 | decay = 0 31 | reg_type = L2 32 | 33 | # volume level preprocessing 34 | volume_padding_size = 12 35 | # histogram normalisation 36 | histogram_ref_file = ./example_volumes/monomodal_parcellation/standardisation_models.txt 37 | norm_type = percentile 38 | cutoff = (0.01, 0.99) 39 | normalisation = True 40 | whitening = True 41 | normalise_foreground_only=True 42 | foreground_type = otsu_plus 43 | multimod_foreground_type = and 44 | 45 | queue_length = 128 46 | window_sampling = uniform 47 | 48 | [TRAINING] 49 | sample_per_volume = 32 50 | rotation_angle = (-10.0, 10.0) 51 | scaling_percentage = (-10.0, 10.0) 52 | lr = 0.01 53 | loss_type = Dice 54 | starting_iter = 0 55 | save_every_n = 5 56 | max_iter = 10 57 | max_checkpoints = 20 58 | 59 | [INFERENCE] 60 | border = (36, 36, 36) 61 | #inference_iter = 10 62 | save_seg_dir = ./output/deepmedic 63 | output_interp_order = 0 64 | spatial_window_size = (195, 195, 195) 65 | 66 | ############################ custom configuration sections 67 | [SEGMENTATION] 68 | image = T1 69 | label = parcellation 70 | output_prob = False 71 | num_classes = 160 72 | label_normalisation = True 73 | -------------------------------------------------------------------------------- /config/default_eval_config.ini: -------------------------------------------------------------------------------- 1 | [output modality 1] 2 | path_to_search = /Users/csudre/Temp/Seg 3 | filename_contains = Lesion,group2 4 | filename_not_contains = 5 | 6 | [ref 1] 7 | path_to_search = /Users/csudre/Temp/Ref 8 | filename_contains = Lesion 9 | filename_not_contains = 10 | 11 | [data 1] 12 | path_to_search = /Users/csudre/Temp/Data 13 | filename_contains = T2 14 | filename_not_contains = 15 | 16 | [data 2] 17 | path_to_search = /Users/csudre/Temp/Data 18 | filename_contains = T1 19 | filename_not_contains = 20 | 21 | [settings] 22 | application_type = segmentation 23 | 24 | # default parameters 25 | threshold = 0.5 26 | step = 0.5 27 | ext = .nii.gz 28 | 29 | #(choice between probabilistic labels 'prob', binary segmentation 'binary' and discrete labels 'discrete') 30 | seg_type = discrete 31 | 32 | # **statistical analysis system parameters 33 | save_csv_dir = /Users/csudre/Temp 34 | save_name = Special 35 | save_discrete = True 36 | save_maps = True 37 | -------------------------------------------------------------------------------- /config/default_monomodal_regression.ini: -------------------------------------------------------------------------------- 1 | [INPUTIMAGE] 2 | spatial_window_size=(64, 64, 64) 3 | filename_contains=pat 4 | filename_not_contains= 5 | path_to_search=./example_volumes/monomodal_parcellation 6 | interp_order=3 7 | 8 | [REGRESSTARGET] 9 | spatial_window_size=(64, 64, 64) 10 | filename_contains=pat 11 | filename_not_contains=() 12 | path_to_search=./example_volumes/monomodal_parcellation 13 | interp_order=3 14 | 15 | 16 | [TRAINING] 17 | loss_type=RMSE 18 | sample_per_volume=32 19 | tensorboard_every_n=20 20 | max_iter=5000 21 | save_every_n=200 22 | max_checkpoints=10 23 | optimiser=adam 24 | lr=0.001 25 | starting_iter=0 26 | 27 | [NETWORK] 28 | cutoff=(0.01, 0.99) 29 | multimod_foreground_type=and 30 | volume_padding_size=(8, 8, 8) 31 | name=highres3dnet 32 | decay=0.00001 33 | activation_function=prelu 34 | normalise_foreground_only=False 35 | histogram_ref_file=./model/standardisation_models.txt 36 | batch_size=2 37 | norm_type=percentile 38 | foreground_type=otsu_plus 39 | window_sampling=uniform 40 | whitening=False 41 | reg_type=L1 42 | normalisation=False 43 | 44 | [INFERENCE] 45 | border=(16, 16, 16) 46 | output_interp_order=3 47 | #inference_iter=600 48 | save_seg_dir=./output/ 49 | spatial_window_size=(136, 136, 136) 50 | 51 | [SYSTEM] 52 | cuda_devices="" 53 | num_gpus=1 54 | num_threads=2 55 | queue_length=5 56 | model_dir=./models/model_monomodal_regression 57 | 58 | [EVALUATION] 59 | 60 | [REGRESSION] 61 | output=REGRESSTARGET 62 | image=INPUTIMAGE 63 | loss_border=8 64 | -------------------------------------------------------------------------------- /config/default_monomodal_regression_eval.ini: -------------------------------------------------------------------------------- 1 | [INPUTIMAGE] 2 | spatial_window_size=(64, 64, 64) 3 | filename_contains=Correct_WS3WT3WC1MergedSPCP_,_corr_corrIT 4 | filename_not_contains= 5 | path_to_search=./NiftyNetEvalTest 6 | interp_order=3 7 | 8 | [REGRESSTARGET] 9 | spatial_window_size=(64, 64, 64) 10 | filename_contains=CHJP_,_vote 11 | filename_not_contains=() 12 | path_to_search=./NiftyNetEvalTest 13 | interp_order=3 14 | 15 | 16 | [TRAINING] 17 | loss_type=RMSE 18 | sample_per_volume=32 19 | tensorboard_every_n=20 20 | max_iter=5000 21 | save_every_n=200 22 | max_checkpoints=10 23 | optimiser=adam 24 | lr=0.001 25 | starting_iter=0 26 | 27 | [NETWORK] 28 | cutoff=(0.01, 0.99) 29 | multimod_foreground_type=and 30 | volume_padding_size=(8, 8, 8) 31 | name=highres3dnet 32 | decay=0.00001 33 | activation_function=prelu 34 | normalise_foreground_only=False 35 | histogram_ref_file=./model/standardisation_models.txt 36 | batch_size=2 37 | norm_type=percentile 38 | foreground_type=otsu_plus 39 | window_sampling=uniform 40 | whitening=False 41 | reg_type=L1 42 | normalisation=False 43 | 44 | [INFERENCE] 45 | border=(16, 16, 16) 46 | output_interp_order=3 47 | #inference_iter=600 48 | save_seg_dir=./output/ 49 | spatial_window_size=(136, 136, 136) 50 | 51 | [SYSTEM] 52 | cuda_devices="" 53 | num_gpus=1 54 | num_threads=2 55 | queue_length=5 56 | model_dir=./models/monomodal_regression 57 | 58 | [EVALUATION] 59 | 60 | save_csv_dir = ./NiftyNetEvalTest 61 | evaluations = mse,rmse,mae 62 | 63 | [REGRESSION] 64 | output=REGRESSTARGET 65 | inferred=INPUTIMAGE 66 | loss_border=8 67 | -------------------------------------------------------------------------------- /config/default_multimodal_segmentation_eval.ini: -------------------------------------------------------------------------------- 1 | ############################ input configuration sections 2 | [seg] 3 | csv_file= 4 | path_to_search = ./NiftyNetTestEval 5 | filename_contains = Correct_WS3WT3WC1MergedSPCP_,_corr_corrIT 6 | filename_not_contains = 7 | spatial_window_size = (64, 64, 64) 8 | interp_order = 0 9 | 10 | 11 | [label] 12 | csv_file= 13 | path_to_search = ./NiftyNetTestEval 14 | filename_contains = CHJP_,_vote 15 | filename_not_contains = 16 | spatial_window_size = (64, 64, 64) 17 | interp_order = 0 18 | 19 | ############################## system configuration sections 20 | [SYSTEM] 21 | cuda_devices = "" 22 | num_threads = 2 23 | num_gpus = 1 24 | model_dir = ./models/model_multimodal_toy 25 | queue_length = 20 26 | 27 | [NETWORK] 28 | #name = holistic_scalenet 29 | name = toynet 30 | activation_function = prelu 31 | batch_size = 1 32 | decay = 0 33 | reg_type = L2 34 | 35 | # volume level preprocessing 36 | volume_padding_size = 21 37 | # histogram normalisation 38 | #histogram_ref_file = ./example_volumes/multimodal_parcellation 39 | #/standardisation_models.txt 40 | #norm_type = percentile 41 | cutoff = (0.01, 0.99) 42 | normalisation = False 43 | whitening = False 44 | 45 | normalise_foreground_only = False 46 | foreground_type = otsu_plus 47 | multimod_foreground_type = and 48 | 49 | [TRAINING] 50 | sample_per_volume = 32 51 | # rotation_angle = (-10.0, 10.0) 52 | # scaling_percentage = (-10.0, 10.0) 53 | # random_flipping_axes= 1 54 | lr = 0.01 55 | loss_type = WGDL 56 | starting_iter = 0 57 | save_every_n = 100 58 | max_iter = 10 59 | max_checkpoints = 20 60 | 61 | [INFERENCE] 62 | border = 5 63 | #inference_iter = 10 64 | save_seg_dir = ./output/toy 65 | output_interp_order = 0 66 | spatial_window_size = (64, 64, 64) 67 | 68 | [EVALUATION] 69 | save_csv_dir = ./NiftyNetTestEval 70 | evaluations = dice,jaccard,false_positive_rate,positive_predictive_values,n_pos_ref,n_pos_seg 71 | 72 | 73 | ############################ custom configuration sections 74 | [SEGMENTATION] 75 | #image = modality1 76 | # describes how to combine multiple input sources 77 | #image = T1,T2,T1c,Flair 78 | inferred = seg 79 | label = label 80 | weight = T1 81 | output_prob = False 82 | num_classes = 5 83 | label_normalisation = False 84 | evaluation_units = foreground 85 | -------------------------------------------------------------------------------- /config/default_segmentation.ini: -------------------------------------------------------------------------------- 1 | ############################ input configuration sections 2 | [modality1] 3 | csv_file= 4 | path_to_search = ./example_volumes/monomodal_parcellation 5 | filename_contains = T1 6 | filename_removefromid = _T1 7 | filename_not_contains = 8 | spatial_window_size = (20, 42, 42) 9 | interp_order = 3 10 | pixdim=(1.0, 1.0, 1.0) 11 | axcodes=(A, R, S) 12 | 13 | [label] 14 | path_to_search = ./example_volumes/monomodal_parcellation 15 | filename_contains = Label 16 | filename_not_contains = 17 | filename_removefromid = _Label 18 | spatial_window_size = (20, 42, 42) 19 | interp_order = 0 20 | pixdim=(1.0, 1.0, 1.0) 21 | axcodes=(A, R, S) 22 | 23 | ############################## system configuration sections 24 | [SYSTEM] 25 | cuda_devices = "" 26 | num_threads = 2 27 | num_gpus = 1 28 | model_dir = ./models/model_monomodal_toy 29 | 30 | [NETWORK] 31 | name = toynet 32 | activation_function = prelu 33 | batch_size = 1 34 | decay = 0.1 35 | reg_type = L2 36 | 37 | # volume level preprocessing 38 | volume_padding_size = 21 39 | # histogram normalisation 40 | histogram_ref_file = ./example_volumes/monomodal_parcellation/standardisation_models.txt 41 | norm_type = percentile 42 | cutoff = (0.01, 0.99) 43 | normalisation = False 44 | whitening = False 45 | normalise_foreground_only=True 46 | foreground_type = otsu_plus 47 | multimod_foreground_type = and 48 | 49 | queue_length = 20 50 | 51 | 52 | [TRAINING] 53 | sample_per_volume = 32 54 | rotation_angle = (-10.0, 10.0) 55 | scaling_percentage = (-10.0, 10.0) 56 | random_flipping_axes= 1 57 | lr = 0.01 58 | loss_type = Dice 59 | starting_iter = 0 60 | save_every_n = 100 61 | max_iter = 10 62 | max_checkpoints = 20 63 | 64 | [INFERENCE] 65 | border = (0, 0, 1) 66 | #inference_iter = 10 67 | save_seg_dir = ./output/toy 68 | output_interp_order = 0 69 | spatial_window_size = (0, 0, 3) 70 | 71 | [EVALUATION] 72 | evaluations=Dice 73 | 74 | ############################ custom configuration sections 75 | [SEGMENTATION] 76 | image = modality1 77 | label = label 78 | output_prob = False 79 | num_classes = 160 80 | label_normalisation = True 81 | -------------------------------------------------------------------------------- /config/default_segmentation_bf.ini: -------------------------------------------------------------------------------- 1 | ############################ input configuration sections 2 | [modality1] 3 | csv_file= 4 | path_to_search = ./example_volumes/monomodal_parcellation 5 | filename_contains = T1 6 | filename_not_contains = 7 | spatial_window_size = (20, 42, 42) 8 | interp_order = 3 9 | pixdim=(1.0, 1.0, 1.0) 10 | axcodes=(A, R, S) 11 | 12 | [label] 13 | path_to_search = ./example_volumes/monomodal_parcellation 14 | filename_contains = Label 15 | filename_not_contains = 16 | spatial_window_size = (20, 42, 42) 17 | interp_order = 0 18 | pixdim=(1.0, 1.0, 1.0) 19 | axcodes=(A, R, S) 20 | 21 | ############################## system configuration sections 22 | [SYSTEM] 23 | cuda_devices = "" 24 | num_threads = 2 25 | num_gpus = 1 26 | model_dir = ./models/model_monomodal_toy 27 | 28 | [NETWORK] 29 | name = toynet 30 | activation_function = prelu 31 | batch_size = 1 32 | decay = 0.1 33 | reg_type = L2 34 | 35 | # volume level preprocessing 36 | volume_padding_size = 21 37 | # histogram normalisation 38 | histogram_ref_file = ./example_volumes/monomodal_parcellation/standardisation_models.txt 39 | norm_type = percentile 40 | cutoff = (0.01, 0.99) 41 | normalisation = False 42 | whitening = False 43 | normalise_foreground_only=True 44 | foreground_type = otsu_plus 45 | multimod_foreground_type = and 46 | 47 | queue_length = 20 48 | 49 | 50 | [TRAINING] 51 | sample_per_volume = 32 52 | rotation_angle = 53 | scaling_percentage = 54 | bf_order = 3 55 | bias_field_range = (-0.5, 0.5) 56 | random_flipping_axes= 1 57 | lr = 0.01 58 | loss_type = Dice 59 | starting_iter = 0 60 | save_every_n = 100 61 | max_iter = 10 62 | max_checkpoints = 20 63 | 64 | [INFERENCE] 65 | border = (0, 0, 1) 66 | #inference_iter = 10 67 | save_seg_dir = ./output/toy 68 | output_interp_order = 0 69 | spatial_window_size = (0, 0, 3) 70 | 71 | ############################ custom configuration sections 72 | [SEGMENTATION] 73 | image = modality1 74 | label = label 75 | output_prob = False 76 | num_classes = 160 77 | label_normalisation = True 78 | -------------------------------------------------------------------------------- /config/densevnet_config.ini: -------------------------------------------------------------------------------- 1 | ############################ input configuration sections 2 | [image] 3 | path_to_search = ./example_volumes/multimodal_BRATS 4 | filename_contains = _T1c 5 | spatial_window_size = (144, 144, 144) 6 | interp_order = 1 7 | axcodes=(A, R, S) 8 | 9 | [label] 10 | path_to_search = ./example_volumes/multimodal_BRATS 11 | filename_contains = _Label 12 | spatial_window_size = (144, 144, 144) 13 | interp_order = 0 14 | axcodes=(A, R, S) 15 | 16 | ############################## system configuration sections 17 | [SYSTEM] 18 | cuda_devices = "" 19 | num_threads = 2 20 | num_gpus = 1 21 | model_dir = models/model_dense_vnet 22 | queue_length = 36 23 | 24 | [NETWORK] 25 | name = dense_vnet 26 | batch_size = 6 27 | 28 | # volume level preprocessing 29 | volume_padding_size = 0 30 | window_sampling = resize 31 | histogram_ref_file = ./example_volumes/multimodal_BRATS/standardisation_models.txt 32 | 33 | [TRAINING] 34 | sample_per_volume = 1 35 | lr = 0.001 36 | loss_type = Dice 37 | starting_iter = 0 38 | save_every_n = 1000 39 | max_iter = 3001 40 | 41 | [INFERENCE] 42 | border = (0, 0, 0) 43 | inference_iter = 3000 44 | output_interp_order = 0 45 | spatial_window_size = (144, 144, 144) 46 | save_seg_dir = ./output/dense_vnet 47 | 48 | [EVALUATION] 49 | 50 | ############################ custom configuration sections 51 | [SEGMENTATION] 52 | image = image 53 | label = label 54 | label_normalisation = True 55 | output_prob = False 56 | num_classes = 2 57 | -------------------------------------------------------------------------------- /config/highres3dnet_config.ini: -------------------------------------------------------------------------------- 1 | [T1] 2 | path_to_search = ./example_volumes/monomodal_parcellation 3 | filename_contains = T1 4 | filename_not_contains = 5 | spatial_window_size = (32, 32, 32) 6 | pixdim = (1.0, 1.0, 1.0) 7 | axcodes=(A, R, S) 8 | interp_order = 3 9 | 10 | [parcellation] 11 | path_to_search = ./example_volumes/monomodal_parcellation 12 | filename_contains = Label 13 | filename_not_contains = 14 | spatial_window_size = (32, 32, 32) 15 | pixdim = (1.0, 1.0, 1.0) 16 | axcodes=(A, R, S) 17 | interp_order = 0 18 | 19 | 20 | ############################## system configuration sections 21 | [SYSTEM] 22 | cuda_devices = "" 23 | num_threads = 2 24 | num_gpus = 1 25 | model_dir = ./models/model_highres3dnet 26 | 27 | [NETWORK] 28 | name = highres3dnet 29 | activation_function = relu 30 | batch_size = 1 31 | decay = 0 32 | reg_type = L2 33 | 34 | # volume level preprocessing 35 | volume_padding_size = 21 36 | # histogram normalisation 37 | histogram_ref_file = ./example_volumes/monomodal_parcellation/standardisation_models.txt 38 | norm_type = percentile 39 | cutoff = (0.01, 0.99) 40 | normalisation = True 41 | whitening = True 42 | normalise_foreground_only=True 43 | foreground_type = otsu_plus 44 | multimod_foreground_type = and 45 | 46 | queue_length = 1 47 | window_sampling = uniform 48 | 49 | [TRAINING] 50 | sample_per_volume = 32 51 | rotation_angle = (-10.0, 10.0) 52 | scaling_percentage = (-10.0, 10.0) 53 | lr = 0.0001 54 | loss_type = Dice 55 | starting_iter = 0 56 | save_every_n = 5 57 | max_iter = 6 58 | max_checkpoints = 20 59 | 60 | [INFERENCE] 61 | border = (5, 5, 5) 62 | #inference_iter = 10 63 | save_seg_dir = ./output/highres3dnet 64 | output_interp_order = 0 65 | spatial_window_size = (0, 0, 3) 66 | 67 | ############################ custom configuration sections 68 | [SEGMENTATION] 69 | image = T1 70 | label = parcellation 71 | output_prob = False 72 | num_classes = 160 73 | label_normalisation = True 74 | -------------------------------------------------------------------------------- /config/holisticnet_config.ini: -------------------------------------------------------------------------------- 1 | [T1] 2 | path_to_search = ./example_volumes/multimodal_BRATS 3 | filename_contains = T1 4 | filename_not_contains = T1c 5 | spatial_window_size = (32, 32, 32) 6 | interp_order = 3 7 | 8 | [Flair] 9 | path_to_search = ./example_volumes/multimodal_BRATS 10 | filename_contains = Flair 11 | filename_not_contains = 12 | spatial_window_size = (32, 32, 32) 13 | interp_order = 3 14 | 15 | [T1c] 16 | path_to_search = ./example_volumes/multimodal_BRATS 17 | filename_contains = T1c 18 | filename_not_contains = 19 | spatial_window_size = (32, 32, 32) 20 | interp_order = 3 21 | 22 | [T2] 23 | path_to_search = ./example_volumes/multimodal_BRATS 24 | filename_contains = T2 25 | filename_not_contains = 26 | spatial_window_size = (32, 32, 32) 27 | interp_order = 3 28 | 29 | [label] 30 | path_to_search = ./example_volumes/multimodal_BRATS 31 | filename_contains = Label 32 | filename_not_contains = T1 33 | spatial_window_size = (32, 32, 32) 34 | interp_order = 0 35 | 36 | [SYSTEM] 37 | cuda_devices = "" 38 | num_threads = 4 39 | num_gpus = 1 40 | model_dir = ./models/model_holisticnet 41 | 42 | 43 | [NETWORK] 44 | name = holisticnet 45 | activation_function = elu 46 | batch_size = 1 47 | decay = 0.1 48 | reg_type = L2 49 | 50 | # volume level preprocessing 51 | volume_padding_size = 21 52 | # histogram normalisation 53 | histogram_ref_file = ./example_volumes/multimodal_BRATS/standardisation_models.txt 54 | norm_type = percentile 55 | cutoff = (0.01, 0.99) 56 | normalisation = True 57 | whitening = True 58 | normalise_foreground_only=True 59 | foreground_type = otsu_plus 60 | multimod_foreground_type = and 61 | 62 | queue_length = 512 63 | window_sampling = uniform 64 | 65 | [TRAINING] 66 | sample_per_volume = 5 67 | #rotation_angle = (-10.0, 10.0) 68 | #scaling_percentage = (-10.0, 10.0) 69 | lr = 0.01 70 | loss_type = WGDL 71 | starting_iter = 0 72 | save_every_n = 5 73 | max_iter = 6 74 | max_checkpoints = 20 75 | 76 | 77 | [INFERENCE] 78 | border = (5, 5, 5) 79 | #inference_iter = 10 80 | save_seg_dir = ./output/holisticnet 81 | output_interp_order = 0 82 | output_prob = False 83 | spatial_window_size = (64, 64, 64) 84 | 85 | ############################ custom configuration sections 86 | [SEGMENTATION] 87 | image = T1,T2,T1c,Flair 88 | label = label 89 | output_prob = False 90 | num_classes = 5 91 | label_normalisation = True 92 | -------------------------------------------------------------------------------- /config/label_driven_registration.ini: -------------------------------------------------------------------------------- 1 | ############################## system configuration sections 2 | [SYSTEM] 3 | cuda_devices = "" 4 | num_threads = 2 5 | num_gpus = 1 6 | model_dir = /mnt/shared/wenqi/model_registration 7 | queue_length = 20 8 | 9 | [NETWORK] 10 | name = niftynet.network.interventional_dense_net.INetDense 11 | activation_function = prelu 12 | batch_size = 2 13 | # volume level preprocessing 14 | volume_padding_size = (5, 5, 5) 15 | decay = 0.5 16 | 17 | [TRAINING] 18 | lr = 1e-5 19 | loss_type = Dice_Dense 20 | starting_iter = 0 21 | save_every_n = 500 22 | max_iter = 5000 23 | max_checkpoints = 20 24 | 25 | validation_every_n = 10 26 | exclude_fraction_for_validation = 0.1 27 | 28 | [INFERENCE] 29 | inference_iter = 1000 30 | output_interp_order = 3 31 | save_seg_dir = resampled_moving/ 32 | 33 | ############################ input configuration sections 34 | [image0] 35 | csv_file= ./image0.csv 36 | path_to_search = /mnt/shared/wenqi/reg_data/us_images 37 | filename_contains = 38 | filename_not_contains = 39 | spatial_window_size = (80, 112, 80) 40 | interp_order = 3 41 | 42 | [label0] 43 | csv_file= ./label0.csv 44 | path_to_search = /mnt/shared/wenqi/reg_data/us_labels 45 | filename_contains = _label000 46 | filename_not_contains = 47 | spatial_window_size = (80, 112, 80) 48 | interp_order = 3 49 | 50 | [image1] 51 | csv_file= ./image1.csv 52 | path_to_search = /mnt/shared/wenqi/reg_data/mr_images 53 | filename_contains = 54 | filename_not_contains = 55 | ;spatial_window_size = (128, 128, 96) 56 | spatial_window_size = (80, 112, 80) 57 | interp_order = 3 58 | 59 | [label1] 60 | csv_file= ./label1.csv 61 | path_to_search = /mnt/shared/wenqi/reg_data/mr_labels 62 | filename_contains = _label000 63 | filename_not_contains = 64 | ;spatial_window_size = (128, 128, 96) 65 | spatial_window_size = (80, 112, 80) 66 | interp_order = 3 67 | 68 | ############################ custom configuration sections 69 | [REGISTRATION] 70 | fixed_image = image0 71 | fixed_label = label0 72 | moving_image = image1 73 | moving_label = label1 74 | label_normalisation = False 75 | -------------------------------------------------------------------------------- /config/scalenet_config.ini: -------------------------------------------------------------------------------- 1 | [T1] 2 | path_to_search = ./example_volumes/multimodal_BRATS 3 | filename_contains = T1 4 | filename_not_contains = T1c 5 | spatial_window_size = (32, 32, 32) 6 | interp_order = 3 7 | 8 | [Flair] 9 | path_to_search = ./example_volumes/multimodal_BRATS 10 | filename_contains = Flair 11 | filename_not_contains = 12 | spatial_window_size = (32, 32, 32) 13 | interp_order = 3 14 | 15 | [T1c] 16 | path_to_search = ./example_volumes/multimodal_BRATS 17 | filename_contains = T1c 18 | filename_not_contains = 19 | spatial_window_size = (32, 32, 32) 20 | interp_order = 3 21 | 22 | [T2] 23 | path_to_search = ./example_volumes/multimodal_BRATS 24 | filename_contains = T2 25 | filename_not_contains = 26 | spatial_window_size = (32, 32, 32) 27 | interp_order = 3 28 | 29 | [label] 30 | path_to_search = ./example_volumes/multimodal_BRATS 31 | filename_contains = Label 32 | filename_not_contains = T1 33 | spatial_window_size = (32, 32, 32) 34 | interp_order = 0 35 | 36 | [SYSTEM] 37 | cuda_devices = "" 38 | num_threads = 4 39 | num_gpus = 1 40 | model_dir = ./models/model_scalenet 41 | 42 | 43 | [NETWORK] 44 | name = scalenet 45 | activation_function = relu 46 | batch_size = 1 47 | decay = 0.1 48 | reg_type = L2 49 | 50 | # volume level preprocessing 51 | volume_padding_size = 21 52 | # histogram normalisation 53 | histogram_ref_file = ./example_volumes/multimodal_BRATS/standardisation_models.txt 54 | norm_type = percentile 55 | cutoff = (0.01, 0.99) 56 | normalisation = True 57 | whitening = True 58 | normalise_foreground_only=True 59 | foreground_type = otsu_plus 60 | multimod_foreground_type = and 61 | 62 | queue_length = 512 63 | window_sampling = uniform 64 | 65 | [TRAINING] 66 | sample_per_volume = 5 67 | #rotation_angle = (-10.0, 10.0) 68 | #scaling_percentage = (-10.0, 10.0) 69 | lr = 0.01 70 | loss_type = Dice 71 | starting_iter = 0 72 | save_every_n = 5 73 | max_iter = 6 74 | max_checkpoints = 20 75 | 76 | 77 | [INFERENCE] 78 | border = (5, 5, 5) 79 | #inference_iter = 10 80 | save_seg_dir = ./output/scalenet 81 | output_interp_order = 0 82 | output_prob = False 83 | spatial_window_size = (64, 64, 64) 84 | 85 | ############################ custom configuration sections 86 | [SEGMENTATION] 87 | image = T1,T2,T1c,Flair 88 | label = label 89 | output_prob = False 90 | num_classes = 5 91 | label_normalisation = True 92 | -------------------------------------------------------------------------------- /config/unet_config.ini: -------------------------------------------------------------------------------- 1 | [T1] 2 | path_to_search = ./example_volumes/monomodal_parcellation 3 | filename_contains = T1 4 | filename_not_contains = 5 | spatial_window_size = (96, 96, 96) 6 | pixdim = (1.0, 1.0, 1.0) 7 | axcodes=(A, R, S) 8 | interp_order = 3 9 | 10 | [parcellation] 11 | path_to_search = ./example_volumes/monomodal_parcellation 12 | filename_contains = Label 13 | filename_not_contains = 14 | spatial_window_size = (96, 96, 96) 15 | pixdim = (1.0, 1.0, 1.0) 16 | axcodes=(A, R, S) 17 | interp_order = 0 18 | 19 | [SYSTEM] 20 | cuda_devices = "" 21 | num_threads = 2 22 | num_gpus = 1 23 | model_dir = ./models/model_unet 24 | 25 | [NETWORK] 26 | name = nonewnet 27 | activation_function = prelu 28 | batch_size = 1 29 | decay = 0 30 | reg_type = L2 31 | 32 | # volume level preprocessing 33 | volume_padding_size = 10 34 | # histogram normalisation 35 | histogram_ref_file = ./example_volumes/monomodal_parcellation/standardisation_models.txt 36 | norm_type = percentile 37 | cutoff = (0.01, 0.99) 38 | normalisation = True 39 | whitening = True 40 | normalise_foreground_only=True 41 | foreground_type = otsu_plus 42 | multimod_foreground_type = and 43 | 44 | queue_length = 128 45 | window_sampling = uniform 46 | 47 | [TRAINING] 48 | sample_per_volume = 32 49 | rotation_angle = (-10.0, 10.0) 50 | scaling_percentage = (-10.0, 10.0) 51 | lr = 0.01 52 | loss_type = Dice 53 | starting_iter = 0 54 | save_every_n = 5 55 | max_iter = 10 56 | max_checkpoints = 20 57 | 58 | [INFERENCE] 59 | # border = (24, 24, 24) 60 | # inference_iter = 10 61 | save_seg_dir = ./output/unet 62 | output_interp_order = 0 63 | spatial_window_size = (104, 104, 104) 64 | 65 | ############################ custom configuration sections 66 | [SEGMENTATION] 67 | image = T1 68 | label = parcellation 69 | output_prob = False 70 | num_classes = 160 71 | label_normalisation = True 72 | -------------------------------------------------------------------------------- /config/vae_config.ini: -------------------------------------------------------------------------------- 1 | [IXI image] 2 | path_to_search = ./example_volumes/autoencoder_test_data 3 | filename_contains = T1 4 | filename_not_contains = 5 | spatial_window_size = (24, 24, 24) 6 | 7 | [Encoded features] 8 | path_to_search = ./output/vae_demo_features 9 | spatial_window_size = (1, 1, 1) 10 | 11 | [SYSTEM] 12 | cuda_devices = "" 13 | num_threads = 2 14 | num_gpus = 1 15 | queue_length = 20 16 | model_dir = ./models/model_autoencoder_demo 17 | 18 | [NETWORK] 19 | name=vae 20 | decay = 1e-7 21 | reg_type = L2 22 | batch_size = 50 23 | normalisation = False 24 | whitening = False 25 | 26 | [TRAINING] 27 | sample_per_volume = 1 28 | #rotation_angle = (-10.0, 10.0) 29 | #scaling_percentage = (-10.0, 10.0) 30 | lr = 0.0001 31 | loss_type = VariationalLowerBound 32 | starting_iter = 0 33 | save_every_n = 100 34 | tensorboard_every_n=2 35 | max_iter = 10000 36 | max_checkpoints = 20 37 | 38 | [INFERENCE] 39 | #inference_iter = 8100 40 | save_seg_dir = ./output/vae_demo_sample 41 | #save_seg_dir = ./output/vae_demo_interpolation 42 | #save_seg_dir = ./output/vae_demo_features 43 | spatial_window_size = (24, 24, 24) 44 | 45 | [AUTOENCODER] 46 | image = IXI image 47 | feature = Encoded features 48 | # Options are (1) encode; (2); encode-decode; 49 | # (3) sample; and (4) linear_interpolation 50 | #inference_type = linear_interpolation 51 | #inference_type = encode-decode 52 | #inference_type = encode 53 | inference_type = sample 54 | # only used when inference type is sample 55 | noise_stddev = 1 56 | # only used when inference type is linear_interpolation 57 | n_interpolations=10 58 | -------------------------------------------------------------------------------- /config/vnet_config.ini: -------------------------------------------------------------------------------- 1 | [T1] 2 | path_to_search = ./example_volumes/monomodal_parcellation 3 | filename_contains = T1 4 | filename_not_contains = 5 | spatial_window_size = (32, 32, 32) 6 | pixdim = (1.0, 1.0, 1.0) 7 | axcodes=(A, R, S) 8 | interp_order = 3 9 | 10 | [parcellation] 11 | path_to_search = ./example_volumes/monomodal_parcellation 12 | filename_contains = Label 13 | filename_not_contains = 14 | spatial_window_size = (32, 32, 32) 15 | pixdim = (1.0, 1.0, 1.0) 16 | axcodes=(A, R, S) 17 | interp_order = 0 18 | 19 | 20 | ############################## system configuration sections 21 | [SYSTEM] 22 | cuda_devices = "" 23 | num_threads = 2 24 | num_gpus = 1 25 | model_dir = ./models/model_vnet 26 | 27 | [NETWORK] 28 | name = vnet 29 | activation_function = prelu 30 | batch_size = 1 31 | decay = 0 32 | reg_type = L2 33 | 34 | # volume level preprocessing 35 | volume_padding_size = 21 36 | # histogram normalisation 37 | histogram_ref_file = ./example_volumes/monomodal_parcellation/standardisation_models.txt 38 | norm_type = percentile 39 | cutoff = (0.01, 0.99) 40 | normalisation = True 41 | whitening = True 42 | normalise_foreground_only=True 43 | foreground_type = otsu_plus 44 | multimod_foreground_type = and 45 | 46 | queue_length = 1 47 | window_sampling = uniform 48 | 49 | [TRAINING] 50 | sample_per_volume = 32 51 | rotation_angle = (-10.0, 10.0) 52 | scaling_percentage = (-10.0, 10.0) 53 | lr = 0.0001 54 | loss_type = Dice 55 | starting_iter = 0 56 | save_every_n = 5 57 | max_iter = 6 58 | max_checkpoints = 20 59 | 60 | [INFERENCE] 61 | border = (5, 5, 5) 62 | #inference_iter = 10 63 | save_seg_dir = ./output/vnet 64 | output_interp_order = 0 65 | spatial_window_size = (0, 0, 3) 66 | 67 | ############################ custom configuration sections 68 | [SEGMENTATION] 69 | image = T1 70 | label = parcellation 71 | output_prob = False 72 | num_classes = 160 73 | label_normalisation = True 74 | -------------------------------------------------------------------------------- /config/weighted_sample_regression.ini: -------------------------------------------------------------------------------- 1 | [INPUTIMAGE] 2 | spatial_window_size=(96, 96, 96) 3 | filename_contains= 4 | filename_not_contains= 5 | path_to_search=./input 6 | interp_order=3 7 | 8 | [OUTPUTIMAGE] 9 | spatial_window_size=(96, 96, 96) 10 | filename_contains=003 11 | filename_not_contains=() 12 | path_to_search=./output 13 | interp_order=3 14 | 15 | [RESIDUALS] 16 | spatial_window_size=(96, 96, 96) 17 | filename_contains= 18 | filename_not_contains= 19 | path_to_search=./weights 20 | interp_order=3 21 | 22 | [SAMPWEIGHT] 23 | spatial_window_size=(96, 96, 96) 24 | filename_contains= 25 | filename_not_contains= 26 | path_to_search=./sampler_frequency 27 | interp_order=3 28 | 29 | [TRAINING] 30 | loss_type=RMSE 31 | sample_per_volume=32 32 | tensorboard_every_n=20 33 | max_iter=5000 34 | save_every_n=200 35 | max_checkpoints=10 36 | optimiser=adam 37 | lr=0.001 38 | starting_iter=0 39 | 40 | [NETWORK] 41 | cutoff=(0.01, 0.99) 42 | multimod_foreground_type=and 43 | volume_padding_size=(8, 8, 8) 44 | name=highres3dnet 45 | decay=0.00001 46 | activation_function=prelu 47 | normalise_foreground_only=False 48 | histogram_ref_file=./model/standardisation_models.txt 49 | batch_size=2 50 | norm_type=percentile 51 | foreground_type=otsu_plus 52 | window_sampling=weighted 53 | whitening=False 54 | reg_type=L1 55 | normalisation=False 56 | 57 | [INFERENCE] 58 | border=(16, 16, 16) 59 | output_interp_order=3 60 | inference_iter=600 61 | save_seg_dir=./output/ 62 | spatial_window_size=(136, 136, 136) 63 | 64 | [SYSTEM] 65 | cuda_devices="" 66 | num_gpus=1 67 | num_threads=2 68 | queue_length=5 69 | model_dir=./model/ 70 | 71 | [REGRESSION] 72 | output=INPUTIMAGE 73 | image=OUTPUTIMAGE 74 | weight=RESIDUALS 75 | sampler=SAMPWEIGHT 76 | loss_border=8 77 | -------------------------------------------------------------------------------- /data/IXI_autoencoder/.gitignore: -------------------------------------------------------------------------------- 1 | # ignore everything in this directory 2 | * 3 | # Except this file 4 | !.gitignore 5 | -------------------------------------------------------------------------------- /data/PROMISE12/setup.py: -------------------------------------------------------------------------------- 1 | """ 2 | Unzip data downloaded from challenge website: 3 | https://promise12.grand-challenge.org/ 4 | 5 | The outcome should be three folders named: 6 | TrainingData_Part1, TrainingData_Part2, TrainingData_Part3 7 | each folder contains multiple '.mhd' and '.raw' files 8 | """ 9 | import os 10 | import zipfile 11 | 12 | zip_dir = '.' 13 | target_dir = '.' 14 | for zip_filename in {'TrainingData_Part1.zip', 'TrainingData_Part2.zip', 15 | 'TrainingData_Part3.zip'}: 16 | print('Extracting', zip_filename, '...') 17 | zip_ref = zipfile.ZipFile(os.path.join(zip_dir, zip_filename), 'r') 18 | zip_ref.extractall(os.path.basename(zip_filename.replace('.zip', ''))) 19 | zip_ref.close() 20 | -------------------------------------------------------------------------------- /data/us_simulator_gan/.gitignore: -------------------------------------------------------------------------------- 1 | gnore everything in this directory 2 | * 3 | # Except this file 4 | !.gitignore 5 | -------------------------------------------------------------------------------- /demos/BRATS17/README.md: -------------------------------------------------------------------------------- 1 | This demo presents how to use NiftyNet for whole tumor segmentation, 2 | which is the first stage of the cascaded CNNs described in the following [paper][wang17_paper]. 3 | [wang17_paper]: https://arxiv.org/abs/1709.00382 4 | 5 | ``` 6 | Wang et al., Automatic Brain Tumor Segmentation using Cascaded Anisotropic Convolutional Neural Networks, MICCAI BRATS 2017. 7 | ``` 8 | 9 | For a full implementation of the method described in this paper with three stages of the cascaded CNNs, 10 | please see: https://github.com/taigw/brats17 11 | 12 | ![A slice from BRATS17](./example_outputs/original.png) 13 | ![Ground truth of whole Tumor](./example_outputs/label.png) 14 | ![Segmentation probability map using this demo](./example_outputs/ave_prob.png) 15 | 16 | From left to right: A slice from BRATS17, ground truth of whole tumor, 17 | and segmentation probability map using this demo [1]. 18 | 19 | *[1] This method ranked the first (in terms of averaged Dice score 0.90499) according 20 | to the online validation leaderboard of [BRATS challenge 2017](https://www.cbica.upenn.edu/BraTS17/lboardValidation.html).* 21 | 22 | _Please checkout a trained model in [NiftyNet model zoo](https://github.com/NifTK/NiftyNetModelZoo/blob/master/anisotropic_nets_brats_challenge_model_zoo.md)._ 23 | 24 | 25 | Model training requires 26 | [The Multimodal Brain Tumor Image Segmentation Benchmark (BRATS)](http://10.1109/TMI.2014.2377694). 27 | 28 | 29 | * For BRATS 2015, please visit [https://sites.google.com/site/braintumorsegmentation/home/brats2015](https://sites.google.com/site/braintumorsegmentation/home/brats2015). 30 | 31 | * For BRATS 2017, please visit [http://www.med.upenn.edu/sbia/brats2017.html](http://www.med.upenn.edu/sbia/brats2017.html). 32 | 33 | To be compatible with the current NiftyNet configuration files and anisotropic 34 | networks, the downloaded datasets must first be preprocessed with [rename_crop_BRATS.py](./rename_crop_BRATS.py). 35 | 36 | _For a full implementation of the method described in this paper with three stages of the cascaded CNNs, 37 | please see: [https://github.com/taigw/brats17](https://github.com/taigw/brats17)._ 38 | -------------------------------------------------------------------------------- /demos/BRATS17/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/demos/BRATS17/__init__.py -------------------------------------------------------------------------------- /demos/BRATS17/example_outputs/ave_prob.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/demos/BRATS17/example_outputs/ave_prob.png -------------------------------------------------------------------------------- /demos/BRATS17/example_outputs/label.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/demos/BRATS17/example_outputs/label.png -------------------------------------------------------------------------------- /demos/BRATS17/example_outputs/original.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/demos/BRATS17/example_outputs/original.png -------------------------------------------------------------------------------- /demos/GAN/README.md: -------------------------------------------------------------------------------- 1 | _Please checkout a trained model in [NiftyNet model zoo](https://github.com/NifTK/NiftyNetModelZoo/blob/master/ultrasound_simulator_gan_model_zoo.md)._ 2 | 3 | -------------------------------------------------------------------------------- /demos/Learning_Rate_Decay/README.md: -------------------------------------------------------------------------------- 1 | # Learning rate decay application 2 | 3 | This application implements a simple learning rate schedule of 4 | "halving the learning rate every 3 iterations" for segmentation applications. 5 | 6 | The concept is general and could be used for other types of application. A brief demo is provide which can be fully run from a jupyter notebook provided a a working installation of NiftyNet exists on your system. 7 | 8 | The core function is implemented by: 9 | 10 | 1) Adding a `self.learning_rate` placeholder, and connect it to the network 11 | in `connect_data_and_network` function 12 | 13 | 2) Adding a `self.current_lr` variable to keep track of the current learning rate 14 | 15 | 3) Overriding the default `set_iteration_update` function provided in `BaseApplication` 16 | so that `self.current_lr` is changed according to the `current_iter`. 17 | 18 | 4) To feed the `self.current_lr` value to the network, the data feeding dictionary 19 | is updated within the customised `set_iteration_update` function, by 20 | ``` 21 | iteration_message.data_feed_dict[self.learning_rate] = self.current_lr 22 | ``` 23 | `iteration_message.data_feed_dict` will be used in 24 | `tf.Session.run(..., feed_dict=iteration_message.data_feed_dict)` by the engine 25 | at each iteration. 26 | 27 | 28 | *This demo only supports NiftyNet cloned from [GitHub](https://github.com/NifTK/NiftyNet).* 29 | Further demos/ trained models can be found at [NiftyNet model zoo](https://github.com/NifTK/NiftyNetModelZoo/blob/master/dense_vnet_abdominal_ct_model_zoo.md). 30 | -------------------------------------------------------------------------------- /demos/Learning_Rate_Decay/learning_rate_demo_train_config.ini: -------------------------------------------------------------------------------- 1 | ############################ input configuration sections 2 | [images] # Name this as you see fit 3 | path_to_search = ./data/decathlon_hippocampus 4 | filename_contains = img_hippocampus_ 5 | filename_not_contains = ._ 6 | spatial_window_size = (24, 24, 24) 7 | interp_order = 3 8 | 9 | [label] 10 | path_to_search = ./data/decathlon_hippocampus 11 | filename_contains = label_hippocampus_ 12 | filename_not_contains = ._ 13 | spatial_window_size = (24, 24, 24) 14 | interp_order = 0 15 | 16 | ############################## system configuration sections 17 | [SYSTEM] 18 | cuda_devices = "" 19 | num_threads = 6 20 | num_gpus = 1 21 | model_dir = ./models/model_multimodal_toy 22 | queue_length = 20 23 | 24 | [NETWORK] 25 | name = highres3dnet 26 | activation_function = prelu 27 | batch_size = 1 28 | decay = 0 29 | reg_type = L2 30 | 31 | # Volume level pre-processing 32 | volume_padding_size = 0 33 | # Normalisation 34 | whitening = True 35 | normalise_foreground_only = False 36 | 37 | [TRAINING] 38 | sample_per_volume = 1 39 | optimiser = gradientdescent 40 | # rotation_angle = (-10.0, 10.0) 41 | # scaling_percentage = (-10.0, 10.0) 42 | # random_flipping_axes= 1 43 | lr = 0.0001 44 | loss_type = CrossEntropy 45 | starting_iter = 0 46 | save_every_n = 100 47 | max_iter = 500 48 | max_checkpoints = 20 49 | 50 | [INFERENCE] 51 | border = 5 52 | #inference_iter = 10 53 | save_seg_dir = ./output/toy 54 | output_interp_order = 0 55 | spatial_window_size = (64, 64, 64) 56 | 57 | ############################ custom configuration sections 58 | [SEGMENTATION] 59 | image = images 60 | label = label 61 | output_prob = False 62 | num_classes = 3 63 | label_normalisation = False 64 | -------------------------------------------------------------------------------- /demos/PROMISE12/README.md: -------------------------------------------------------------------------------- 1 | To start this Jupyter Notebook demo: 2 | 3 | 1) Install conda 4 | 5 | 2) in conda terminal run the following commands: 6 | 7 | ```bash 8 | conda create -n tensorflow python=3.5 9 | 10 | # If you are using bash terminal: 11 | source activate tensorflow 12 | # otherwise: 13 | activate tensorflow 14 | 15 | conda install nb_conda_kernels 16 | jupyter notebook 17 | ``` 18 | 19 | _This demo only supports NiftyNet cloned from [GitHub](https://github.com/NifTK/NiftyNet)_ 20 | 21 | Please find further demos/trained models at [NiftyNet model zoo](https://github.com/NifTK/NiftyNetModelZoo/blob/master/dense_vnet_abdominal_ct_model_zoo.md). 22 | 23 | -------------------------------------------------------------------------------- /demos/PROMISE12/promise12_balanced_train_config.ini: -------------------------------------------------------------------------------- 1 | [promise12] 2 | path_to_search = data/PROMISE12/TrainingData_Part1,data/PROMISE12/TrainingData_Part2,data/PROMISE12/TrainingData_Part3 3 | filename_contains = Case,mhd 4 | filename_not_contains = Case2,segmentation 5 | spatial_window_size = (64, 64, 8) 6 | interp_order = 3 7 | axcodes=(A, R, S) 8 | 9 | [label] 10 | path_to_search = data/PROMISE12/TrainingData_Part1,data/PROMISE12/TrainingData_Part2,data/PROMISE12/TrainingData_Part3 11 | filename_contains = Case,_segmentation,mhd 12 | filename_not_contains = Case2 13 | spatial_window_size = (64, 64, 8) 14 | interp_order = 0 15 | axcodes=(A, R, S) 16 | 17 | ############################## system configuration sections 18 | [SYSTEM] 19 | cuda_devices = "" 20 | num_threads = 2 21 | num_gpus = 1 22 | model_dir = ./promise12_model 23 | 24 | [NETWORK] 25 | name = dense_vnet 26 | activation_function = prelu 27 | batch_size = 1 28 | 29 | # volume level preprocessing 30 | volume_padding_size = 0 31 | # histogram normalisation 32 | histogram_ref_file = standardisation_models.txt 33 | norm_type = percentile 34 | cutoff = (0.01, 0.99) 35 | normalisation = True 36 | whitening = True 37 | normalise_foreground_only=True 38 | foreground_type = otsu_plus 39 | multimod_foreground_type = and 40 | window_sampling = balanced 41 | 42 | queue_length = 8 43 | 44 | 45 | [TRAINING] 46 | sample_per_volume = 4 47 | rotation_angle = (-10.0, 10.0) 48 | scaling_percentage = (-10.0, 10.0) 49 | random_flipping_axes= 1 50 | lr = 0.00002 51 | loss_type = Dice 52 | starting_iter = 0 53 | save_every_n = 12500 54 | max_iter = 25000 55 | max_checkpoints = 20 56 | 57 | ############################ custom configuration sections 58 | [SEGMENTATION] 59 | image = promise12 60 | label = label 61 | sampler = label 62 | output_prob = False 63 | num_classes = 2 64 | label_normalisation = True 65 | min_numb_labels = 2 66 | min_sampling_ratio = 0.000001 67 | -------------------------------------------------------------------------------- /demos/PROMISE12/promise12_demo_inference_config.ini: -------------------------------------------------------------------------------- 1 | [promise12] 2 | path_to_search = data/PROMISE12/TrainingData_Part1,data/PROMISE12/TrainingData_Part2,data/PROMISE12/TrainingData_Part3 3 | filename_contains = Case2,mhd 4 | filename_not_contains = segmentation 5 | spatial_window_size = (64, 64, 64) 6 | interp_order = 3 7 | axcodes=(A, R, S) 8 | 9 | 10 | [label] 11 | path_to_search = data/PROMISE12/TrainingData_Part1,data/PROMISE12/TrainingData_Part2,data/PROMISE12/TrainingData_Part3 12 | filename_contains = Case2,_segmentation,mhd 13 | filename_not_contains = 14 | spatial_window_size = (64, 64, 64) 15 | interp_order = 3 16 | axcodes=(A, R, S) 17 | 18 | ############################## system configuration sections 19 | [SYSTEM] 20 | cuda_devices = "" 21 | num_threads = 2 22 | num_gpus = 1 23 | model_dir = ./promise12_model 24 | 25 | [NETWORK] 26 | name = dense_vnet 27 | activation_function = prelu 28 | batch_size = 1 29 | 30 | # volume level preprocessing 31 | volume_padding_size = 0 32 | # histogram normalisation 33 | histogram_ref_file = standardisation_models.txt 34 | norm_type = percentile 35 | cutoff = (0.01, 0.99) 36 | normalisation = True 37 | whitening = True 38 | normalise_foreground_only=True 39 | foreground_type = otsu_plus 40 | multimod_foreground_type = and 41 | window_sampling = resize 42 | 43 | queue_length = 8 44 | 45 | [INFERENCE] 46 | border = (5, 5, 5) 47 | #inference_iter = 10 48 | save_seg_dir = output/ 49 | output_interp_order = 0 50 | spatial_window_size = (0, 0, 3) 51 | 52 | ############################ custom configuration sections 53 | [SEGMENTATION] 54 | image = promise12 55 | label = label 56 | output_prob = False 57 | num_classes = 2 58 | label_normalisation = True 59 | min_numb_labels = 2 60 | min_sampling_ratio = 0.000001 61 | -------------------------------------------------------------------------------- /demos/PROMISE12/promise12_demo_train_config.ini: -------------------------------------------------------------------------------- 1 | [promise12] 2 | path_to_search = data/PROMISE12/TrainingData_Part1,data/PROMISE12/TrainingData_Part2,data/PROMISE12/TrainingData_Part3 3 | filename_contains = Case,mhd 4 | filename_not_contains = Case2,segmentation 5 | spatial_window_size = (64, 64, 64) 6 | interp_order = 3 7 | axcodes=(A, R, S) 8 | 9 | [label] 10 | path_to_search = data/PROMISE12/TrainingData_Part1,data/PROMISE12/TrainingData_Part2,data/PROMISE12/TrainingData_Part3 11 | filename_contains = Case,_segmentation,mhd 12 | filename_not_contains = Case2 13 | spatial_window_size = (64, 64, 64) 14 | interp_order = 0 15 | axcodes=(A, R, S) 16 | 17 | ############################## system configuration sections 18 | [SYSTEM] 19 | cuda_devices = "" 20 | num_threads = 2 21 | num_gpus = 1 22 | model_dir = ./promise12_model 23 | 24 | [NETWORK] 25 | name = dense_vnet 26 | activation_function = prelu 27 | batch_size = 1 28 | 29 | # volume level preprocessing 30 | volume_padding_size = 0 31 | # histogram normalisation 32 | histogram_ref_file = standardisation_models.txt 33 | norm_type = percentile 34 | cutoff = (0.01, 0.99) 35 | normalisation = True 36 | whitening = True 37 | normalise_foreground_only=True 38 | foreground_type = otsu_plus 39 | multimod_foreground_type = and 40 | window_sampling = resize 41 | 42 | queue_length = 8 43 | 44 | 45 | [TRAINING] 46 | sample_per_volume = 4 47 | rotation_angle = (-10.0, 10.0) 48 | scaling_percentage = (-10.0, 10.0) 49 | random_flipping_axes= 1 50 | lr = 0.00002 51 | loss_type = Dice 52 | starting_iter = 0 53 | save_every_n = 12500 54 | max_iter = 25000 55 | max_checkpoints = 20 56 | 57 | ############################ custom configuration sections 58 | [SEGMENTATION] 59 | image = promise12 60 | label = label 61 | output_prob = False 62 | num_classes = 2 63 | label_normalisation = True 64 | min_numb_labels = 2 65 | min_sampling_ratio = 0.000001 66 | -------------------------------------------------------------------------------- /demos/PyTorchNiftyNet/libs/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/demos/PyTorchNiftyNet/libs/__init__.py -------------------------------------------------------------------------------- /demos/PyTorchNiftyNet/libs/dataset_niftynet.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import torch 3 | from torch.utils.data import Dataset 4 | 5 | 6 | class DatasetNiftySampler(Dataset): 7 | """ 8 | A simple adapter 9 | converting NiftyNet sampler's output into PyTorch Dataset properties 10 | """ 11 | def __init__(self, sampler): 12 | super(DatasetNiftySampler, self).__init__() 13 | self.sampler = sampler 14 | 15 | def __getitem__(self, index): 16 | data = self.sampler(idx=index) 17 | 18 | # Transpose to PyTorch format 19 | image = np.transpose(data['image'], (0, 5, 1, 2, 3, 4)) 20 | label = np.transpose(data['label'], (0, 5, 1, 2, 3, 4)) 21 | 22 | image = torch.from_numpy(image).float() 23 | label = torch.from_numpy(label).float() 24 | 25 | return image, label 26 | 27 | def __len__(self): 28 | return len(self.sampler.reader.output_list) 29 | -------------------------------------------------------------------------------- /demos/PyTorchNiftyNet/libs/loss.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | 4 | 5 | class SoftDiceLoss(nn.Module): 6 | 7 | def __init__(self): 8 | super(SoftDiceLoss, self).__init__() 9 | 10 | def forward(self, output, label): 11 | probs = output.view(-1) 12 | mask = label.view(-1) 13 | smooth = 1 14 | intersection = torch.sum(probs * mask) 15 | den1 = torch.sum(probs) 16 | den2 = torch.sum(mask) 17 | soft_dice = (2 * intersection + smooth) / (den1 + den2 + smooth) 18 | return -soft_dice 19 | 20 | 21 | def dice(input, target): 22 | epsilon = 1e-8 23 | iflat = input.view(-1) 24 | tflat = target.view(-1) 25 | intersection = (iflat * tflat).sum() 26 | return 2 * intersection / (iflat.sum() + tflat.sum() + epsilon) 27 | -------------------------------------------------------------------------------- /demos/README.md: -------------------------------------------------------------------------------- 1 | * Please checkout [NiftyNet model zoo](https://github.com/NifTK/NiftyNetModelZoo/blob/master/README.md) for demos and trained models. 2 | 3 | * Please checkout [NiftyNet documentation website](http://niftynet.readthedocs.io/en/dev/config_spec.html) for configuration file usage. 4 | 5 | -------------------------------------------------------------------------------- /demos/brain_parcellation/README.md: -------------------------------------------------------------------------------- 1 | ## Brain parcellation demo 2 | ![Brain parcellation](./example_outputs/screenshot.png) 3 | 4 | Visualisation of segmentation results generated by this demo. 5 | 6 | 7 | #### Overview 8 | This demo employs a high resolution 3D network using the method 9 | described in 10 | ``` 11 | Li et al., On the Compactness, Efficiency, and Representation of 3D 12 | Convolutional Networks: Brain Parcellation as a Pretext Task, 13 | In: Information Processing in Medical Imaging (IPMI) 2017. 14 | ``` 15 | DOI: [10.1007/978-3-319-59050-9_28](http://doi.org/10.1007/978-3-319-59050-9_28) 16 | 17 | This demo will download an MR volume and a 18 | trained network model, and then using the NiftyNet inference program to 19 | generate brain parcellation. 20 | 21 | _Please visit the [NiftyNet model zoo entry](https://github.com/NifTK/NiftyNetModelZoo/blob/master/highres3dnet_brain_parcellation_model_zoo.md) 22 | for more information on running this demo._ 23 | -------------------------------------------------------------------------------- /demos/brain_parcellation/example_outputs/screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/demos/brain_parcellation/example_outputs/screenshot.png -------------------------------------------------------------------------------- /demos/module_examples/README.md: -------------------------------------------------------------------------------- 1 | To start this Jupyter Notebook demo: 2 | 3 | 1) Install conda 4 | 5 | 2) in conda terminal run the following commands: 6 | 7 | ```bash 8 | conda create -n tensorflow python=3.5 9 | 10 | # If you are using bash terminal: 11 | source activate tensorflow 12 | # otherwise: 13 | activate tensorflow 14 | 15 | conda install nb_conda_kernels 16 | jupyter notebook 17 | ``` 18 | 19 | _This demo only supports NiftyNet cloned from [GitHub](https://github.com/NifTK/NiftyNet)_ 20 | -------------------------------------------------------------------------------- /demos/module_examples/mapping.txt: -------------------------------------------------------------------------------- 1 | label_label-from 0.0 1.0 2 | label_label-to 0 1 3 | -------------------------------------------------------------------------------- /demos/unet/HeLa.ini: -------------------------------------------------------------------------------- 1 | [cells] 2 | path_to_search = ./data/u-net/DIC-C2DH-HeLa/niftynet_data 3 | filename_contains = img_ 4 | spatial_window_size = (572, 572, 1) 5 | interp_order = 3 6 | loader = skimage 7 | 8 | [label] 9 | path_to_search = ./data/u-net/DIC-C2DH-HeLa/niftynet_data 10 | filename_contains = bin_seg_ 11 | spatial_window_size = (388, 388, 1) 12 | interp_order = 0 13 | loader = skimage 14 | 15 | [xent_weights] 16 | path_to_search = ./data/u-net/DIC-C2DH-HeLa/niftynet_data 17 | filename_contains = weight_ 18 | spatial_window_size = (388, 388, 1) 19 | interp_order = 3 20 | loader = skimage 21 | 22 | [SYSTEM] 23 | cuda_devices = "" 24 | num_threads = 6 25 | num_gpus = 1 26 | 27 | [NETWORK] 28 | name = unet_2d 29 | activation_function = relu 30 | batch_size = 4 31 | 32 | # volume level preprocessing 33 | volume_padding_size = (92, 92, 0) 34 | volume_padding_mode = symmetric 35 | whitening = True 36 | normalise_foreground_only=False 37 | 38 | queue_length = 20 39 | window_sampling = uniform 40 | 41 | [TRAINING] 42 | sample_per_volume = 2 43 | random_flipping_axes=-1 44 | lr = 0.0003 45 | loss_type = CrossEntropy 46 | starting_iter = 0 47 | save_every_n = 200 48 | max_iter = 2000 49 | max_checkpoints = 10 50 | 51 | do_elastic_deformation = False 52 | deformation_sigma = 50 53 | num_ctrl_points = 6 54 | proportion_to_deform=0.9 55 | 56 | validation_every_n = 10 57 | validation_max_iter = 1 58 | 59 | [INFERENCE] 60 | border = (92, 92, 0) 61 | inference_iter = -1 62 | save_seg_dir = ./output 63 | output_interp_order = 0 64 | spatial_window_size = (572,572,1) 65 | 66 | ############################ custom configuration sections 67 | [SEGMENTATION] 68 | image = cells 69 | label = label 70 | output_prob = False 71 | num_classes = 2 72 | label_normalisation = False 73 | weight = xent_weights 74 | -------------------------------------------------------------------------------- /demos/unet/README.md: -------------------------------------------------------------------------------- 1 | This folder presents the IPython notebook document and scripts for tutorial: 2 | 3 | > Zach Eaton-Rosen, "[Using NiftyNet to Train U-Net for Cell Segmentation](https://miccai-sb.github.io/materials/U-Net_Demo.html)", 2018. 4 | 5 | The tutorial is the winner* 6 | of [the MICCAI educational challenge 2018](https://miccai-sb.github.io/challenge). 7 | 8 | *Decided through expert panel judging followed by a popular vote. 9 | -------------------------------------------------------------------------------- /demos/unet/U373.ini: -------------------------------------------------------------------------------- 1 | [cells] 2 | path_to_search = ./data/u-net/PhC-C2DH-U373/niftynet_data 3 | filename_contains = img_ 4 | filename_not_contains = 5 | spatial_window_size = (572, 572, 1) 6 | interp_order = 3 7 | loader = skimage 8 | 9 | [label] 10 | path_to_search = ./data/u-net/PhC-C2DH-U373/niftynet_data 11 | filename_contains = bin_seg_ 12 | filename_not_contains = 13 | spatial_window_size = (388, 388, 1) 14 | interp_order = 0 15 | loader = skimage 16 | 17 | [xent_weights] 18 | path_to_search = ./data/u-net/PhC-C2DH-U373/niftynet_data 19 | filename_contains = weight_ 20 | filename_not_contains = 21 | spatial_window_size = (388, 388, 1) 22 | interp_order = 3 23 | loader = skimage 24 | 25 | [SYSTEM] 26 | cuda_devices = "" 27 | num_threads = 6 28 | num_gpus = 1 29 | 30 | [NETWORK] 31 | name = unet_2d 32 | activation_function = relu 33 | batch_size = 4 34 | 35 | # volume level preprocessing 36 | volume_padding_size = (92, 92, 0) 37 | volume_padding_mode = symmetric 38 | normalisation = False 39 | whitening = True 40 | normalise_foreground_only=False 41 | 42 | queue_length = 20 43 | window_sampling = uniform 44 | 45 | [TRAINING] 46 | sample_per_volume = 2 47 | random_flipping_axes=0,1 48 | lr = 0.0003 49 | loss_type = CrossEntropy 50 | starting_iter = 0 51 | save_every_n = 500 52 | max_iter = 10000 53 | max_checkpoints = 15 54 | 55 | do_elastic_deformation = True 56 | deformation_sigma = 50 57 | num_ctrl_points = 6 58 | proportion_to_deform=0.9 59 | 60 | validation_every_n = 10 61 | validation_max_iter = 1 62 | 63 | [INFERENCE] 64 | border = (92, 92, 0) 65 | inference_iter = -1 66 | save_seg_dir = ./output 67 | output_interp_order = 0 68 | spatial_window_size = (572,572,1) 69 | 70 | ############################ custom configuration sections 71 | [SEGMENTATION] 72 | image = cells 73 | label = label 74 | output_prob = False 75 | num_classes = 2 76 | label_normalisation = False 77 | weight = xent_weights 78 | -------------------------------------------------------------------------------- /demos/unet/file_sorter.py: -------------------------------------------------------------------------------- 1 | import os 2 | from shutil import copy 3 | import argparse 4 | 5 | 6 | def get_user_args(): 7 | parser = argparse.ArgumentParser() 8 | parser.add_argument('--file_dir', 9 | default=os.path.join('data', 'u-net'), 10 | help='The directory containing the cell tracking data.', 11 | ) 12 | parser.add_argument('--experiment_names', 13 | default=['DIC-C2DH-HeLa', 'PhC-C2DH-U373'], 14 | help='The names of the cell tracking experiments.', 15 | type=list 16 | ) 17 | return parser.parse_args() 18 | 19 | 20 | def main(): 21 | args = get_user_args() 22 | 23 | # for each specified folder 24 | for experiment_name in args.experiment_names: 25 | out_dir = os.path.join(args.file_dir, experiment_name, 'niftynet_data') 26 | if not os.path.isdir(out_dir): 27 | os.makedirs(out_dir) 28 | 29 | for root, _, files in os.walk(os.path.join(args.file_dir, experiment_name)): 30 | for name in [f for f in files if 'track' not in f]: 31 | if 'niftynet_data' not in root: # don't look at the ones that are done already 32 | cell_id = root.split(os.sep)[root.split('/').index(experiment_name) + 1][:2] 33 | out_name = name.replace('t0', 'img_0').replace('t1', 'img_1').replace('man_seg', 'seg_') 34 | out_name = ''.join([out_name.split('.')[0] + '_', cell_id, '.tif']) 35 | out_path = os.path.join(out_dir, out_name) 36 | copy(os.path.join(root, name), out_path) 37 | 38 | 39 | if __name__ == "__main__": 40 | main() 41 | -------------------------------------------------------------------------------- /demos/unet/make_cell_weights.py: -------------------------------------------------------------------------------- 1 | import os 2 | import numpy as np 3 | import matplotlib.pyplot as plt # for visualising and debugging 4 | from scipy.ndimage.morphology import distance_transform_edt 5 | from skimage.io import imsave, imread 6 | from skimage.segmentation import find_boundaries 7 | from demos.unet.file_sorter import get_user_args 8 | 9 | W_0, SIGMA = 10, 5 10 | 11 | 12 | def construct_weights_and_mask(img): 13 | seg_boundaries = find_boundaries(img, mode='inner') 14 | 15 | bin_img = img > 0 16 | # take segmentations, ignore boundaries 17 | binary_with_borders = np.bitwise_xor(bin_img, seg_boundaries) 18 | 19 | foreground_weight = 1 - binary_with_borders.sum() / binary_with_borders.size 20 | background_weight = 1 - foreground_weight 21 | 22 | # build euclidean distances maps for each cell: 23 | cell_ids = [x for x in np.unique(img) if x > 0] 24 | distances = np.zeros((img.shape[0], img.shape[1], len(cell_ids))) 25 | 26 | for i, cell_id in enumerate(cell_ids): 27 | distances[..., i] = distance_transform_edt(img != cell_id) 28 | 29 | # we need to look at the two smallest distances 30 | distances.sort(axis=-1) 31 | 32 | weight_map = W_0 * np.exp(-(1 / (2 * SIGMA ** 2)) * ((distances[..., 0] + distances[..., 1]) ** 2)) 33 | weight_map[binary_with_borders] = foreground_weight 34 | weight_map[~binary_with_borders] += background_weight 35 | 36 | return weight_map, binary_with_borders 37 | 38 | 39 | def main(): 40 | args = get_user_args() 41 | for experiment_name in args.experiment_names: 42 | file_dir = os.path.join(args.file_dir, experiment_name, 'niftynet_data') 43 | for f_name in [f for f in os.listdir(file_dir) if f.startswith('seg') and f.endswith('.tif')]: 44 | img = imread(os.path.join(file_dir, f_name)) 45 | weight_map, binary_seg = construct_weights_and_mask(img) 46 | imsave(os.path.join(file_dir, f_name).replace('seg', 'weight'), weight_map) 47 | imsave(os.path.join(file_dir, f_name).replace('seg', 'bin_seg'), binary_seg.astype(np.uint8)) 48 | 49 | 50 | if __name__ == "__main__": 51 | main() 52 | -------------------------------------------------------------------------------- /demos/unet_histology/config.ini: -------------------------------------------------------------------------------- 1 | ############################ Input Configuration 2 | [slice] 3 | path_to_search = ./data/unet_histology 4 | filename_contains = input_ 5 | filename_not_contains = _labels 6 | interp_order = 1 7 | spatial_window_size = (400, 400) 8 | 9 | [label] 10 | path_to_search = ./data/unet_histology 11 | filename_contains = input_, _labels 12 | interp_order = 0 13 | spatial_window_size = (228, 228) 14 | 15 | ############################## System Configuration 16 | [SYSTEM] 17 | cuda_devices = "" 18 | num_threads = 1 19 | num_gpus = 1 20 | model_dir = ./models/unet_histology 21 | queue_length = 36 22 | 23 | [NETWORK] 24 | name = unet_2d 25 | batch_size = 5 26 | volume_padding_size = 92, 92, 0 27 | window_sampling = balanced 28 | whitening = True 29 | 30 | [TRAINING] 31 | sample_per_volume = 1 32 | lr = 0.00001 33 | starting_iter = 0 34 | save_every_n = 100 35 | tensorboard_every_n = 10 36 | max_iter = 2501 37 | loss_type = DicePlusXEnt 38 | random_flipping_axes = (0, 1) 39 | validation_every_n = 10 40 | exclude_fraction_for_validation = 0.2 41 | exclude_fraction_for_inference = 0.05 42 | 43 | [INFERENCE] 44 | border = (92, 92) 45 | inference_iter = 2500 46 | output_interp_order = 0 47 | spatial_window_size = (400, 400) 48 | save_seg_dir = output/ 49 | dataset_to_infer = inference 50 | 51 | [EVALUATION] 52 | save_csv_dir = ./eval.csv 53 | evaluations = dice 54 | 55 | ############################ Application Configuration 56 | [SEGMENTATION] 57 | image = slice 58 | label = label 59 | sampler = label 60 | label_normalisation = False 61 | output_prob = False 62 | num_classes = 2 63 | evaluation_units = label 64 | -------------------------------------------------------------------------------- /demos/unet_histology/data_in_itksnap_scaled.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/demos/unet_histology/data_in_itksnap_scaled.png -------------------------------------------------------------------------------- /demos/unet_histology/tensorboard_scaled.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/demos/unet_histology/tensorboard_scaled.png -------------------------------------------------------------------------------- /demos/variational_autoencoder/example_outputs/1037.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/demos/variational_autoencoder/example_outputs/1037.png -------------------------------------------------------------------------------- /demos/variational_autoencoder/example_outputs/464.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/demos/variational_autoencoder/example_outputs/464.png -------------------------------------------------------------------------------- /demos/variational_autoencoder/example_outputs/interpolation.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/demos/variational_autoencoder/example_outputs/interpolation.gif -------------------------------------------------------------------------------- /demos/variational_autoencoder/vae_config.ini: -------------------------------------------------------------------------------- 1 | [IXI image] 2 | path_to_search = ./data/IXI_autoencoder 3 | filename_contains = T1 4 | filename_not_contains = 5 | spatial_window_size = (24, 24, 24) 6 | 7 | [Encoded features] 8 | path_to_search = ./output/vae_demo_features 9 | filename_contains = generated 10 | spatial_window_size = (1, 1, 1) 11 | 12 | [SYSTEM] 13 | cuda_devices = "" 14 | num_threads = 2 15 | num_gpus = 1 16 | queue_length = 200 17 | model_dir = ./models/model_autoencoder_demo 18 | 19 | [NETWORK] 20 | name=vae 21 | decay = 0 22 | reg_type = L2 23 | batch_size = 50 24 | 25 | [TRAINING] 26 | sample_per_volume = 1 27 | lr = 0.001 28 | loss_type = VariationalLowerBound 29 | starting_iter = 0 30 | save_every_n = 200 31 | tensorboard_every_n=100 32 | max_iter = 15000 33 | max_checkpoints = 100 34 | 35 | [INFERENCE] 36 | inference_iter = 12000 37 | #save_seg_dir = ./output/vae_demo_sample 38 | save_seg_dir = ./output/vae_demo_interpolation 39 | #save_seg_dir = ./output/vae_demo_features 40 | spatial_window_size = (24, 24, 24) 41 | 42 | [AUTOENCODER] 43 | image = IXI image 44 | feature = Encoded features 45 | # Options are (1) encode; (2); encode-decode; 46 | # (3) sample; and (4) linear_interpolation 47 | inference_type = linear_interpolation 48 | #inference_type = encode-decode 49 | #inference_type = encode 50 | #inference_type = sample 51 | # only used when inference type is sample 52 | noise_stddev = 1 53 | # only used when inference type is linear_interpolation 54 | n_interpolations=10 55 | -------------------------------------------------------------------------------- /doc/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | SPHINXPROJ = NiftyNet 8 | SOURCEDIR = source 9 | BUILDDIR = build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) -------------------------------------------------------------------------------- /doc/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | pushd %~dp0 4 | 5 | REM Command file for Sphinx documentation 6 | 7 | if "%SPHINXBUILD%" == "" ( 8 | set SPHINXBUILD=sphinx-build 9 | ) 10 | set SOURCEDIR=source 11 | set BUILDDIR=build 12 | set SPHINXPROJ=NiftyNet 13 | 14 | if "%1" == "" goto help 15 | 16 | %SPHINXBUILD% >NUL 2>NUL 17 | if errorlevel 9009 ( 18 | echo. 19 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 20 | echo.installed, then set the SPHINXBUILD environment variable to point 21 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 22 | echo.may add the Sphinx directory to PATH. 23 | echo. 24 | echo.If you don't have Sphinx installed, grab it from 25 | echo.http://sphinx-doc.org/ 26 | exit /b 1 27 | ) 28 | 29 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% 30 | goto end 31 | 32 | :help 33 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% 34 | 35 | :end 36 | popd 37 | -------------------------------------------------------------------------------- /doc/requirements.txt: -------------------------------------------------------------------------------- 1 | Sphinx>=1.6 2 | simpleitk 3 | sphinx-nameko-theme 4 | sphinx-markdown-tables==0.0.9 5 | recommonmark==0.4.0 6 | 7 | six>=1.10 8 | nibabel>=2.1.0 9 | numpy>=1.13.3 10 | scipy>=0.18 11 | configparser 12 | tensorflow==1.15.* 13 | pandas 14 | pillow 15 | blinker 16 | -------------------------------------------------------------------------------- /doc/source/_static/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/doc/source/_static/.gitkeep -------------------------------------------------------------------------------- /doc/source/_static/3d_sampling.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/doc/source/_static/3d_sampling.jpg -------------------------------------------------------------------------------- /doc/source/_static/custom.css: -------------------------------------------------------------------------------- 1 | body { 2 | font-family: "Helvetica", sans-serif; 3 | letter-spacing: 0.02em; 4 | line-height: 23px; 5 | } 6 | input, 7 | button, 8 | select, 9 | textarea { 10 | font-family: "Helvetica", sans-serif; 11 | } 12 | 13 | h1, h2 { 14 | clear: left; 15 | } 16 | h1 { 17 | font-size: 28px; 18 | line-height: 36px; 19 | } 20 | h2 { 21 | font-size: 22px; 22 | line-height: 30px; 23 | } 24 | -------------------------------------------------------------------------------- /doc/source/_static/grid.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/doc/source/_static/grid.png -------------------------------------------------------------------------------- /doc/source/_static/grid_cropped_50_12.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/doc/source/_static/grid_cropped_50_12.png -------------------------------------------------------------------------------- /doc/source/_static/grid_overlay.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/doc/source/_static/grid_overlay.png -------------------------------------------------------------------------------- /doc/source/_static/grid_pad_50.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/doc/source/_static/grid_pad_50.png -------------------------------------------------------------------------------- /doc/source/_static/grid_pad_50_12.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/doc/source/_static/grid_pad_50_12.png -------------------------------------------------------------------------------- /doc/source/_static/image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/doc/source/_static/image.png -------------------------------------------------------------------------------- /doc/source/_static/image_pad_50.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/doc/source/_static/image_pad_50.png -------------------------------------------------------------------------------- /doc/source/_static/uniform.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/doc/source/_static/uniform.png -------------------------------------------------------------------------------- /doc/source/_static/uniform_pad_50.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/doc/source/_static/uniform_pad_50.png -------------------------------------------------------------------------------- /doc/source/_static/uniform_pad_50_12.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/doc/source/_static/uniform_pad_50_12.png -------------------------------------------------------------------------------- /doc/source/_templates/badge.html: -------------------------------------------------------------------------------- 1 |

2 | pipeline status 3 | coverage report 4 |

-------------------------------------------------------------------------------- /doc/source/_templates/globaltoc.html: -------------------------------------------------------------------------------- 1 |

2 |
3 | 4 |

5 | {{ toctree(titles_only=True, collapse=False, maxdepth=2)}} 6 | -------------------------------------------------------------------------------- /doc/source/_templates/layout.html: -------------------------------------------------------------------------------- 1 | {%- extends "basic/layout.html" %} 2 | {%- block extrahead %} 3 | {{ super() }} 4 | 5 | 6 | 7 | {% endblock %} 8 | {%- block relbar2 %}{% endblock %} 9 | {% block header %} 10 | {{ super() }} 11 | {% if pagename == 'index' %} 12 |
13 | {% endif %} 14 | {% endblock %} 15 | {%- block footer %} 16 | 20 | {% if pagename == 'index' %} 21 |
22 | {% endif %} 23 | {%- endblock %} -------------------------------------------------------------------------------- /doc/source/extending_app.md: -------------------------------------------------------------------------------- 1 | # Extending application 2 | 3 | Please checkout [the slides](https://docs.google.com/presentation/d/1pjGUYTXpi-onbVe90pVtk2xKmBH_J9VYqkmJdXee1Dk/edit?usp=sharing) for an overview. 4 | 5 | 6 | -------------------------------------------------------------------------------- /doc/source/installation.rst: -------------------------------------------------------------------------------- 1 | Installation 2 | ============ 3 | 4 | 1. Installing the appropriate `TensorFlow`_ package: 5 | 6 | - ``pip install "tensorflow==1.15.*"`` 7 | 8 | 2. Installing NiftyNet package 9 | 10 | Option 1. released version from `PyPI`_: 11 | 12 | .. code-block:: bash 13 | 14 | pip install niftynet 15 | 16 | Option 2. latest dev version from `source code repository`_: 17 | 18 | .. code-block:: bash 19 | 20 | git clone https://github.com/NifTK/NiftyNet.git 21 | 22 | # installing dependencies from the list of requirements 23 | cd NiftyNet/ 24 | pip install -r requirements.txt 25 | 26 | Alternatively, you can `download the code`_ as a .zip file and extract it. 27 | 28 | 3. (Optional) Accessing MetaImage format (``.mha/.mhd`` files) requires SimpleITK: 29 | 30 | .. code-block:: bash 31 | 32 | pip install SimpleITK 33 | 34 | 35 | .. _`TensorFlow`: https://www.tensorflow.org/ 36 | .. _`PyPI`: https://pypi.org/project/NiftyNet/ 37 | .. _`source code repository`: https://github.com/NifTK/NiftyNet 38 | .. _`download the code`: https://github.com/NifTK/NiftyNet/archive/dev.zip 39 | -------------------------------------------------------------------------------- /doc/source/introductory.md: -------------------------------------------------------------------------------- 1 | # Platform overview 2 | 3 | Please checkout the talk at "Medical Imaging meets NIPS", NIPS 2017 by M. Jorge Cardoso: 4 | 5 | ['NiftyNet: An open-source community-driven framework for neural networks in medical imaging'](https://www.youtube.com/watch?v=ZaWStjGf0wg) 6 | 7 | 8 | -------------------------------------------------------------------------------- /doc/source/list_modules.rst: -------------------------------------------------------------------------------- 1 | niftynet 2 | -------- 3 | 4 | .. toctree:: 5 | :maxdepth: 1 6 | 7 | niftynet.application 8 | niftynet.contrib 9 | niftynet.engine 10 | niftynet.evaluation 11 | niftynet.io 12 | niftynet.layer 13 | niftynet.network 14 | niftynet.utilities 15 | -------------------------------------------------------------------------------- /doc/source/versioneer.rst: -------------------------------------------------------------------------------- 1 | versioneer module 2 | ================= 3 | 4 | .. automodule:: versioneer 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | -------------------------------------------------------------------------------- /net_autoencoder.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | import sys 4 | 5 | from niftynet import main 6 | 7 | if __name__ == "__main__": 8 | sys.exit(main()) 9 | -------------------------------------------------------------------------------- /net_classify.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | import sys 4 | 5 | from niftynet import main 6 | 7 | if __name__ == "__main__": 8 | sys.exit(main()) 9 | -------------------------------------------------------------------------------- /net_download.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | import sys 4 | 5 | from niftynet.utilities.download import main 6 | 7 | if __name__ == "__main__": 8 | sys.exit(main()) 9 | -------------------------------------------------------------------------------- /net_gan.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | import sys 4 | 5 | from niftynet import main 6 | 7 | if __name__ == "__main__": 8 | sys.exit(main()) 9 | -------------------------------------------------------------------------------- /net_regress.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | import sys 4 | 5 | from niftynet import main 6 | 7 | if __name__ == "__main__": 8 | sys.exit(main()) 9 | -------------------------------------------------------------------------------- /net_run.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | import sys 4 | 5 | from niftynet import main 6 | 7 | if __name__ == "__main__": 8 | sys.exit(main()) 9 | -------------------------------------------------------------------------------- /net_segment.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | import sys 4 | 5 | from niftynet import main 6 | 7 | if __name__ == "__main__": 8 | sys.exit(main()) 9 | -------------------------------------------------------------------------------- /niftynet-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/niftynet-logo.png -------------------------------------------------------------------------------- /niftynet/application/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | .. module:: niftynet.application 4 | :synopsis: Specific high-level NiftyNet applications. 5 | 6 | """ 7 | -------------------------------------------------------------------------------- /niftynet/contrib/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | .. module:: niftynet.contrib 4 | :synopsis: Experimental code for new features. 5 | 6 | """ 7 | -------------------------------------------------------------------------------- /niftynet/contrib/checkpoint_tools/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/niftynet/contrib/checkpoint_tools/__init__.py -------------------------------------------------------------------------------- /niftynet/contrib/csv_reader/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/niftynet/contrib/csv_reader/__init__.py -------------------------------------------------------------------------------- /niftynet/contrib/csv_reader/applications_maybe/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/niftynet/contrib/csv_reader/applications_maybe/__init__.py -------------------------------------------------------------------------------- /niftynet/contrib/csv_reader/default_segmentation_csvsampler.ini: -------------------------------------------------------------------------------- 1 | ############################ input configuration sections 2 | [modality1] 3 | path_to_search = ./example_volumes/csv_data 4 | filename_contains = MahalT1Mask_ 5 | filename_removefromid = MahalT1Mask_ 6 | filename_not_contains = 7 | spatial_window_size = (35, 35, 35) 8 | interp_order = 3 9 | pixdim=(2.0, 1.0, 1.0) 10 | axcodes=(A, R, S) 11 | 12 | [label] 13 | path_to_search = ./example_volumes/csv_data/ 14 | filename_contains = BinLabel 15 | filename_not_contains = 16 | filename_removefromid = BinLabel_ 17 | spatial_window_size = (35, 35, 35) 18 | interp_order = 0 19 | pixdim=(2.0, 1.0, 1.0) 20 | axcodes=(A, R, S) 21 | 22 | [sampler] 23 | csv_data_file = ./example_volumes/csv_data/PlacesLabels.csv 24 | 25 | ############################## system configuration sections 26 | [SYSTEM] 27 | cuda_devices = "" 28 | num_threads = 1 29 | num_gpus = 1 30 | model_dir = ./models/model_monomodal_toy 31 | 32 | [NETWORK] 33 | name = niftynet.network.toynet.ToyNet 34 | activation_function = prelu 35 | batch_size = 1 36 | decay = 0.1 37 | reg_type = L2 38 | 39 | # volume level preprocessing 40 | volume_padding_size = 1 41 | # histogram normalisation 42 | histogram_ref_file = ./example_volumes/monomodal_parcellation/standardisation_models.txt 43 | norm_type = percentile 44 | cutoff = (0.01, 0.99) 45 | normalisation = False 46 | whitening = False 47 | normalise_foreground_only=False 48 | foreground_type = otsu_plus 49 | multimod_foreground_type = and 50 | window_sampling=patch 51 | queue_length = 2 52 | 53 | 54 | [TRAINING] 55 | sample_per_volume = 1 56 | rotation_angle = (-10.0, 10.0) 57 | scaling_percentage = (-10.0, 10.0) 58 | random_flipping_axes= 1 59 | lr = 0.01 60 | loss_type = Dice 61 | starting_iter = 0 62 | save_every_n = 100 63 | max_iter = 10 64 | max_checkpoints = 20 65 | 66 | 67 | [INFERENCE] 68 | border = (0, 0, 1) 69 | #inference_iter = 10 70 | save_seg_dir = ./output/toy 71 | output_interp_order = 0 72 | spatial_window_size = (0, 0, 3) 73 | 74 | [EVALUATION] 75 | evaluations=Dice 76 | 77 | ############################ custom configuration sections 78 | [SEGMENTATION] 79 | image = modality1 80 | label = label 81 | sampler = sampler 82 | output_prob = False 83 | num_classes = 160 84 | label_normalisation = True 85 | -------------------------------------------------------------------------------- /niftynet/contrib/csv_reader/default_segmentation_multitask.ini: -------------------------------------------------------------------------------- 1 | ############################ input configuration sections 2 | [modality1] 3 | csv_file= 4 | path_to_search = ./example_volumes/monomodal_parcellation 5 | filename_contains = T1 6 | filename_removefromid = _T1 7 | filename_not_contains = 8 | spatial_window_size = (20, 42, 42) 9 | interp_order = 3 10 | pixdim=(1.0, 1.0, 1.0) 11 | axcodes=(A, R, S) 12 | 13 | [value] 14 | csv_data_file = ./example_volumes/monomodal_parcellation/class_pat.csv 15 | 16 | [label] 17 | path_to_search = ./example_volumes/monomodal_parcellation 18 | filename_contains = Label 19 | filename_not_contains = 20 | filename_removefromid = _Label 21 | spatial_window_size = (20, 42, 42) 22 | interp_order = 0 23 | pixdim=(1.0, 1.0, 1.0) 24 | axcodes=(A, R, S) 25 | 26 | ############################## system configuration sections 27 | [SYSTEM] 28 | cuda_devices = "" 29 | num_threads = 2 30 | num_gpus = 1 31 | model_dir = ./models/model_monomodal_multitask 32 | 33 | [NETWORK] 34 | name = toynet 35 | activation_function = prelu 36 | batch_size = 2 37 | decay = 0.1 38 | reg_type = L2 39 | 40 | # volume level preprocessing 41 | volume_padding_size = 21 42 | # histogram normalisation 43 | histogram_ref_file = ./example_volumes/monomodal_parcellation/standardisation_models.txt 44 | norm_type = percentile 45 | cutoff = (0.01, 0.99) 46 | normalisation = False 47 | whitening = False 48 | normalise_foreground_only=True 49 | foreground_type = otsu_plus 50 | multimod_foreground_type = and 51 | window_sampling=uniform 52 | queue_length = 10 53 | 54 | 55 | [TRAINING] 56 | sample_per_volume = 12 57 | rotation_angle = (-10.0, 10.0) 58 | scaling_percentage = (-10.0, 10.0) 59 | random_flipping_axes= 1 60 | lr = 0.01 61 | loss_type = Dice 62 | starting_iter = 0 63 | save_every_n = 100 64 | max_iter = 10 65 | max_checkpoints = 20 66 | 67 | [INFERENCE] 68 | border = (0, 0, 1) 69 | #inference_iter = 10 70 | save_seg_dir = ./output/toy 71 | output_interp_order = 0 72 | spatial_window_size = (20, 42, 42) 73 | 74 | [EVALUATION] 75 | evaluations=Dice 76 | 77 | ############################ custom configuration sections 78 | [SEGMENTATION] 79 | image = modality1 80 | label = label 81 | value = value 82 | output_prob = False 83 | num_classes = 160 84 | label_normalisation = True 85 | -------------------------------------------------------------------------------- /niftynet/contrib/csv_reader/toynet_features.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import absolute_import, print_function 3 | 4 | from niftynet.layer.convolution import ConvolutionalLayer 5 | from niftynet.network.base_net import BaseNet 6 | 7 | 8 | class ToyNetFeat(BaseNet): 9 | def __init__(self, 10 | num_classes, 11 | w_initializer=None, 12 | w_regularizer=None, 13 | b_initializer=None, 14 | b_regularizer=None, 15 | acti_func='prelu', 16 | name='ToyNet'): 17 | 18 | super(ToyNetFeat, self).__init__( 19 | num_classes=num_classes, 20 | w_initializer=w_initializer, 21 | w_regularizer=w_regularizer, 22 | b_initializer=b_initializer, 23 | b_regularizer=b_regularizer, 24 | acti_func=acti_func, 25 | name=name) 26 | 27 | self.hidden_features = 10 28 | 29 | def layer_op(self, images, is_training=True, **unused_kwargs): 30 | conv_1 = ConvolutionalLayer(self.hidden_features, 31 | kernel_size=3, 32 | w_initializer=self.initializers['w'], 33 | w_regularizer=self.regularizers['w'], 34 | b_initializer=self.initializers['b'], 35 | b_regularizer=self.regularizers['b'], 36 | acti_func='relu', 37 | name='conv_input') 38 | 39 | # conv_2 = ConvolutionalLayer(self.num_classes, 40 | # kernel_size=1, 41 | # w_initializer=self.initializers['w'], 42 | # w_regularizer=self.regularizers['w'], 43 | # b_initializer=self.initializers['b'], 44 | # b_regularizer=self.regularizers['b'], 45 | # acti_func=None, 46 | # name='conv_output') 47 | 48 | flow = conv_1(images, is_training) 49 | # flow = conv_2(flow, is_training) 50 | return flow 51 | -------------------------------------------------------------------------------- /niftynet/contrib/deep_boosted_regression/README.md: -------------------------------------------------------------------------------- 1 | # Deep Boosted Regression 2 | 3 | In order to train a neural network as in [1] you can add your data to a folder such as `/home/foo/data/` and then run the following line 4 | 5 | `python net_run.py train -c niftynet/contrib/deep_boosted_regression/net_DBR.ini -a niftynet.contrib.deep_boosted_regression.regression_rec_application.RegressionRecApplication` 6 | 7 | [1] Kläser K. et al. (2018) Deep Boosted Regression for MR to CT Synthesis. In: Gooya A., Goksel O., Oguz I., Burgos N. (eds) Simulation and Synthesis in Medical Imaging. SASHIMI 2018. Lecture Notes in Computer Science, vol 11037 -------------------------------------------------------------------------------- /niftynet/contrib/deep_boosted_regression/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/niftynet/contrib/deep_boosted_regression/__init__.py -------------------------------------------------------------------------------- /niftynet/contrib/deep_boosted_regression/net_DBR.ini: -------------------------------------------------------------------------------- 1 | 2 | [T1] 3 | spatial_window_size=(56, 56, 56) 4 | filename_contains=() 5 | filename_not_contains=() 6 | path_to_search=/home/foo/data/ 7 | interp_order=3 8 | 9 | [T2] 10 | spatial_window_size=(56, 56, 56) 11 | filename_contains=() 12 | filename_not_contains=() 13 | path_to_search=/home/foo/data/ 14 | interp_order=3 15 | 16 | [CT] 17 | spatial_window_size=(56, 56, 56) 18 | filename_contains=() 19 | filename_not_contains=() 20 | path_to_search=/home/foo/data/ 21 | interp_order=3 22 | 23 | [SAMPWEIGHT] 24 | spatial_window_size=(56,56,56) 25 | filename_contains=() 26 | filename_not_contains=() 27 | path_to_search=/home/foo/data/sampweight/ 28 | interp_order=3 29 | 30 | [TRAINING] 31 | loss_type=RMSE 32 | sample_per_volume=32 33 | tensorboard_every_n=10 34 | max_iter=40000 35 | save_every_n=1000 36 | max_checkpoints=100 37 | optimiser=adam 38 | lr=0.001 39 | starting_iter=0 40 | rotation_angle = (-10.0, 10.0) 41 | scaling_percentage = (-10.0, 10.0) 42 | random_flipping_axes= 1 43 | validation_every_n=200 44 | validation_max_iter=20 45 | exclude_fraction_for_validation=0.1 46 | exclude_fraction_for_inference=0.2 47 | 48 | [NETWORK] 49 | cutoff=(0.01, 0.99) 50 | multimod_foreground_type=and 51 | volume_padding_size=(16, 16, 16) 52 | name=highres3dnet 53 | decay=0.00000001 54 | activation_function=prelu 55 | normalise_foreground_only=False 56 | histogram_ref_file=/home/foo/model/ 57 | batch_size=1 58 | norm_type=percentile 59 | foreground_type=otsu_plus 60 | window_sampling=weighted 61 | whitening=True 62 | reg_type=L2 63 | normalisation=False 64 | 65 | [INFERENCE] 66 | border=(16, 16, 16) 67 | output_interp_order=3 68 | inference_iter=36000 69 | save_seg_dir=/home/foo/output/ 70 | spatial_window_size=(144, 144, 144) 71 | 72 | [SYSTEM] 73 | cuda_devices="" 74 | num_gpus=1 75 | num_threads=2 76 | queue_length=5 77 | model_dir=/home/foo/model/ 78 | 79 | [REGRESSION] 80 | output=CT 81 | image=T1, T2 82 | sampler=SAMPWEIGHT 83 | loss_border=8 84 | -------------------------------------------------------------------------------- /niftynet/contrib/evaluation/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/niftynet/contrib/evaluation/__init__.py -------------------------------------------------------------------------------- /niftynet/contrib/evaluation/regression_evaluations.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/niftynet/contrib/evaluation/regression_evaluations.py -------------------------------------------------------------------------------- /niftynet/contrib/layer/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/niftynet/contrib/layer/__init__.py -------------------------------------------------------------------------------- /niftynet/contrib/layer/resampler_optional_niftyreg.py: -------------------------------------------------------------------------------- 1 | # Flag stating whether C++/CUDA image resampling is available 2 | HAS_NIFTYREG_RESAMPLING = False 3 | 4 | try: 5 | from niftyreg_image_resampling import NiftyregImageResamplingLayer 6 | import niftyreg_image_resampling as resampler_module 7 | 8 | ResamplerOptionalNiftyRegLayer = NiftyregImageResamplingLayer 9 | 10 | HAS_NIFTYREG_RESAMPLING = True 11 | except ImportError: 12 | import tensorflow as tf 13 | 14 | tf.logging.warning(''' 15 | niftyreg_image_resampling is not installed; falling back onto 16 | niftynet.layer.resampler.ResamplerLayer. To install 17 | niftyreg_image_resampling please see 18 | niftynet/contrib/niftyreg_image_resampling/README.md 19 | ''') 20 | 21 | from niftynet.layer.resampler import ResamplerLayer 22 | import niftynet.layer.resampler as resampler_module 23 | 24 | ResamplerOptionalNiftyRegLayer = ResamplerLayer 25 | 26 | 27 | # Passthrough of supported boundary types 28 | SUPPORTED_BOUNDARY = resampler_module.SUPPORTED_BOUNDARY 29 | 30 | 31 | # Passthrough of supported interpolation types 32 | SUPPORTED_INTERPOLATION = resampler_module.SUPPORTED_INTERPOLATION 33 | -------------------------------------------------------------------------------- /niftynet/contrib/learning_rate_schedule/README.md: -------------------------------------------------------------------------------- 1 | # Learning rate decaying example 2 | 3 | This application implements a simple learning rate schedule of 4 | "halving the learning rate every 3 iterations" for segmentation applications. 5 | 6 | The concept is general and could be used for other types of application. 7 | 8 | The core function is implemented by 9 | 10 | 1) add a `self.learning_rate` placeholder, and connect it to the network 11 | in `connect_data_and_network` function 12 | 13 | 2) add a `self.current_lr` variable to keep track of the current learning rate 14 | 15 | 3) override the default `set_iteration_update` function provided in `BaseApplication` 16 | so that `self.current_lr` is changed according to the `current_iter`. 17 | 18 | 4) To feed the `self.current_lr` value to the network, the data feeding dictionary 19 | is updated within the customised `set_iteration_update` function, by 20 | ``` 21 | iteration_message.data_feed_dict[self.learning_rate] = self.current_lr 22 | ``` 23 | `iteration_message.data_feed_dict` will be used in 24 | `tf.Session.run(..., feed_dict=iteration_message.data_feed_dict)` by the engine 25 | at each iteration. 26 | 27 | 28 | To run this application from command line with a config file (e.g., `config/default_segmentation.ini`): 29 | ``` 30 | python net_run.py train -a niftynet.contrib.learning_rate_schedule.decay_lr_application.DecayLearningRateApplication 31 | -c config/default_segmentation.ini 32 | ``` -------------------------------------------------------------------------------- /niftynet/contrib/learning_rate_schedule/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/niftynet/contrib/learning_rate_schedule/__init__.py -------------------------------------------------------------------------------- /niftynet/contrib/multi_output/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/niftynet/contrib/multi_output/__init__.py -------------------------------------------------------------------------------- /niftynet/contrib/niftyreg_image_resampling/.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | -------------------------------------------------------------------------------- /niftynet/contrib/niftyreg_image_resampling/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2009, University College London, United-Kingdom 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | Neither the name of the University College London nor the names of its 14 | contributors may be used to endorse or promote products derived from 15 | this software without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 18 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 19 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 20 | ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 21 | LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 22 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 23 | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 24 | INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 25 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 26 | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 27 | THE POSSIBILITY OF SUCH DAMAGE. 28 | 29 | -------------------------------------------------------------------------------- /niftynet/contrib/niftyreg_image_resampling/README.md: -------------------------------------------------------------------------------- 1 | # NiftyNet GPU Image Resampling Module 2 | 3 | ## Purpose and Scope 4 | 5 | This module provides a faster implementation of image resampling. For most usage scenarios, it is a drop-in replacement for niftynet.layer.resampler.ResamplerLayer, however, its feature set is limited to: 6 | 7 | * ZERO (zero-padding), REPLICATE (clamping of intensities at edges), and SYMMETRIC (mirroring) boundaries 8 | * NEAREST (constant), LINEAR, and BSPLINE (cubic spline) interpolation. 9 | * Differentiation with respect to the floating image is a CPU-only operation. 10 | 11 | To provide compatibility where this module is not installed, the following module can be used: niftynet.contrib.layer.resampler_optional_niftyreg.ResamplerOptionalNiftyRegLayer. This module will try to load NiftyregImageResamplingLayer, if that fails, it defaults to niftynet.layer.resampler.ResamplerLayer. 12 | 13 | ## Building and Installing 14 | 15 | Building and installing is performed as usual via the setup file. 16 | 17 | Building the module requires that a CUDA toolkit and CMake be installed, and nvcc and cmake can be found on the executables search path. 18 | CMake variables can be overriden through the `override` command and `--settings`/`-s` switch as a list of colon (':') separated variable-value pairs. E.g., `python setup.py override -s "CMAKE_CXX_COMPILER:/usr/bin/g++-6:CMAKE_C_COMPILER:/usr/bin/gcc-6" build`. 19 | 20 | Building was only tested with CUDA 9.0/gcc 5.4 and gcc 6.4, on Ubuntu 16.04 and 18.04. 21 | 22 | ## Acknowledgements 23 | 24 | The image resampling code contained in this module is heavily based on code extracted from NiftyReg (https://sourceforge.net/projects/niftyreg/). 25 | 26 | -------------------------------------------------------------------------------- /niftynet/contrib/niftyreg_image_resampling/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/niftynet/contrib/niftyreg_image_resampling/__init__.py -------------------------------------------------------------------------------- /niftynet/contrib/niftyreg_image_resampling/niftyreg_gpu_resampler/_reg_maths_eigen.h: -------------------------------------------------------------------------------- 1 | //_reg_maths_eigen.h 2 | #ifndef _REG_MATHS_EIGEN_H 3 | #define _REG_MATHS_EIGEN_H 4 | 5 | #include "nifti1_io.h" 6 | 7 | /* *************************************************************** */ 8 | /* Functions calling the Eigen library */ 9 | /* See http://eigen.tuxfamily.org/index.php?title=Main_Page */ 10 | /* *************************************************************** */ 11 | 12 | /* *************************************************************** */ 13 | extern "C++" template 14 | void svd(T **in, size_t m, size_t n, T * w, T **v); 15 | /* *************************************************************** */ 16 | extern "C++" template 17 | void svd(T **in, size_t m, size_t n, T ***U, T ***S, T ***V); 18 | /* *************************************************************** */ 19 | extern "C++" template 20 | T reg_matrix2DDet(T** mat, size_t m, size_t n); 21 | /* *************************************************************** */ 22 | /** @brief Compute the inverse of a 4-by-4 matrix 23 | */ 24 | mat44 reg_mat44_inv(mat44 const* mat); 25 | /* *************************************************************** */ 26 | /** @brief Compute the square root of a 4-by-4 matrix 27 | */ 28 | mat44 reg_mat44_sqrt(mat44 const* mat); 29 | /* *************************************************************** */ 30 | /** @brief Compute the log of a 3-by-3 matrix 31 | */ 32 | void reg_mat33_expm(mat33 *in_tensor); 33 | /* *************************************************************** */ 34 | /** @brief Compute the exp of a 4-by-4 matrix 35 | */ 36 | mat44 reg_mat44_expm(const mat44 *mat); 37 | /* *************************************************************** */ 38 | /** @brief Compute the log of a 3-by-3 matrix 39 | */ 40 | void reg_mat33_logm(mat33 *in_tensor); 41 | /* *************************************************************** */ 42 | /** @brief Compute the log of a 4-by-4 matrix 43 | */ 44 | mat44 reg_mat44_logm(const mat44 *mat); 45 | /* *************************************************************** */ 46 | /** @brief Compute the average of two matrices using a log-euclidean 47 | * framework 48 | */ 49 | mat44 reg_mat44_avg2(mat44 const* A, mat44 const* b); 50 | 51 | #endif 52 | -------------------------------------------------------------------------------- /niftynet/contrib/niftyreg_image_resampling/niftyreg_gpu_resampler/_reg_resampling_gpu.h: -------------------------------------------------------------------------------- 1 | /* 2 | * _reg_resampling_gpu.h 3 | * 4 | * 5 | * Created by Marc Modat on 24/03/2009. 6 | * Copyright (c) 2009, University College London. All rights reserved. 7 | * Centre for Medical Image Computing (CMIC) 8 | * See the LICENSE.txt file in the nifty_reg root folder 9 | * 10 | */ 11 | 12 | #ifndef _REG_RESAMPLING_GPU_H 13 | #define _REG_RESAMPLING_GPU_H 14 | 15 | #include "_reg_common_cuda.h" 16 | #include "resampler_boundary.h" 17 | 18 | extern "C++" 19 | void reg_getImageGradient_gpu(const nifti_image &sourceImage, 20 | const nifti_image &deformationImage, 21 | const float *sourceImageArray_d, 22 | const float *positionFieldImageArray_d, 23 | float *resultGradientArray_d, 24 | const resampler_boundary_e boundary, 25 | const int interpolation); 26 | #endif 27 | -------------------------------------------------------------------------------- /niftynet/contrib/niftyreg_image_resampling/niftyreg_gpu_resampler/cmake/modules/FindNumPy.cmake: -------------------------------------------------------------------------------- 1 | if (NOT NumPy_FOUND) 2 | find_package(PythonInterp REQUIRED) 3 | 4 | execute_process(COMMAND "${PYTHON_EXECUTABLE}" "-c" "import numpy; print(numpy.get_include())" 5 | OUTPUT_VARIABLE NumPy_INCLUDE_DIR 6 | OUTPUT_STRIP_TRAILING_WHITESPACE 7 | ) 8 | 9 | set(NumPy_FOUND 1) 10 | endif (NOT NumPy_FOUND) 11 | -------------------------------------------------------------------------------- /niftynet/contrib/niftyreg_image_resampling/niftyreg_gpu_resampler/cmake/modules/FindTensorflow.cmake: -------------------------------------------------------------------------------- 1 | if (NOT Tensorflow_FOUND) 2 | find_package(PythonInterp REQUIRED) 3 | 4 | macro (get_tensorflow_setting OUTVAR SETTING_GETTER) 5 | execute_process( 6 | COMMAND "${PYTHON_EXECUTABLE}" -c "import tensorflow; ${SETTING_GETTER}" 7 | OUTPUT_VARIABLE ${OUTVAR} 8 | ERROR_QUIET 9 | OUTPUT_STRIP_TRAILING_WHITESPACE 10 | TIMEOUT 120 11 | ) 12 | endmacro (get_tensorflow_setting) 13 | 14 | get_tensorflow_setting(Tensorflow_INCLUDE_DIRS "print(tensorflow.sysconfig.get_include())") 15 | get_tensorflow_setting(Tensorflow_LIBRARY_DIRS "print(tensorflow.sysconfig.get_lib())") 16 | get_tensorflow_setting(Tensorflow_CFLAGS "print(' '.join(tensorflow.sysconfig.get_compile_flags()))") 17 | get_tensorflow_setting(Tensorflow_LFLAGS "print(' '.join(tensorflow.sysconfig.get_compile_link()))") 18 | 19 | set(Tensorflow_LIBRARIES 20 | "tensorflow_framework") 21 | 22 | if (Tensorflow_INCLUDE_DIRS) 23 | set(Tensorflow_FOUND 1) 24 | endif (Tensorflow_INCLUDE_DIRS) 25 | endif (NOT Tensorflow_FOUND) 26 | -------------------------------------------------------------------------------- /niftynet/contrib/niftyreg_image_resampling/niftyreg_gpu_resampler/interpolations.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "resampler_boundary.h" 4 | 5 | /** 6 | * \brief Cubic spline formula matching the one from niftynet.layer.resampler 7 | * \param relative floating point index relative to kernel base index. 8 | */ 9 | template 10 | NR_HOST_DEV void reg_getNiftynetCubicSpline(const TCoord relative, TBasis *p_basis); 11 | 12 | /** 13 | * \brief Analytic derivative of cubic spline formula matching the one from niftynet.layer.resampler 14 | * \param relative floating point index relative to kernel base index. 15 | */ 16 | template 17 | NR_HOST_DEV void reg_getNiftynetCubicSplineDerivative(const TCoord relative, TBasis *p_basis); 18 | 19 | #include "interpolations.tpp" 20 | -------------------------------------------------------------------------------- /niftynet/contrib/niftyreg_image_resampling/niftyreg_gpu_resampler/interpolations.tpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "interpolations.h" 4 | 5 | template 6 | NR_HOST_DEV void reg_getNiftynetCubicSpline(const TCoord relative, TBasis *p_basis) { 7 | const TCoord sqr_relative = relative*relative; 8 | 9 | p_basis[0] = (((-relative + 3)*relative - 3)*relative + 1)/6; 10 | p_basis[1] = ((3*relative - 6)*sqr_relative + 4)/6; 11 | p_basis[2] = (((-3*relative + 3)*relative + 3)*relative + 1)/6; 12 | p_basis[3] = sqr_relative*relative/6; 13 | } 14 | 15 | template 16 | NR_HOST_DEV void reg_getNiftynetCubicSplineDerivative(const TCoord relative, TBasis *p_basis) { 17 | p_basis[0] = ((-3*relative + 6)*relative - 3)/6; 18 | p_basis[1] = (9*relative - 12)*relative/6; 19 | p_basis[2] = ((-9*relative + 6)*relative + 3)/6; 20 | p_basis[3] = relative*relative/2; 21 | } 22 | -------------------------------------------------------------------------------- /niftynet/contrib/niftyreg_image_resampling/niftyreg_gpu_resampler/nifti/LICENSE: -------------------------------------------------------------------------------- 1 | Niftilib has been developed by members of the NIFTI DFWG and volunteers in the 2 | neuroimaging community and serves as a reference implementation of the nifti-1 3 | file format. 4 | 5 | http://nifti.nimh.nih.gov/ 6 | 7 | Nifticlib code is released into the public domain, developers are encouraged to 8 | incorporate niftilib code into their applications, and, to contribute changes 9 | and enhancements to niftilib. 10 | -------------------------------------------------------------------------------- /niftynet/contrib/niftyreg_image_resampling/niftyreg_gpu_resampler/niftyreg_cpu_resample_gradient_op.cpp: -------------------------------------------------------------------------------- 1 | #include "niftyreg_cpu_resample_gradient_op.h" 2 | #include "niftyreg_cpu_resample_op.h" 3 | 4 | #include "_reg_resampling.h" 5 | 6 | void NiftyRegCPUResampleGradientOp::Compute(tf::OpKernelContext *p_context) { 7 | float const *pc_floating = this->extract_floating_image(p_context).flat().data(); 8 | float const *pc_deformation = this->extract_deformation_image(p_context).flat().data(); 9 | float *p_gradient = nullptr; 10 | nifti_image *p_img_nim = nifti_simple_init_nim(); 11 | nifti_image *p_deformation_nim = nifti_simple_init_nim(); 12 | nifti_image gradient; 13 | int image_size; 14 | int displacement_size; 15 | tf::Tensor *p_output; 16 | 17 | this->populate_nifti_headers_from_context(*p_img_nim, *p_deformation_nim, p_context); 18 | 19 | image_size = p_img_nim->nvox; 20 | displacement_size = p_deformation_nim->nvox; 21 | 22 | p_context->allocate_output(0, this->compute_gradient_shape(p_context), &p_output); 23 | this->load_nifti_dimensions_from_tensor(gradient, *p_output); 24 | p_gradient = p_output->flat().data(); 25 | if (gradient.nu != p_deformation_nim->nu) { 26 | gradient.nu = gradient.dim[5] = p_deformation_nim->nu; 27 | gradient.nvox = p_deformation_nim->nvox; 28 | } 29 | 30 | for (int b = 0; b < this->batch_size(p_context); ++b) { 31 | for (int m = 0; m < p_img_nim->nu*p_img_nim->nt; ++m) { 32 | p_deformation_nim->data = const_cast(pc_deformation); 33 | p_img_nim->data = const_cast(pc_floating); 34 | gradient.data = p_gradient; 35 | 36 | reg_getImageGradient(p_img_nim, 37 | &gradient, 38 | p_deformation_nim, 39 | this->interpolation(), 40 | this->boundary(), 41 | m, 42 | nullptr); 43 | 44 | p_gradient += displacement_size; 45 | } 46 | pc_deformation += displacement_size; 47 | pc_floating += image_size; 48 | } 49 | 50 | p_img_nim->data = p_deformation_nim->data = nullptr; 51 | nifti_image_free(p_img_nim); 52 | nifti_image_free(p_deformation_nim); 53 | } 54 | -------------------------------------------------------------------------------- /niftynet/contrib/niftyreg_image_resampling/niftyreg_gpu_resampler/niftyreg_cpu_resample_gradient_op.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "niftyreg_cpu_resample_op.h" 4 | 5 | /** 6 | * \brief CPU implementation of gradient wrt. deformation 7 | */ 8 | class NiftyRegCPUResampleGradientOp : public NiftyRegCPUResampleOp { 9 | /** 10 | * \name Typedefs 11 | * @{ 12 | */ 13 | public: 14 | typedef NiftyRegCPUResampleOp Superclass; 15 | /** @} */ 16 | 17 | /** 18 | * \name Op API 19 | * @{ 20 | */ 21 | public: 22 | virtual void Compute(tf::OpKernelContext *p_context) override; 23 | /** @} */ 24 | 25 | /** 26 | * \name Instantiation 27 | * @{ 28 | */ 29 | public: 30 | explicit NiftyRegCPUResampleGradientOp(tf::OpKernelConstruction* context) : Superclass(context) {} 31 | /** @} */ 32 | }; 33 | -------------------------------------------------------------------------------- /niftynet/contrib/niftyreg_image_resampling/niftyreg_gpu_resampler/niftyreg_cpu_resample_image_gradient_op.cpp: -------------------------------------------------------------------------------- 1 | #include "niftyreg_cpu_resample_image_gradient_op.h" 2 | #include "_reg_resampling.h" 3 | 4 | tf::TensorShape NiftyRegCPUResampleImageGradientOp::compute_image_gradient_product_shape(tf::OpKernelContext *p_context) { 5 | return NiftyRegCPUResampleImageGradientOp::extract_image_shape(p_context); 6 | } 7 | 8 | tf::shape_inference::ShapeHandle NiftyRegCPUResampleImageGradientOp::compute_image_gradient_product_shape(tf::shape_inference::InferenceContext *p_context) { 9 | return p_context->input(0); 10 | } 11 | 12 | void NiftyRegCPUResampleImageGradientOp::Compute(tf::OpKernelContext *p_context) { 13 | const float *pc_image = p_context->input(0).flat().data(); 14 | const float *pc_deformation = p_context->input(1).flat().data(); 15 | const tf::Tensor &gradient_out = p_context->input(2); 16 | 17 | nifti_image image_nim; 18 | nifti_image deformation_nim; 19 | nifti_image gradient_out_nim; 20 | nifti_image gradient_image_nim; 21 | tf::Tensor *p_output; 22 | 23 | this->populate_nifti_headers_from_context(image_nim, deformation_nim, p_context); 24 | p_context->allocate_output(0, this->compute_image_gradient_product_shape(p_context), &p_output); 25 | this->load_nifti_dimensions_from_tensor(gradient_out_nim, gradient_out); 26 | this->load_nifti_dimensions_from_tensor(gradient_image_nim, *p_output); 27 | 28 | for (int b = 0; b < this->batch_size(p_context); ++b) { 29 | image_nim.data = const_cast(pc_image + b*image_nim.nvox); 30 | deformation_nim.data = const_cast(pc_deformation + b*deformation_nim.nvox); 31 | gradient_out_nim.data = const_cast(gradient_out.flat().data() + b*gradient_out_nim.nvox); 32 | gradient_image_nim.data = p_output->flat().data() + b*gradient_image_nim.nvox; 33 | 34 | compute_gradient_product(gradient_image_nim, image_nim, deformation_nim, gradient_out_nim, this->boundary(), this->interpolation()); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /niftynet/contrib/niftyreg_image_resampling/niftyreg_gpu_resampler/niftyreg_cpu_resample_image_gradient_op.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "niftyreg_cpu_resample_op.h" 4 | 5 | /** 6 | * \brief CPU implementation of NiftyRegResampleOp 7 | */ 8 | class NiftyRegCPUResampleImageGradientOp : public NiftyRegCPUResampleOp { 9 | /** 10 | * \name Typedefs 11 | * @{ 12 | */ 13 | public: 14 | typedef NiftyRegCPUResampleOp Superclass; 15 | /** @} */ 16 | 17 | /** 18 | * \name Op API 19 | * @{ 20 | */ 21 | public: 22 | /** \returns the size of the gradient outputted by this operation, at execution time */ 23 | static tf::TensorShape compute_image_gradient_product_shape(tf::OpKernelContext *p_context); 24 | 25 | /** \returns the size of the gradient outputted by this operation, at graph-compilation time */ 26 | static tf::shape_inference::ShapeHandle compute_image_gradient_product_shape(tf::shape_inference::InferenceContext *p_context); 27 | 28 | virtual void Compute(tf::OpKernelContext *p_context) override; 29 | /** @} */ 30 | 31 | /** 32 | * \name Instantiation 33 | * @{ 34 | */ 35 | public: 36 | explicit NiftyRegCPUResampleImageGradientOp(tf::OpKernelConstruction* context) : Superclass(context) {} 37 | /** @} */ 38 | }; 39 | -------------------------------------------------------------------------------- /niftynet/contrib/niftyreg_image_resampling/niftyreg_gpu_resampler/niftyreg_cpu_resample_op.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "niftyreg_resample_op.h" 4 | 5 | /** 6 | * \brief CPU implementation of NiftyRegResampleOp 7 | */ 8 | class NiftyRegCPUResampleOp : public NiftyRegResampleOp { 9 | /** 10 | * \name Typedefs 11 | * @{ 12 | */ 13 | public: 14 | typedef NiftyRegResampleOp Superclass; 15 | /** @} */ 16 | 17 | /** 18 | * \name Op API 19 | * @{ 20 | */ 21 | protected: 22 | /** \brief Fully populates the image and deformation-field Nifti-headers given the kernel context */ 23 | void populate_nifti_headers_from_context(nifti_image &r_image, nifti_image &r_deformation, tf::OpKernelContext *p_context) const; 24 | 25 | public: 26 | virtual void Compute(tf::OpKernelContext *p_context) override; 27 | /** @} */ 28 | 29 | /** 30 | * \name Instantiation 31 | * @{ 32 | */ 33 | public: 34 | explicit NiftyRegCPUResampleOp(tf::OpKernelConstruction* context) : Superclass(context) {} 35 | /** @} */ 36 | }; 37 | -------------------------------------------------------------------------------- /niftynet/contrib/niftyreg_image_resampling/niftyreg_gpu_resampler/niftyreg_gpu_resample_gradient_op.cu: -------------------------------------------------------------------------------- 1 | #include "niftyreg_gpu_resample_gradient_op.h" 2 | #include "niftyreg_gpu_resample_op.h" 3 | #include "_reg_resampling_gpu.h" 4 | 5 | #include 6 | 7 | void NiftyRegGPUResampleGradientOp::Compute(tf::OpKernelContext *p_context) { 8 | const auto &input_image = this->extract_floating_image(p_context); 9 | const auto &input_deformation = this->extract_deformation_image(p_context); 10 | 11 | nifti_image img_nim; 12 | nifti_image deformation_nim; 13 | float *dp_gradient; 14 | tf::Tensor *p_output; 15 | 16 | this->load_nifti_dimensions_from_tensors(img_nim, deformation_nim, input_image, input_deformation); 17 | 18 | p_context->allocate_output(0, this->compute_gradient_shape(p_context), &p_output); 19 | dp_gradient = p_output->flat().data(); 20 | 21 | if (this->interpolation() != 1 && this->interpolation() != 3) { 22 | std::cerr << "WARNING: gradient is only available for cubic/linear interpolation.\n"; 23 | } 24 | 25 | for (int b = 0; b < this->batch_size(p_context); ++b) { 26 | for (int m = 0; m < img_nim.nu; ++m) { 27 | const float *dpc_source = input_image.flat().data() + (b + m)*img_nim.nx*img_nim.ny*img_nim.nz; 28 | const float *dpc_deformation = input_deformation.flat().data() + b*deformation_nim.nvox; 29 | 30 | reg_getImageGradient_gpu(img_nim, 31 | deformation_nim, 32 | dpc_source, 33 | dpc_deformation, 34 | dp_gradient, 35 | this->boundary(), 36 | this->interpolation()); 37 | 38 | dp_gradient += deformation_nim.nvox; 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /niftynet/contrib/niftyreg_image_resampling/niftyreg_gpu_resampler/niftyreg_gpu_resample_gradient_op.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "niftyreg_gpu_resample_op.h" 4 | 5 | /** 6 | * \brief GPU implementation of gradient wrt. deformation 7 | */ 8 | class NiftyRegGPUResampleGradientOp : public NiftyRegGPUResampleOp { 9 | /** 10 | * \name Typedefs 11 | * @{ 12 | */ 13 | public: 14 | typedef NiftyRegGPUResampleOp Superclass; 15 | /** @} */ 16 | 17 | /** 18 | * \name Op API 19 | * @{ 20 | */ 21 | public: 22 | virtual void Compute(tf::OpKernelContext *p_context) override; 23 | /** @} */ 24 | 25 | /** 26 | * \name Instantiation 27 | * @{ 28 | */ 29 | public: 30 | explicit NiftyRegGPUResampleGradientOp(tf::OpKernelConstruction* context) : Superclass(context) {} 31 | /** @} */ 32 | }; 33 | -------------------------------------------------------------------------------- /niftynet/contrib/niftyreg_image_resampling/niftyreg_gpu_resampler/niftyreg_gpu_resample_op.cu: -------------------------------------------------------------------------------- 1 | #include "niftyreg_gpu_resample_op.h" 2 | #include "resampleKernel.h" 3 | #include "_reg_common_cuda.h" 4 | #ifdef DT_INT32 5 | #undef DT_INT32 6 | #endif 7 | #ifdef DT_FLOAT 8 | #undef DT_FLOAT 9 | #endif 10 | 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | void NiftyRegGPUResampleOp::Compute(tf::OpKernelContext *p_context) { 17 | const auto &input_image = this->extract_floating_image(p_context); 18 | const auto &input_deformation = this->extract_deformation_image(p_context); 19 | 20 | tf::Tensor *p_destination; 21 | nifti_image floating_image; 22 | nifti_image warped_image; 23 | nifti_image deformation_image; 24 | 25 | this->load_nifti_dimensions_from_tensors(floating_image, deformation_image, input_image, input_deformation); 26 | 27 | p_context->allocate_output(0, this->compute_output_shape(p_context), &p_destination); 28 | this->load_nifti_dimensions_from_tensor(warped_image, *p_destination); 29 | 30 | for (int b = 0; b < this->batch_size(p_context); ++b) { 31 | const float *dpc_floating = input_image.flat().data() + b*floating_image.nvox; 32 | const float *dpc_deformation = input_deformation.flat().data() + b*deformation_image.nvox; 33 | 34 | float *dp_warped = p_destination->flat().data() + b*warped_image.nvox; 35 | 36 | launchResample(&floating_image, &warped_image, this->interpolation(), this->boundary(), dpc_floating, dp_warped, dpc_deformation); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /niftynet/contrib/niftyreg_image_resampling/niftyreg_gpu_resampler/niftyreg_gpu_resample_op.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "niftyreg_resample_op.h" 4 | 5 | /** 6 | * \brief GPU Implementation of NiftyReg-powered image resampling operation. 7 | */ 8 | class NiftyRegGPUResampleOp : public NiftyRegResampleOp { 9 | /** 10 | * \name Typedefs 11 | * @{ 12 | */ 13 | public: 14 | typedef NiftyRegResampleOp Superclass; 15 | /** @} */ 16 | 17 | /** 18 | * \name Op API 19 | * @{ 20 | */ 21 | public: 22 | virtual void Compute(tf::OpKernelContext *p_context) override; 23 | /** @} */ 24 | 25 | /** 26 | * \name Instantiation 27 | * @{ 28 | */ 29 | public: 30 | explicit NiftyRegGPUResampleOp(tf::OpKernelConstruction* context) : Superclass(context) {} 31 | /** @} */ 32 | }; 33 | -------------------------------------------------------------------------------- /niftynet/contrib/niftyreg_image_resampling/niftyreg_gpu_resampler/resampleKernel.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "resampler_boundary.h" 4 | #include "nifti1_io.h" 5 | 6 | /** 7 | * \brief Runs a resampling operation on the image referenced by pc_floating. 8 | * \param[in] pc_floating floating image description (header only) 9 | * \param[in] pc_warped destination image description (header only) 10 | * \param interp interpolation code (0, 1, 3) 11 | * \param[out] dp_warped device base pointer of destination buffer. 12 | */ 13 | void launchResample(const nifti_image *pc_floating, const nifti_image *pc_warped, const int interp, 14 | const resampler_boundary_e boundary, const float *floatingImage_d, float *dp_warped, 15 | const float *dpc_deformation); 16 | 17 | /** 18 | * \brief Resamples the floating argument image based on the displacement/deformation field passed in r_displacements 19 | * \param r_displacements displacement/deformation field, if given as displacements it is converted to a deformation field in-place, thus destroying the original data. 20 | * \param floating the image to resample 21 | * \param interp_code a NiftyReg interpolation code (0, 1, 3, 4) 22 | * \param is_displacement_argument indicates if the first argument is a displacement field or a deformation field (default: true) 23 | * \returns the resampled image, to be freed by client 24 | */ 25 | nifti_image* resample(nifti_image &r_displacements, const nifti_image &floating, const int interp_code, const resampler_boundary_e boundary, const bool is_displacement_argument = true); 26 | 27 | -------------------------------------------------------------------------------- /niftynet/contrib/niftyreg_image_resampling/niftyreg_gpu_resampler/resampler_boundary.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #ifdef __CUDACC__ 4 | #define NR_HOST_DEV __host__ __device__ 5 | #else 6 | #define NR_HOST_DEV 7 | #endif 8 | 9 | /** \brief Resampler boundary treatment options */ 10 | enum class resampler_boundary_e { 11 | ZEROPAD = 0, /**< Zero-padding */ 12 | NANPAD, /**< NaN-padding */ 13 | CLAMPING, /**< Clamp to nearest boundary voxel intensity */ 14 | REFLECTING, /**< Reflect indices at boundaries */ 15 | SENTINEL, /**< Sentinel code */ 16 | }; 17 | 18 | /** 19 | * \brief Boundary index modification function 20 | * \tparam tBoundary boundary treatment enum value 21 | * \returns an appropriately modified index 22 | */ 23 | template 24 | NR_HOST_DEV int reg_applyBoundary(const int idx, const int bound); 25 | 26 | /** 27 | * \param bound upper bound on index 28 | * \tparam tBoundary boundary treatment enum value 29 | * \returns true if the argument index lies between 0 (incl) and bound (excl), or the index is guearanteed to be valid by virtue of the applied boundary treatment. 30 | */ 31 | template 32 | NR_HOST_DEV bool reg_checkImageDimensionIndex(const TIndex index, const TBound bound); 33 | 34 | /** \returns the appropriate padding value for a given boundary treatment enum value */ 35 | template 36 | NR_HOST_DEV constexpr TVoxel reg_getPaddingValue(const resampler_boundary_e boundary); 37 | 38 | #include "resampler_boundary.tpp" 39 | -------------------------------------------------------------------------------- /niftynet/contrib/niftyreg_image_resampling/niftyreg_gpu_resampler/resampler_boundary.tpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "resampler_boundary.h" 4 | 5 | #include 6 | #include 7 | #include 8 | 9 | template 10 | NR_HOST_DEV int reg_applyBoundary(const int idx, const int bound) { 11 | int bdyIdx = idx; 12 | 13 | switch (tBoundary) { 14 | case resampler_boundary_e::CLAMPING: 15 | bdyIdx = bdyIdx >= 0? bdyIdx : 0; 16 | bdyIdx = bdyIdx < bound? bdyIdx : bound - 1; 17 | break; 18 | 19 | case resampler_boundary_e::REFLECTING: { 20 | const int wrap_size = 2*bound - 2; 21 | 22 | bdyIdx = bound - 1 - std::abs(bound - 1 - (bdyIdx%wrap_size + wrap_size)%wrap_size); 23 | break; 24 | } 25 | } 26 | 27 | return bdyIdx; 28 | } 29 | /* *************************************************************** */ 30 | template 31 | NR_HOST_DEV bool reg_checkImageDimensionIndex(const TIndex index, const TBound bound) { 32 | return resampler_boundary_e(tBoundary) == resampler_boundary_e::CLAMPING || resampler_boundary_e(tBoundary) == resampler_boundary_e::REFLECTING || (index >= 0 && index < bound); 33 | } 34 | /* *************************************************************** */ 35 | template 36 | NR_HOST_DEV constexpr TVoxel reg_getPaddingValue(const resampler_boundary_e boundary) { 37 | return boundary == resampler_boundary_e::ZEROPAD? TVoxel(0) 38 | : (std::is_integral::value? std::numeric_limits::lowest() : std::numeric_limits::quiet_NaN()); 39 | } 40 | -------------------------------------------------------------------------------- /niftynet/contrib/niftyreg_image_resampling/niftyreg_module_loader.py.in: -------------------------------------------------------------------------------- 1 | import os.path as osp 2 | import tensorflow as tf 3 | 4 | __MODULE_FILENAME__ = '$' 5 | __INSTALL_LOCATION__ \ 6 | = '$' 7 | __BUILD_LOCATION__ \ 8 | = '$' 9 | 10 | 11 | def _find_and_load_op(): 12 | for test_path in (osp.join(osp.dirname(__file__), __MODULE_FILENAME__), 13 | osp.join('.', __INSTALL_LOCATION__, __MODULE_FILENAME__), 14 | osp.join(__INSTALL_LOCATION__, __MODULE_FILENAME__), 15 | osp.join(__BUILD_LOCATION__, __MODULE_FILENAME__)): 16 | if osp.isfile(test_path): 17 | return tf.load_op_library(test_path) 18 | 19 | # raise ImportError('Could not locate resampling library: %s' 20 | # % __MODULE_FILENAME__) 21 | 22 | 23 | __nr_module__ = _find_and_load_op() 24 | 25 | 26 | def get_niftyreg_module(): 27 | return __nr_module__ 28 | -------------------------------------------------------------------------------- /niftynet/contrib/niftyreg_image_resampling/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/niftynet/contrib/niftyreg_image_resampling/tests/__init__.py -------------------------------------------------------------------------------- /niftynet/contrib/preprocessors/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/niftynet/contrib/preprocessors/__init__.py -------------------------------------------------------------------------------- /niftynet/contrib/regression_weighted_sampler/README.md: -------------------------------------------------------------------------------- 1 | ### Training regression network with weighted sampling of image windows 2 | 3 | ref: 4 | 5 | Berger et al., "An Adaptive Sampling Scheme to Efficiently Train Fully Convolutional Networks for Semantic Segmentation", 6 | https://arxiv.org/pdf/1709.02764.pdf 7 | 8 | Please see [the model zoo entry](https://github.com/NifTK/NiftyNetModelZoo/blob/master/mr_ct_regression_model_zoo.md) 9 | for instructions for downloading data and config file. 10 | 11 | ### Training regression network with autocontext model 12 | 13 | Please see [the model zoo entry](https://github.com/NifTK/NiftyNetModelZoo/blob/master/autocontext_mr_ct_model_zoo.md) 14 | for instructions for downloading data and config file. 15 | 16 | 17 | ### Parameters for config file in the regression section 18 | |Params.| Type |Example|Default| 19 | |---|---|---|---| 20 | |[error_map](#error_map)|Boolean|`error_map=True`|`'False'`| 21 | 22 | 23 | ###### `error_map` 24 | At inference time, setting the parameter to True to generate errormaps on the input data. 25 | 26 | -------------------------------------------------------------------------------- /niftynet/contrib/regression_weighted_sampler/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/niftynet/contrib/regression_weighted_sampler/__init__.py -------------------------------------------------------------------------------- /niftynet/contrib/sampler_pairwise/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/niftynet/contrib/sampler_pairwise/__init__.py -------------------------------------------------------------------------------- /niftynet/contrib/segmentation_bf_aug/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/niftynet/contrib/segmentation_bf_aug/__init__.py -------------------------------------------------------------------------------- /niftynet/contrib/segmentation_selective_sampler/README.md: -------------------------------------------------------------------------------- 1 | ### Training segmentation network with selective sampling of image windows 2 | 3 | To run this application (from NiftyNet source code root folder) 4 | with a config file (e.g., `niftynet/contrib/segmentation_selective_sampler/selective_seg.ini`) 5 | ```bash 6 | python net_run.py train -a niftynet.contrib.segmentation_selective_sampler.ss_app.SelectiveSampling \ 7 | -c niftynet/contrib/segmentation_selective_sampler/selective_seg.ini 8 | ``` 9 | 10 | ### Parameters for config file in the SEGMENTATION section 11 | |Params.| Type |Example|Default| 12 | |---|---|---|---| 13 | |[rand_samples](#rand_samples)|Integer|`rand_samples=5`|`'0'`| 14 | |[min_numb_labels](#min_numb_labels)|Integer|`min_numb_labels=3`|`'1'`| 15 | |[proba_connect](#proba_connect)|Boolean|`proba_connect=False`|`'False'`| 16 | |[min_sampling_ratio](#min_sampling_ratio)|Float|`min_sampling_ratio=0.001`|`'0.00001'`| 17 | |[compulsory_labels](#compulsory_labels)|Integer array|`compulsory_labels=0, 2`|`0, 1`| 18 | 19 | 20 | ###### `rand_samples` 21 | Integer - Number of samples taken without any sampling rule / using a uniform sampler 22 | 23 | ###### `min_numb_labels` 24 | Integer - Minimum number of labels present in a sampling window 25 | 26 | ###### `proba_connect` 27 | Boolean - Indicates the distribution of sizes of connected components should be considered in the sampling 28 | 29 | ###### `min_sampling_ratio` 30 | Float - Minimum frequency of each label in the sampled window 31 | 32 | ###### `compulsory_labels` 33 | List of integers - Labels that must be present in the sampled window 34 | -------------------------------------------------------------------------------- /niftynet/contrib/segmentation_selective_sampler/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/niftynet/contrib/segmentation_selective_sampler/__init__.py -------------------------------------------------------------------------------- /niftynet/contrib/segmentation_selective_sampler/selective_seg.ini: -------------------------------------------------------------------------------- 1 | ############################ input configuration sections 2 | [modality1] 3 | csv_file= 4 | path_to_search = ./example_volumes/monomodal_parcellation 5 | filename_contains = T1 6 | filename_not_contains = 7 | spatial_window_size = (20, 42, 42) 8 | interp_order = 3 9 | pixdim=(1.0, 1.0, 1.0) 10 | axcodes=(A, R, S) 11 | 12 | [label] 13 | path_to_search = ./example_volumes/monomodal_parcellation 14 | filename_contains = Label 15 | filename_not_contains = 16 | spatial_window_size = (20, 42, 42) 17 | interp_order = 0 18 | pixdim=(1.0, 1.0, 1.0) 19 | axcodes=(A, R, S) 20 | 21 | ############################## system configuration sections 22 | [SYSTEM] 23 | cuda_devices = "" 24 | num_threads = 2 25 | num_gpus = 1 26 | model_dir = ./models/model_monomodal_toy 27 | 28 | [NETWORK] 29 | name = toynet 30 | activation_function = prelu 31 | batch_size = 1 32 | decay = 0.1 33 | reg_type = L2 34 | 35 | # volume level preprocessing 36 | volume_padding_size = 21 37 | # histogram normalisation 38 | histogram_ref_file = ./example_volumes/monomodal_parcellation/standardisation_models.txt 39 | norm_type = percentile 40 | cutoff = (0.01, 0.99) 41 | normalisation = False 42 | whitening = False 43 | normalise_foreground_only=True 44 | foreground_type = otsu_plus 45 | multimod_foreground_type = and 46 | 47 | queue_length = 20 48 | 49 | 50 | [TRAINING] 51 | sample_per_volume = 32 52 | rotation_angle = (-10.0, 10.0) 53 | scaling_percentage = (-10.0, 10.0) 54 | random_flipping_axes= 1 55 | lr = 0.01 56 | loss_type = Dice 57 | starting_iter = 0 58 | save_every_n = 100 59 | max_iter = 10 60 | max_checkpoints = 20 61 | 62 | [INFERENCE] 63 | border = (0, 0, 1) 64 | #inference_iter = 10 65 | save_seg_dir = ./output/toy 66 | output_interp_order = 0 67 | spatial_window_size = (0, 0, 3) 68 | 69 | ############################ custom configuration sections 70 | [SEGMENTATION] 71 | image = modality1 72 | label = label 73 | output_prob = False 74 | num_classes = 160 75 | label_normalisation = True 76 | 77 | rand_samples=0 78 | min_numb_labels=1 79 | proba_connect=True 80 | compulsory_labels=0, 1 81 | -------------------------------------------------------------------------------- /niftynet/contrib/ultrasound_simulator_gan/README.md: -------------------------------------------------------------------------------- 1 | # Freehand Ultrasound Image Simulation with Spatially-Conditioned Generative Adversarial Networks 2 | 3 | This page describes how to acquire and use the network described in 4 | 5 | Yipeng Hu, Eli Gibson, Li-Lin Lee, Weidi Xie, Dean C. Barratt, Tom Vercauteren, J. Alison Noble 6 | (2017). [Freehand Ultrasound Image Simulation with Spatially-Conditioned Generative Adversarial Networks](https://arxiv.org/abs/1707.05392), In MICCAI RAMBO 2017 7 | 8 | ## Downloading model zoo file and conditioning data 9 | 10 | The model zoo file is available [here](https://www.dropbox.com/s/etptck5yi1fzvkr/ultrasound_simulator_gan_model_zoo.tar.gz?dl=0). Extract the model directory named `ultrasound_simulator_gan_model_zoo` from this file. 11 | 12 | This network generates ultrasound images conditioned by a coordinate map. Example coordinate maps are available [here](https://www.dropbox.com/s/w0frdlxaie3mndg/test_data.tar.gz?dl=0)). Extract `test_data.tar.gz` to a data directory. 13 | 14 | ## Editing the configuration file 15 | 16 | Inside the model_dir is a configuration file: `inference_config.ini`. You will need to change this file to point to the correct paths for the model directory (`model_dir=`) and the conditioning data (`path_to_search=`). 17 | 18 | ## Generating samples 19 | 20 | Generate samples from the simulator with the command `net_gan.py inference -c ultrasound_simulator_gan_model_zoo/inference_config.ini` 21 | 22 | 23 | -------------------------------------------------------------------------------- /niftynet/contrib/ultrasound_simulator_gan/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/niftynet/contrib/ultrasound_simulator_gan/__init__.py -------------------------------------------------------------------------------- /niftynet/engine/README.md: -------------------------------------------------------------------------------- 1 | ### Structure 2 | The basic picture of a training procedure (data parallelism) is: 3 | ``` 4 | 5 | (engine/training.py) 6 | |>----------------------+ 7 | |>---------------+ | 8 | |^| | | 9 | (engine/input_buffer.py) |^| sync GPU_1 GPU_2 ... 10 | |^| +----> model model (network/*.py) 11 | with multiple threads: |^| | | | 12 | (layer/input_normalisation.py) |^| CPU v v (layer/*.py) 13 | image&label ->> (engine/*_sampler.py) >>> | model <----+------+ 14 | (*.nii.gz) (layer/rand_*.py) >>> | update stochastic gradients 15 | ``` 16 | -------------------------------------------------------------------------------- /niftynet/engine/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | 5 | .. module:: niftynet.engine 6 | :synopsis: Application engine. 7 | 8 | """ 9 | -------------------------------------------------------------------------------- /niftynet/engine/handler_console.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | This module implements a console output writer. 4 | """ 5 | 6 | import tensorflow as tf 7 | 8 | from niftynet.engine.application_variables import CONSOLE 9 | from niftynet.engine.signal import ITER_STARTED, ITER_FINISHED 10 | 11 | 12 | class ConsoleLogger(object): 13 | """ 14 | This class handles iteration events to print output to the console. 15 | """ 16 | 17 | def __init__(self, **_unused): 18 | ITER_STARTED.connect(self.read_console_vars) 19 | ITER_FINISHED.connect(self.print_console_vars) 20 | 21 | def read_console_vars(self, sender, **msg): 22 | """ 23 | Event handler to add all console output ops to the iteration message 24 | 25 | :param sender: a niftynet.application instance 26 | :param msg: an iteration message instance 27 | :return: 28 | """ 29 | msg['iter_msg'].ops_to_run[CONSOLE] = \ 30 | sender.outputs_collector.variables(CONSOLE) 31 | 32 | def print_console_vars(self, _sender, **msg): 33 | """ 34 | Printing iteration message with ``tf.logging`` interface. 35 | 36 | :param _sender: 37 | :param msg: an iteration message instance 38 | :return: 39 | """ 40 | tf.logging.info(msg['iter_msg'].to_console_string()) 41 | -------------------------------------------------------------------------------- /niftynet/engine/handler_network_output.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | This module implements a network output interpreter. 4 | """ 5 | from niftynet.engine.application_variables import NETWORK_OUTPUT 6 | from niftynet.engine.signal import ITER_STARTED, ITER_FINISHED 7 | 8 | 9 | class OutputInterpreter(object): 10 | """ 11 | This class handles iteration events to interpret output. 12 | """ 13 | 14 | def __init__(self, **_unused): 15 | ITER_STARTED.connect(self.set_tensors_to_run) 16 | ITER_FINISHED.connect(self.interpret_output) 17 | 18 | def set_tensors_to_run(self, sender, **msg): 19 | """ 20 | Event handler to add all tensors to evaluate to the iteration message. 21 | The driver will fetch tensors' values from 22 | ``_iter_msg.ops_to_run``. 23 | 24 | :param sender: a niftynet.application instance 25 | :param msg: an iteration message instance 26 | :return: 27 | """ 28 | _iter_msg = msg['iter_msg'] 29 | _iter_msg.ops_to_run[NETWORK_OUTPUT] = \ 30 | sender.outputs_collector.variables(NETWORK_OUTPUT) 31 | 32 | # modifying `_iter_msg` using applications's set_iteration_update 33 | sender.set_iteration_update(_iter_msg) 34 | 35 | def interpret_output(self, sender, **msg): 36 | """ 37 | Calling sender application to interpret evaluated tensors. 38 | Set ``_iter_msg.should_stop`` to a True value 39 | if it's an end of the engine loop. 40 | 41 | See also: 42 | ``niftynet.engine.application_driver.loop`` 43 | 44 | :param sender: a niftynet.application instance 45 | :param msg: an iteration message instance 46 | :return: 47 | """ 48 | _iter_msg = msg['iter_msg'] 49 | waiting_for_more_output = sender.interpret_output( 50 | _iter_msg.current_iter_output[NETWORK_OUTPUT]) 51 | if not waiting_for_more_output: 52 | _iter_msg.should_stop = OutputInterpreter.__name__ 53 | -------------------------------------------------------------------------------- /niftynet/engine/handler_performance.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | This module tracks model validation performance over training 4 | """ 5 | import tensorflow as tf 6 | 7 | from niftynet.engine.application_variables import CONSOLE 8 | from niftynet.engine.signal import ITER_FINISHED 9 | 10 | 11 | class PerformanceLogger(object): 12 | """ 13 | This class handles iteration events to store the current performance as 14 | an attribute of the sender (i.e. application). 15 | """ 16 | 17 | def __init__(self, **_unused): 18 | ITER_FINISHED.connect(self.update_performance_history) 19 | 20 | def update_performance_history(self, _sender, **msg): 21 | """ 22 | Printing iteration message with ``tf.logging`` interface. 23 | :param _sender: 24 | :param msg: an iteration message instance 25 | :return: 26 | """ 27 | iter_msg = msg['iter_msg'] 28 | 29 | if iter_msg.is_validation: 30 | try: 31 | console_content = iter_msg.current_iter_output.get(CONSOLE, '') 32 | current_loss = console_content['total_loss'] 33 | 34 | if len(_sender.performance_history) < _sender.patience: 35 | _sender.performance_history.append(current_loss) 36 | else: 37 | _sender.performance_history = \ 38 | _sender.performance_history[1:] + [current_loss] 39 | except (AttributeError, KeyError): 40 | tf.logging.warning("does not contain any performance field " 41 | "called total loss.") 42 | -------------------------------------------------------------------------------- /niftynet/engine/handler_sampler.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | This module implements a sampler threads controller. 4 | """ 5 | import tensorflow as tf 6 | 7 | # from niftynet.engine.signal import SESS_STARTED 8 | from niftynet.engine.signal import SESS_FINISHED 9 | from niftynet.utilities.util_common import traverse_nested 10 | 11 | 12 | class SamplerThreading(object): 13 | """ 14 | This class handles iteration events to start/stop samplers' threads. 15 | """ 16 | 17 | def __init__(self, **_unused): 18 | # SESS_STARTED.connect(self.start_sampler_threads) 19 | SESS_FINISHED.connect(self.stop_sampler_threads) 20 | 21 | def start_sampler_threads(self, _sender, **_unused_msg): 22 | """ 23 | Get samplers from application and try to run sampler's threads. 24 | 25 | (deprecating) 26 | 27 | :param sender: 28 | :param _unused_msg: 29 | :return: 30 | """ 31 | pass 32 | # try: 33 | # for sampler in traverse_nested(sender.get_sampler()): 34 | # if sampler is None: 35 | # continue 36 | # sampler.run_threads(self.num_threads) 37 | # tf.logging.info('filling queues (this can take a few minutes).') 38 | # except (NameError, TypeError, AttributeError, IndexError): 39 | # tf.logging.fatal( 40 | # "samplers not running, pop_batch_op operations " 41 | # "are blocked.") 42 | # raise 43 | 44 | def stop_sampler_threads(self, sender, **_unused_msg): 45 | """ 46 | Stop the sampler's threads 47 | 48 | :param sender: an instance of niftynet.application 49 | :param _unused_msg: 50 | :return: 51 | """ 52 | try: 53 | tf.logging.info('stopping sampling threads') 54 | for sampler in traverse_nested(sender.get_sampler()): 55 | if sampler is None: 56 | continue 57 | sampler.close_all() 58 | except (AttributeError, TypeError): 59 | pass 60 | -------------------------------------------------------------------------------- /niftynet/engine/signal.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | This module defines default signals supported by NiftyNet engine. 4 | 5 | By design, all connected functions (event handlers) have access 6 | to TF session and graph 7 | by ``tf.get_default_session()`` and ``tf.get_default_graph()``. 8 | """ 9 | 10 | from __future__ import print_function 11 | from __future__ import unicode_literals 12 | 13 | from blinker import Namespace 14 | 15 | # possible phases of the engine, used throughout the project. 16 | TRAIN = 'training' 17 | VALID = 'validation' 18 | INFER = 'inference' 19 | EVAL = 'evaluation' 20 | ALL = 'all' 21 | 22 | #: namespace of NiftyNet's default signals. 23 | NIFTYNET = Namespace() 24 | 25 | #: Signal emitted immediately after the application's graph is created 26 | GRAPH_CREATED = NIFTYNET.signal( 27 | 'graph_started', 28 | doc="emitted when application's graph is created") 29 | 30 | #: Signal emitted at the beginning of a training/inference process 31 | #: (after the creation of both graph and session.) 32 | SESS_STARTED = NIFTYNET.signal( 33 | 'session_started', 34 | doc='signal emitted at the beginning of the training/inference loop.') 35 | 36 | #: Signal emitted before the end of a training/inference process 37 | #: (after the creation of both graph and session.) 38 | SESS_FINISHED = NIFTYNET.signal( 39 | 'session_finished', 40 | doc='signal emitted at the end of the training/inference loop.') 41 | 42 | #: Signal emitted immediately when each iteration starts 43 | #: (after the creation of both graph and session.) 44 | ITER_STARTED = NIFTYNET.signal( 45 | 'iteration_started', 46 | doc='emitted when every iteration starts, before ``tf.session.run(...)``.') 47 | 48 | #: Signal emitted before the end of each iteration 49 | #: (after the creation of both graph and session.) 50 | ITER_FINISHED = NIFTYNET.signal( 51 | 'iteration_finished', 52 | doc='emitted at the end of each iteration, after ``tf.session.run(...)``.') 53 | 54 | 55 | # EPOCH_STARTED = NIFTYNET.signal( 56 | # 'epoch_started', 57 | # doc='emitted at the beginning of each training epoch') 58 | # EPOCH_FINISHED = NIFTYNET.signal( 59 | # 'epoch_finished', 60 | # doc='emitted at the end of each training epoch') 61 | -------------------------------------------------------------------------------- /niftynet/evaluation/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | .. module:: niftynet.evaluation 4 | :synopsis: Evaluation metrics for network outputs. 5 | 6 | """ 7 | -------------------------------------------------------------------------------- /niftynet/evaluation/classification_evaluations.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | This module defines built-in evaluation functions for classification 4 | applications 5 | 6 | Many classification metrics only make sense computed over all subjects, 7 | so aggregation is used. 8 | """ 9 | 10 | from __future__ import absolute_import, division, print_function 11 | 12 | import numpy as np 13 | import pandas as pd 14 | 15 | from niftynet.evaluation.base_evaluations import BaseEvaluation 16 | from niftynet.evaluation.base_evaluator import ScalarAggregator,\ 17 | DataFrameAggregator 18 | 19 | class accuracy(BaseEvaluation): 20 | def layer_op(self, subject_id, data): 21 | metric_name = 'accuracy_' 22 | if self.app_param.output_prob: 23 | inferred_label = np.argmax(data['inferred'][0,0,0,0,:]) 24 | else: 25 | inferred_label = data['inferred'][0,0,0,0,0] 26 | pdf = pd.DataFrame.from_records([{'subject_id':subject_id, 27 | 'acc_i':inferred_label, 28 | 'acc_l':data['label'][0,0,0,0,0]}], 29 | index=('subject_id',)) 30 | return [pdf] 31 | 32 | def aggregate(self, df): 33 | print(df) 34 | agg = pd.DataFrame.from_records([{'accuracy':(df.acc_i==df.acc_l).mean()}]) 35 | return [agg] 36 | 37 | def get_aggregations(self): 38 | return [DataFrameAggregator(('subject_id',), self.aggregate)] 39 | -------------------------------------------------------------------------------- /niftynet/evaluation/classification_evaluator.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | This module defines the specialized Evaluator for classification applications 4 | All logic except default metrics is delegated to the parent class 5 | """ 6 | 7 | from __future__ import absolute_import, division, print_function 8 | 9 | from niftynet.evaluation.base_evaluator import BaseEvaluator 10 | 11 | class ClassificationEvaluator(BaseEvaluator): 12 | """ 13 | Evaluator for ClassificationApplication 14 | """ 15 | def default_evaluation_list(self): 16 | """ 17 | :return: list of metric names to compute by default 18 | """ 19 | return ['classification_accuracy', 'roc_auc', 'roc'] 20 | -------------------------------------------------------------------------------- /niftynet/evaluation/regression_evaluations.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | This module defines built-in evaluation functions for regression applications 4 | 5 | """ 6 | 7 | from __future__ import absolute_import, division, print_function 8 | 9 | import numpy as np 10 | import pandas as pd 11 | 12 | from niftynet.evaluation.base_evaluations import BaseEvaluation 13 | 14 | 15 | class BaseRegressionEvaluation(BaseEvaluation): 16 | """ Interface for scalar regression metrics """ 17 | def layer_op(self, subject_id, data): 18 | metric_name = self.__class__.__name__ 19 | metric_value = self.metric(data['inferred'], data['output']) 20 | pdf = pd.DataFrame.from_records([{'subject_id':subject_id, 21 | metric_name:metric_value}], 22 | ('subject_id',)) 23 | return [pdf] 24 | 25 | def metric(self, reg, ref): 26 | """ 27 | Computes a scalar value for the metric 28 | :param reg: np.array with inferred regression 29 | :param ref: np array with the reference output 30 | :return: scalar metric value 31 | """ 32 | raise NotImplementedError 33 | 34 | #pylint: disable=invalid-name 35 | class mse(BaseRegressionEvaluation): 36 | """ Computes mean squared error """ 37 | def metric(self, reg, ref): 38 | return np.mean(np.square(reg - ref)) 39 | 40 | 41 | class rmse(BaseRegressionEvaluation): 42 | """ Computes root mean squared error """ 43 | def metric(self, reg, ref): 44 | return np.sqrt(np.mean(np.square(reg - ref))) 45 | 46 | 47 | class mae(BaseRegressionEvaluation): 48 | """ Computes mean absolute error """ 49 | def metric(self, reg, ref): 50 | return np.mean(np.abs(ref - reg)) 51 | -------------------------------------------------------------------------------- /niftynet/evaluation/regression_evaluator.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | This module defines the specialized Evaluator for segmentation applications 4 | All logic except default metrics is delegated to the parent class 5 | """ 6 | 7 | from __future__ import absolute_import, division, print_function 8 | 9 | from niftynet.evaluation.base_evaluator import BaseEvaluator 10 | 11 | class RegressionEvaluator(BaseEvaluator): 12 | """ 13 | Evaluator for RegressionApplication 14 | """ 15 | def default_evaluation_list(self): 16 | """ 17 | :return: list of metric names to compute by default 18 | """ 19 | return ['mse', 'rmse', 'mae'] 20 | -------------------------------------------------------------------------------- /niftynet/evaluation/segmentation_evaluator.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | This module defines the specialized Evaluator for segmentation applications 4 | All logic except default metrics is delegated to the parent class 5 | """ 6 | 7 | from __future__ import absolute_import, division, print_function 8 | 9 | from niftynet.evaluation.base_evaluator import CachedSubanalysisEvaluator 10 | 11 | class SegmentationEvaluator(CachedSubanalysisEvaluator): 12 | """ 13 | Evaluator for SegmentationApplication 14 | Supports caching of intermediate results which is 15 | important for boundary error calculations 16 | """ 17 | def default_evaluation_list(self): 18 | """ 19 | :return: list of metric names to compute by default 20 | """ 21 | return ['dice', 'jaccard', 'average_distance'] 22 | -------------------------------------------------------------------------------- /niftynet/io/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | .. module:: niftynet.io 4 | :synopsis: High-level input / output operations. 5 | 6 | """ 7 | -------------------------------------------------------------------------------- /niftynet/layer/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | .. module:: niftynet.layer 4 | :synopsis: Building blocks for neural network layers. 5 | 6 | """ 7 | -------------------------------------------------------------------------------- /niftynet/layer/crop.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import absolute_import, print_function 3 | 4 | import tensorflow as tf 5 | 6 | from niftynet.layer import layer_util 7 | from niftynet.layer.base_layer import Layer 8 | 9 | 10 | class CropLayer(Layer): 11 | """ 12 | This class defines a cropping operation: 13 | Removing ``2*border`` pixels from each spatial dim of the input, 14 | and return the spatially centred elements extracted from the input. 15 | """ 16 | 17 | def __init__(self, border, name='crop'): 18 | super(CropLayer, self).__init__(name=name) 19 | self.border = border 20 | 21 | def layer_op(self, inputs): 22 | spatial_rank = layer_util.infer_spatial_rank(inputs) 23 | offsets = [0] + [int(self.border)] * spatial_rank + [0] 24 | # inferring the shape of the output by subtracting the border dimension 25 | out_shape = [ 26 | int(d) - 2 * int(self.border) 27 | for d in list(inputs.shape)[1:-1]] 28 | out_shape = [-1] + out_shape + [-1] 29 | output_tensor = tf.slice(inputs, offsets, out_shape) 30 | return output_tensor 31 | -------------------------------------------------------------------------------- /niftynet/layer/dilatedcontext.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import absolute_import, print_function 3 | 4 | import tensorflow as tf 5 | 6 | from niftynet.layer import layer_util 7 | 8 | 9 | class DilatedTensor(object): 10 | """ 11 | This context manager makes a wrapper of input_tensor 12 | When created, the input_tensor is dilated, 13 | the input_tensor resumes to original space when exiting the context. 14 | """ 15 | 16 | def __init__(self, input_tensor, dilation_factor): 17 | assert (layer_util.check_spatial_dims( 18 | input_tensor, lambda x: x % dilation_factor == 0)) 19 | self._tensor = input_tensor 20 | self.dilation_factor = dilation_factor 21 | # parameters to transform input tensor 22 | self.spatial_rank = layer_util.infer_spatial_rank(self._tensor) 23 | self.zero_paddings = [[0, 0]] * self.spatial_rank 24 | self.block_shape = [dilation_factor] * self.spatial_rank 25 | 26 | def __enter__(self): 27 | if self.dilation_factor > 1: 28 | self._tensor = tf.space_to_batch_nd(self._tensor, 29 | self.block_shape, 30 | self.zero_paddings, 31 | name='dilated') 32 | return self 33 | 34 | def __exit__(self, *args): 35 | if self.dilation_factor > 1: 36 | self._tensor = tf.batch_to_space_nd(self._tensor, 37 | self.block_shape, 38 | self.zero_paddings, 39 | name='de-dilate') 40 | 41 | @property 42 | def tensor(self): 43 | return self._tensor 44 | 45 | @tensor.setter 46 | def tensor(self, value): 47 | self._tensor = value 48 | -------------------------------------------------------------------------------- /niftynet/layer/figures/elu_eq.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/niftynet/layer/figures/elu_eq.pdf -------------------------------------------------------------------------------- /niftynet/layer/figures/elu_img.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/niftynet/layer/figures/elu_img.png -------------------------------------------------------------------------------- /niftynet/layer/figures/prelu_eq.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/niftynet/layer/figures/prelu_eq.pdf -------------------------------------------------------------------------------- /niftynet/layer/figures/prelu_img.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/niftynet/layer/figures/prelu_img.png -------------------------------------------------------------------------------- /niftynet/layer/figures/relu_eq.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/niftynet/layer/figures/relu_eq.pdf -------------------------------------------------------------------------------- /niftynet/layer/figures/relu_img.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/niftynet/layer/figures/relu_img.png -------------------------------------------------------------------------------- /niftynet/layer/figures/sigmoid_eq.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/niftynet/layer/figures/sigmoid_eq.pdf -------------------------------------------------------------------------------- /niftynet/layer/figures/sigmoid_img.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/niftynet/layer/figures/sigmoid_img.png -------------------------------------------------------------------------------- /niftynet/layer/figures/softplus_eq.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/niftynet/layer/figures/softplus_eq.pdf -------------------------------------------------------------------------------- /niftynet/layer/figures/softplus_img.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/niftynet/layer/figures/softplus_img.png -------------------------------------------------------------------------------- /niftynet/layer/figures/softsign_eq.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/niftynet/layer/figures/softsign_eq.pdf -------------------------------------------------------------------------------- /niftynet/layer/figures/softsign_img.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/niftynet/layer/figures/softsign_img.png -------------------------------------------------------------------------------- /niftynet/layer/figures/tanh_eq.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/niftynet/layer/figures/tanh_eq.pdf -------------------------------------------------------------------------------- /niftynet/layer/figures/tanh_img.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/niftynet/layer/figures/tanh_img.png -------------------------------------------------------------------------------- /niftynet/layer/gan_blocks.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import absolute_import, print_function, division 3 | 4 | import tensorflow as tf 5 | 6 | from niftynet.layer.base_layer import TrainableLayer 7 | 8 | 9 | class GANImageBlock(TrainableLayer): 10 | def __init__(self, 11 | generator, 12 | discriminator, 13 | clip=None, 14 | name='GAN_image_block'): 15 | self._generator = generator 16 | self._discriminator = discriminator 17 | self.clip = clip 18 | super(GANImageBlock, self).__init__(name=name) 19 | 20 | def layer_op(self, 21 | random_source, 22 | training_image, 23 | conditioning, 24 | is_training): 25 | shape_to_generate = training_image.shape.as_list()[1:] 26 | fake_image = self._generator(random_source, 27 | shape_to_generate, 28 | conditioning, 29 | is_training) 30 | 31 | fake_logits = self._discriminator(fake_image, 32 | conditioning, 33 | is_training) 34 | if self.clip: 35 | with tf.name_scope('clip_real_images'): 36 | training_image = tf.maximum( 37 | -self.clip, 38 | tf.minimum(self.clip, training_image)) 39 | real_logits = self._discriminator(training_image, 40 | conditioning, 41 | is_training) 42 | return fake_image, real_logits, fake_logits 43 | 44 | 45 | class BaseGenerator(TrainableLayer): 46 | def __init__(self, name='generator', *args, **kwargs): 47 | super(BaseGenerator, self).__init__(name=name) 48 | 49 | 50 | class BaseDiscriminator(TrainableLayer): 51 | def __init__(self, name='discriminator', *args, **kwargs): 52 | super(BaseDiscriminator, self).__init__(name=name) 53 | -------------------------------------------------------------------------------- /niftynet/layer/loss_gan.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import absolute_import, print_function 3 | 4 | import tensorflow as tf 5 | 6 | from niftynet.engine.application_factory import LossGANFactory 7 | from niftynet.layer.base_layer import Layer 8 | 9 | 10 | class LossFunction(Layer): 11 | def __init__(self, 12 | loss_type='CrossEntropy', 13 | loss_func_params=None, 14 | name='loss_function'): 15 | 16 | super(LossFunction, self).__init__(name=name) 17 | if loss_func_params is not None: 18 | self._loss_func_params = loss_func_params 19 | else: 20 | self._loss_func_params = {} 21 | self._data_loss_func = None 22 | self.make_callable_loss_func(loss_type) 23 | 24 | def make_callable_loss_func(self, type_str): 25 | self._data_loss_func = LossGANFactory.create(type_str) 26 | 27 | def layer_op(self, pred_real, pred_fake, var_scope=None): 28 | with tf.device('/cpu:0'): 29 | g_loss = self._data_loss_func['g']( 30 | pred_fake, 31 | **self._loss_func_params) 32 | d_fake = self._data_loss_func['d_fake']( 33 | pred_fake, 34 | **self._loss_func_params) 35 | d_real = self._data_loss_func['d_real']( 36 | pred_real, 37 | **self._loss_func_params) 38 | return g_loss, (d_fake + d_real) 39 | 40 | 41 | def cross_entropy_function(is_real, softness=.1): 42 | def cross_entropy_op(pred, **kwargs): 43 | if is_real: 44 | target = (1. - softness) * tf.ones_like(pred) 45 | else: 46 | target = softness * tf.ones_like(pred) 47 | entropy = tf.nn.sigmoid_cross_entropy_with_logits(logits=pred, 48 | labels=target) 49 | return tf.reduce_mean(entropy) 50 | 51 | return cross_entropy_op 52 | 53 | 54 | cross_entropy = {'g': cross_entropy_function(True, 0), 55 | 'd_fake': cross_entropy_function(False, 0), 56 | 'd_real': cross_entropy_function(True, .1)} 57 | -------------------------------------------------------------------------------- /niftynet/layer/post_processing.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import absolute_import, print_function 3 | 4 | import tensorflow as tf 5 | 6 | from niftynet.layer.base_layer import Layer 7 | from niftynet.utilities.util_common import look_up_operations 8 | 9 | SUPPORTED_OPS = set(["SOFTMAX", "ARGMAX", "IDENTITY"]) 10 | 11 | 12 | class PostProcessingLayer(Layer): 13 | """ 14 | This layer operation converts the raw network outputs into final inference 15 | results. 16 | """ 17 | 18 | def __init__(self, func='', num_classes=0, name='post_processing'): 19 | super(PostProcessingLayer, self).__init__(name=name) 20 | self.func = look_up_operations(func.upper(), SUPPORTED_OPS) 21 | self.num_classes = num_classes 22 | 23 | def num_output_channels(self): 24 | assert self._op._variables_created 25 | if self.func == "SOFTMAX": 26 | return self.num_classes 27 | else: 28 | return 1 29 | 30 | def layer_op(self, inputs): 31 | if self.func == "SOFTMAX": 32 | output_tensor = tf.cast(tf.nn.softmax(inputs), tf.float32) 33 | elif self.func == "ARGMAX": 34 | output_tensor = tf.cast(tf.argmax(inputs, -1), tf.int32) 35 | output_tensor = tf.expand_dims(output_tensor, axis=-1) 36 | elif self.func == "IDENTITY": 37 | output_tensor = tf.cast(inputs, tf.float32) 38 | return output_tensor 39 | -------------------------------------------------------------------------------- /niftynet/network/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | .. module:: niftynet.network 4 | :synopsis: Neural network (re-)implementations. 5 | 6 | """ 7 | -------------------------------------------------------------------------------- /niftynet/network/base_net.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import, print_function 2 | 3 | import tensorflow as tf 4 | from niftynet.layer.base_layer import TrainableLayer 5 | 6 | 7 | class BaseNet(TrainableLayer): 8 | """ 9 | Template for networks 10 | """ 11 | 12 | def __init__(self, 13 | num_classes=0, 14 | w_initializer=None, 15 | w_regularizer=None, 16 | b_initializer=None, 17 | b_regularizer=None, 18 | acti_func='prelu', 19 | name="net_template"): 20 | 21 | super(BaseNet, self).__init__(name=name) 22 | 23 | self.num_classes = num_classes 24 | self.acti_func = acti_func 25 | 26 | self.initializers = {'w': w_initializer, 'b': b_initializer} 27 | self.regularizers = {'w': w_regularizer, 'b': b_regularizer} 28 | 29 | tf.logging.info('using {}'.format(name)) 30 | -------------------------------------------------------------------------------- /niftynet/utilities/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | .. module:: niftynet.utilities 4 | :synopsis: High-level re-usable utilities. 5 | 6 | """ 7 | 8 | 9 | from .niftynet_launch_config import NiftyNetLaunchConfig 10 | -------------------------------------------------------------------------------- /niftynet/utilities/decorators.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import absolute_import, print_function 3 | 4 | from functools import wraps 5 | 6 | 7 | def singleton(cls): 8 | """Decorate a class as singleton. 9 | 10 | Inspired by: https://wiki.python.org/moin/PythonDecoratorLibrary#Singleton 11 | """ 12 | 13 | cls.__new_original__ = cls.__new__ 14 | 15 | @wraps(cls.__new__) 16 | def singleton_new(cls, *args, **kw): 17 | it = cls.__dict__.get('__it__') 18 | if it is not None: 19 | return it 20 | 21 | cls.__it__ = it = cls.__new_original__(cls, *args, **kw) 22 | it.__init_original__(*args, **kw) 23 | return it 24 | 25 | cls.__new__ = staticmethod(singleton_new) 26 | cls.__init_original__ = cls.__init__ 27 | cls.__init__ = object.__init__ 28 | 29 | return cls 30 | -------------------------------------------------------------------------------- /niftynet/utilities/niftynet_launch_config.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | NiftyNet launch configuration 4 | """ 5 | 6 | 7 | try: 8 | import ConfigParser as configparser 9 | except ImportError: 10 | import configparser 11 | 12 | 13 | class NiftyNetLaunchConfig(configparser.ConfigParser): 14 | """Launch configuration settings""" 15 | 16 | pass 17 | -------------------------------------------------------------------------------- /niftynet/utilities/util_import.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ check module to be imported""" 3 | import importlib 4 | 5 | import tensorflow as tf 6 | 7 | 8 | def require_module(name, 9 | min_version=None, 10 | descriptor='Optional', 11 | mandatory=False): 12 | """ 13 | Check if the module exists, and 14 | satisfies the minimum version requirement. 15 | 16 | Returns the imported module if it satisfies requirements. 17 | 18 | Raises ImportError and AssertionError. 19 | 20 | :param name: 21 | :param min_version: 22 | :param descriptor: 23 | :param mandatory: 24 | :return: the imported module 25 | """ 26 | 27 | name = '{}'.format(name) 28 | log_level = tf.logging.fatal if mandatory else tf.logging.info 29 | 30 | try: 31 | the_module = importlib.import_module(name) 32 | except ImportError: 33 | log_level( 34 | descriptor + ' Python module %s not found, ' 35 | 'please install %s and retry if the application fails.', 36 | name, name) 37 | if mandatory: 38 | raise 39 | 40 | try: 41 | if min_version is not None: 42 | if isinstance(min_version, tuple): 43 | version_number = the_module.__version__.split('.') 44 | min_version = tuple(int(v) for v in min_version) 45 | mod_version = tuple(int(v) for v in version_number) 46 | else: 47 | mod_version = the_module.__version__ 48 | min_version = '{}'.format(min_version) 49 | 50 | assert mod_version >= min_version 51 | return the_module 52 | except AttributeError: 53 | pass 54 | except (AssertionError, NameError): 55 | log_level( 56 | descriptor + ' Python module %s version %s not found, ' 57 | 'please install %s-%s and retry if the application fails.', 58 | name, min_version, name, min_version) 59 | if mandatory: 60 | raise 61 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | six>=1.10 2 | nibabel>=2.1.0 3 | numpy>=1.13.3 4 | scipy>=0.18 5 | configparser 6 | tensorflow==1.15.* 7 | pandas 8 | pillow 9 | blinker 10 | packaging 11 | -------------------------------------------------------------------------------- /run_test.sh: -------------------------------------------------------------------------------- 1 | wget -q https://www.dropbox.com/s/lioecnpv82r5n6e/example_volumes_v0_2.tar.gz 2 | tar -xzvf example_volumes_v0_2.tar.gz 3 | rm example_volumes_v0_2.tar.gz 4 | wget -N https://www.dropbox.com/s/p7b3t2c3mewtree/testing_data_v0_2.tar.gz 5 | tar -xzvf testing_data_v0_2.tar.gz 6 | rm testing_data_v0_2.tar.gz 7 | wget -N https://www.dropbox.com/s/gt0hm6o61rlsfcc/csv_data.tar.gz 8 | tar -C data -xzvf csv_data.tar.gz 9 | rm csv_data.tar.gz 10 | 11 | python -m unittest discover -s "tests" -p "*_test.py" 12 | 13 | ## run global config tests 14 | ## These need to be run separately because NiftyNetGlobalConfig is a singleton, AND 15 | ## its operations pertain to a global configuration file (~/.niftynet/config.ini). 16 | #GLOBAL_CONFIG_TEST_gcs=True python -m unittest tests.niftynet_global_config_test 17 | #GLOBAL_CONFIG_TEST_necfc=True python -m unittest tests.niftynet_global_config_test 18 | #GLOBAL_CONFIG_TEST_ecfl=True python -m unittest tests.niftynet_global_config_test 19 | #GLOBAL_CONFIG_TEST_icfbu=True python -m unittest tests.niftynet_global_config_test 20 | #GLOBAL_CONFIG_TEST_nenhc=True python -m unittest tests.niftynet_global_config_test 21 | #GLOBAL_CONFIG_TEST_enhnt=True python -m unittest tests.niftynet_global_config_test 22 | 23 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bdist_wheel] 2 | universal=1 3 | 4 | [versioneer] 5 | VCS=git 6 | versionfile_source=niftynet/utilities/versioneer_version.py 7 | style=pep440 8 | tag_prefix=v 9 | -------------------------------------------------------------------------------- /tests/README.md: -------------------------------------------------------------------------------- 1 | ## Writing unit tests 2 | Please checkout [niftynet.readthedocs.io](http://niftynet.readthedocs.io/en/dev/contributing.html#writing-unit-tests). 3 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NifTK/NiftyNet/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/tests/__init__.py -------------------------------------------------------------------------------- /tests/application_factory_test.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import, print_function 2 | 3 | import tensorflow as tf 4 | import niftynet.engine.application_factory as Factory 5 | from tests.niftynet_testcase import NiftyNetTestCase 6 | 7 | class FactoryTest(NiftyNetTestCase): 8 | def test_import(self): 9 | var_names = [ 10 | item for item in list(dir(Factory)) if item.startswith("SUPPORTED")] 11 | for var_name in var_names: 12 | mod_table = Factory.__dict__[var_name] 13 | for mod_name in list(mod_table): 14 | Factory.select_module(mod_name, 'test', mod_table) 15 | 16 | 17 | 18 | if __name__ == "__main__": 19 | tf.test.main() 20 | -------------------------------------------------------------------------------- /tests/binary_masking_test.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import, print_function 2 | 3 | import numpy as np 4 | import tensorflow as tf 5 | 6 | from niftynet.layer.binary_masking import BinaryMaskingLayer 7 | from tests.niftynet_testcase import NiftyNetTestCase 8 | 9 | 10 | class BinaryMaskingTest(NiftyNetTestCase): 11 | def get_3d_input(self): 12 | input_shape = (16, 16, 16) 13 | x = np.random.randint(-10, 10, size=input_shape) 14 | return x 15 | 16 | def get_5d_input(self): 17 | input_shape = (16, 16, 16, 3, 2) 18 | x = np.random.randint(-10, 10, size=input_shape) 19 | return x 20 | 21 | def test_3d_plus_shape(self): 22 | x = self.get_3d_input() 23 | mask_layer = BinaryMaskingLayer( 24 | type_str='otsu_plus', 25 | multimod_fusion='or', 26 | threshold=0.0) 27 | mask_out = mask_layer(x) 28 | print(mask_layer) 29 | self.assertAllClose(x.shape, mask_out.shape) 30 | 31 | def test_3d_minus_shape(self): 32 | x = self.get_3d_input() 33 | mask_layer = BinaryMaskingLayer( 34 | type_str='otsu_minus', 35 | multimod_fusion='or', 36 | threshold=0.0) 37 | mask_out = mask_layer(x) 38 | print(mask_layer) 39 | self.assertAllClose(x.shape, mask_out.shape) 40 | 41 | def test_5d_shape(self): 42 | x = self.get_5d_input() 43 | mask_layer = BinaryMaskingLayer( 44 | type_str='threshold_minus', 45 | multimod_fusion='and', 46 | threshold=0.0) 47 | mask_out = mask_layer(x) 48 | print(mask_layer) 49 | self.assertAllClose(x.shape, mask_out.shape) 50 | 51 | def test_5d_mean_shape(self): 52 | x = self.get_5d_input() 53 | mask_layer = BinaryMaskingLayer( 54 | type_str='mean_plus', 55 | multimod_fusion='and', 56 | threshold=0.0) 57 | mask_out = mask_layer(x) 58 | print(mask_layer) 59 | self.assertAllClose(x.shape, mask_out.shape) 60 | 61 | 62 | if __name__ == "__main__": 63 | tf.test.main() 64 | -------------------------------------------------------------------------------- /tests/classification_evaluator_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import absolute_import, print_function 3 | 4 | import six 5 | import numpy as np 6 | import tensorflow as tf 7 | 8 | from niftynet.evaluation.classification_evaluator import ClassificationEvaluator 9 | from niftynet.io.misc_io import set_logger 10 | from tests.niftynet_testcase import NiftyNetTestCase 11 | 12 | class ClassificationEvaluatorTest(NiftyNetTestCase): 13 | def test_basic(self): 14 | class NS(object): 15 | def __init__(self, dict): 16 | self.__dict__.update(dict) 17 | classification_param=NS({'num_classes':2, 18 | 'output_prob':False}) 19 | eval_param=NS({'evaluations':'niftynet.evaluation.classification_evaluations.accuracy'}) 20 | positive = np.reshape(1,[1,1,1,1,1]) 21 | negative = np.reshape(0,[1,1,1,1,1]) 22 | mask = np.reshape(np.abs(np.linspace(0.,2.,64)-1)>.8,[4,4,4,1,1]) 23 | tp = {'label':positive,'inferred':positive} 24 | fp = {'label':negative,'inferred':positive} 25 | tn = {'label':negative,'inferred':negative} 26 | fn = {'label':positive,'inferred':negative} 27 | interp_orders = {'label':0,'inferred':-1} 28 | image_folder = '.' 29 | e = ClassificationEvaluator(None, classification_param, eval_param) 30 | 31 | def generator(): 32 | yield ('test1', tp,interp_orders) 33 | yield ('test2', tp,interp_orders) 34 | yield ('test3', fn,interp_orders) 35 | yield ('test4', fp,interp_orders) 36 | 37 | result_dict = e.evaluate_from_generator(generator()) 38 | self.assertIn((None,), result_dict) 39 | self.assertEqual(result_dict[(None,)].to_dict('index'), 40 | {0: {'accuracy': 0.5}}) 41 | 42 | 43 | 44 | if __name__ == "__main__": 45 | set_logger() 46 | # _run_test_application() 47 | tf.test.main() 48 | -------------------------------------------------------------------------------- /tests/crop_test.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import, print_function 2 | 3 | import tensorflow as tf 4 | from niftynet.layer.crop import CropLayer 5 | from tests.niftynet_testcase import NiftyNetTestCase 6 | 7 | class CropTest(NiftyNetTestCase): 8 | def test_3d_shape(self): 9 | input_shape = (2, 16, 16, 16, 8) 10 | test_border = 3 11 | x = tf.ones(input_shape) 12 | 13 | crop_layer = CropLayer(border=test_border) 14 | out_crop = crop_layer(x) 15 | print(crop_layer) 16 | 17 | input_shape = (2, 7, 7, 7, 8) 18 | test_border = 3 19 | x = tf.ones(input_shape) 20 | 21 | crop_layer = CropLayer(border=test_border) 22 | out_crop_1 = crop_layer(x) 23 | print(crop_layer) 24 | 25 | with self.cached_session() as sess: 26 | out = sess.run(out_crop) 27 | out_1 = sess.run(out_crop_1) 28 | self.assertAllClose((2, 10, 10, 10, 8), out.shape) 29 | self.assertAllClose((2, 1, 1, 1, 8), out_1.shape) 30 | 31 | def test_2d_shape(self): 32 | input_shape = (2, 16, 16, 8) 33 | test_border = 3 34 | x = tf.ones(input_shape) 35 | 36 | crop_layer = CropLayer(border=test_border) 37 | out_crop = crop_layer(x) 38 | print(crop_layer) 39 | 40 | input_shape = (2, 7, 7, 8) 41 | test_border = 3 42 | x = tf.ones(input_shape) 43 | 44 | crop_layer = CropLayer(border=test_border) 45 | out_crop_1 = crop_layer(x) 46 | print(crop_layer) 47 | 48 | with self.cached_session() as sess: 49 | out = sess.run(out_crop) 50 | out_1 = sess.run(out_crop_1) 51 | self.assertAllClose((2, 10, 10, 8), out.shape) 52 | self.assertAllClose((2, 1, 1, 8), out_1.shape) 53 | 54 | 55 | if __name__ == "__main__": 56 | tf.test.main() 57 | -------------------------------------------------------------------------------- /tests/dense_vnet_test.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import, print_function 2 | 3 | import unittest 4 | 5 | import os 6 | import tensorflow as tf 7 | from tensorflow.contrib.layers.python.layers import regularizers 8 | 9 | from niftynet.network.dense_vnet import DenseVNet 10 | from tests.niftynet_testcase import NiftyNetTestCase 11 | 12 | @unittest.skipIf(os.environ.get('QUICKTEST', "").lower() == "true", 'Skipping slow tests') 13 | class DenseVNetTest(NiftyNetTestCase): 14 | def test_3d_shape(self): 15 | input_shape = (2, 72, 72, 72, 3) 16 | x = tf.ones(input_shape) 17 | 18 | dense_vnet_instance = DenseVNet( 19 | num_classes=2) 20 | out = dense_vnet_instance(x, is_training=True) 21 | # print(tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)) 22 | 23 | with self.cached_session() as sess: 24 | sess.run(tf.global_variables_initializer()) 25 | out = sess.run(out) 26 | self.assertAllClose((2, 72, 72, 72, 2), out.shape) 27 | 28 | def test_2d_shape(self): 29 | input_shape = (2, 72, 72, 3) 30 | x = tf.ones(input_shape) 31 | 32 | dense_vnet_instance = DenseVNet( 33 | num_classes=2) 34 | out = dense_vnet_instance(x, is_training=True) 35 | # print(tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)) 36 | 37 | with self.cached_session() as sess: 38 | sess.run(tf.global_variables_initializer()) 39 | out = sess.run(out) 40 | self.assertAllClose((2, 72, 72, 2), out.shape) 41 | 42 | if __name__ == "__main__": 43 | tf.test.main() 44 | -------------------------------------------------------------------------------- /tests/dilatedcontext_test.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import, print_function 2 | import tensorflow as tf 3 | 4 | from niftynet.layer.dilatedcontext import DilatedTensor 5 | from tests.niftynet_testcase import NiftyNetTestCase 6 | 7 | 8 | class BNTest(NiftyNetTestCase): 9 | def get_2d_input(self): 10 | input_shape = (2, 16, 16, 8) 11 | x = tf.ones(input_shape) 12 | return x 13 | 14 | def get_3d_input(self): 15 | input_shape = (2, 16, 16, 16, 8) 16 | x = tf.ones(input_shape) 17 | return x 18 | 19 | def test_2d_dilating_shape(self): 20 | x = self.get_2d_input() 21 | with DilatedTensor(x, 4) as dilated: 22 | intermediate = dilated.tensor 23 | x = dilated.tensor 24 | 25 | with self.cached_session() as sess: 26 | out = sess.run(x) 27 | out_dilated = sess.run(intermediate) 28 | self.assertAllClose((2, 16, 16, 8), out.shape) 29 | self.assertAllClose((32, 4, 4, 8), out_dilated.shape) 30 | 31 | def test_3d_dilating_shape(self): 32 | x = self.get_3d_input() 33 | with DilatedTensor(x, 4) as dilated: 34 | intermediate = dilated.tensor 35 | x = dilated.tensor 36 | 37 | with self.cached_session() as sess: 38 | out = sess.run(x) 39 | out_dilated = sess.run(intermediate) 40 | self.assertAllClose((2, 16, 16, 16, 8), out.shape) 41 | self.assertAllClose((128, 4, 4, 4, 8), out_dilated.shape) 42 | 43 | 44 | if __name__ == "__main__": 45 | tf.test.main() 46 | -------------------------------------------------------------------------------- /tests/download_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import absolute_import 3 | from __future__ import division 4 | from __future__ import print_function 5 | 6 | import os 7 | 8 | import tensorflow as tf 9 | 10 | from niftynet.utilities.download import download 11 | from niftynet.utilities.niftynet_global_config import NiftyNetGlobalConfig 12 | from tests.niftynet_testcase import NiftyNetTestCase 13 | 14 | MODEL_HOME = NiftyNetGlobalConfig().get_niftynet_home_folder() 15 | 16 | TEST_CASE_1 = 'dense_vnet_abdominal_ct_model_zoo' 17 | TEST_CASE_1_TARGET = os.path.join( 18 | MODEL_HOME, 'models', 'dense_vnet_abdominal_ct') 19 | TEST_CASE_2 = 'default' 20 | TEST_CASE_2_TARGET = os.path.join(MODEL_HOME, 'examples', TEST_CASE_2) 21 | TEST_CASE_3 = 'default_multimodal' 22 | TEST_CASE_3_TARGET = os.path.join(MODEL_HOME, 'examples', TEST_CASE_3) 23 | 24 | TEST_WRONG_ID = '42' 25 | 26 | 27 | class NetDownloadTest(NiftyNetTestCase): 28 | def test_download(self): 29 | self.assertTrue(download(TEST_CASE_1, False)) 30 | self.assertTrue(os.path.isdir(TEST_CASE_1_TARGET)) 31 | 32 | if os.path.isdir(TEST_CASE_1_TARGET): 33 | print('skipping tests: %s folder exists' % TEST_CASE_1_TARGET) 34 | else: 35 | self.assertTrue(download(TEST_CASE_1, True)) 36 | self.assertTrue(os.path.isdir(TEST_CASE_1_TARGET)) 37 | 38 | def test_wrong_ids(self): 39 | self.assertFalse(download([], False)) 40 | self.assertFalse(download((), False)) 41 | self.assertFalse(download(None, False)) 42 | self.assertFalse(download([], True)) 43 | self.assertFalse(download((), True)) 44 | self.assertFalse(download(None, True)) 45 | self.assertFalse(download(TEST_WRONG_ID, True)) 46 | self.assertFalse(download(TEST_WRONG_ID, False)) 47 | 48 | def test_multiple_ids(self): 49 | self.assertTrue( 50 | download([TEST_CASE_1, TEST_CASE_2, TEST_CASE_3], False)) 51 | self.assertTrue(os.path.isdir(TEST_CASE_1_TARGET)) 52 | self.assertTrue(os.path.isdir(TEST_CASE_2_TARGET)) 53 | self.assertTrue(os.path.isdir(TEST_CASE_3_TARGET)) 54 | 55 | 56 | if __name__ == "__main__": 57 | tf.test.main() 58 | -------------------------------------------------------------------------------- /tests/get_gpu_index.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import absolute_import, print_function 3 | 4 | from subprocess import Popen, PIPE 5 | 6 | bash_string = "nvidia-smi --query-gpu=memory.free --format=csv" 7 | p1 = Popen(bash_string.split(), stdout=PIPE) 8 | bash_string = "tail -n 2" 9 | p2 = Popen(bash_string.split(), stdin=p1.stdout, stdout=PIPE) 10 | p3 = Popen(['sed', 's: MiB::'], stdin=p2.stdout, stdout=PIPE) 11 | output, error = p3.communicate() 12 | 13 | free_memory = [float(x) for x in output.decode('utf-8').split('\n')[:-1]] 14 | if free_memory[1] > free_memory[0]: 15 | print('1') 16 | else: 17 | print('0') 18 | -------------------------------------------------------------------------------- /tests/handler_console_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import absolute_import, print_function 3 | 4 | import tensorflow as tf 5 | from tests.application_driver_test import get_initialised_driver 6 | from niftynet.engine.application_iteration import IterationMessage 7 | from niftynet.engine.signal import SESS_STARTED, ITER_FINISHED 8 | from tests.niftynet_testcase import NiftyNetTestCase 9 | 10 | 11 | class EventConsoleTest(NiftyNetTestCase): 12 | def test_init(self): 13 | ITER_FINISHED.connect(self.iteration_listener) 14 | 15 | app_driver = get_initialised_driver() 16 | app_driver.load_event_handlers( 17 | ['niftynet.engine.handler_model.ModelRestorer', 18 | 'niftynet.engine.handler_console.ConsoleLogger', 19 | 'niftynet.engine.handler_sampler.SamplerThreading']) 20 | graph = app_driver.create_graph(app_driver.app, 1, True) 21 | with self.cached_session(graph=graph) as sess: 22 | SESS_STARTED.send(app_driver.app, iter_msg=None) 23 | msg = IterationMessage() 24 | msg.current_iter = 1 25 | app_driver.loop(app_driver.app, [msg]) 26 | app_driver.app.stop() 27 | 28 | ITER_FINISHED.disconnect(self.iteration_listener) 29 | 30 | def iteration_listener(self, sender, **msg): 31 | msg = msg['iter_msg'] 32 | self.assertRegexpMatches(msg.to_console_string(), 'mean') 33 | self.assertRegexpMatches(msg.to_console_string(), 'var') 34 | 35 | 36 | if __name__ == "__main__": 37 | tf.test.main() 38 | -------------------------------------------------------------------------------- /tests/handler_network_output_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import absolute_import, print_function 3 | 4 | import tensorflow as tf 5 | 6 | from niftynet.engine.application_iteration import IterationMessageGenerator 7 | from niftynet.engine.application_variables import NETWORK_OUTPUT 8 | from tests.application_driver_test import get_initialised_driver 9 | from niftynet.engine.signal import SESS_STARTED 10 | from tests.niftynet_testcase import NiftyNetTestCase 11 | 12 | 13 | def set_iteration_update(msg): 14 | msg.ops_to_run[NETWORK_OUTPUT] = \ 15 | tf.get_default_graph().get_tensor_by_name("G/conv_bn_selu/conv_/w:0") 16 | 17 | 18 | class EventConsoleTest(NiftyNetTestCase): 19 | def create_interpreter(self): 20 | def mini_interpreter(np_array): 21 | self.assertEqual(np_array.shape, (10, 1, 20)) 22 | return False 23 | 24 | return mini_interpreter 25 | 26 | def test_init(self): 27 | app_driver = get_initialised_driver() 28 | test_graph = app_driver.create_graph(app_driver.app, 1, True) 29 | 30 | app_driver.app.set_iteration_update = set_iteration_update 31 | app_driver.app.interpret_output = self.create_interpreter() 32 | 33 | app_driver.load_event_handlers( 34 | ['niftynet.engine.handler_model.ModelRestorer', 35 | 'niftynet.engine.handler_network_output.OutputInterpreter', 36 | 'niftynet.engine.handler_sampler.SamplerThreading']) 37 | with self.cached_session(graph=test_graph) as sess: 38 | SESS_STARTED.send(app_driver.app, iter_msg=None) 39 | 40 | iterator = IterationMessageGenerator(is_training_action=False) 41 | app_driver.loop(app_driver.app, iterator()) 42 | app_driver.app.stop() 43 | 44 | 45 | if __name__ == "__main__": 46 | tf.test.main() 47 | -------------------------------------------------------------------------------- /tests/handler_performance_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import absolute_import, print_function 3 | 4 | import tensorflow as tf 5 | import numpy as np 6 | 7 | from tests.application_driver_test import get_initialised_driver 8 | from niftynet.engine.application_iteration import IterationMessage 9 | from niftynet.engine.signal import SESS_STARTED, ITER_FINISHED, VALID 10 | from tests.niftynet_testcase import NiftyNetTestCase 11 | 12 | 13 | class PerformanceLoggerTest(NiftyNetTestCase): 14 | def test_init(self): 15 | ITER_FINISHED.connect(self.iteration_listener) 16 | app_driver = get_initialised_driver() 17 | app_driver.load_event_handlers( 18 | ['niftynet.engine.handler_model.ModelRestorer', 19 | 'niftynet.engine.handler_console.ConsoleLogger', 20 | 'niftynet.engine.handler_sampler.SamplerThreading', 21 | 'niftynet.engine.handler_performance.PerformanceLogger']) 22 | graph = app_driver.create_graph(app_driver.app, 1, True) 23 | with self.cached_session(graph=graph) as sess: 24 | for i in range(110): 25 | SESS_STARTED.send(app_driver.app, iter_msg=None) 26 | msg = IterationMessage() 27 | msg._phase = VALID 28 | msg.current_iter = i 29 | app_driver.loop(app_driver.app, [msg]) 30 | app_driver.app.stop() 31 | ITER_FINISHED.disconnect(self.iteration_listener) 32 | 33 | def iteration_listener(self, sender, **msg): 34 | msg = msg['iter_msg'] 35 | self.assertRegexpMatches(msg.to_console_string(), '.*total_loss.*') 36 | if msg.current_iter > 1: 37 | self.assertTrue(isinstance(sender.performance_history, list)) 38 | self.assertTrue(len(sender.performance_history) <= sender.patience) 39 | self.assertTrue(all([isinstance(p, np.float32) for p in sender.performance_history])) 40 | 41 | 42 | if __name__ == "__main__": 43 | tf.test.main() 44 | -------------------------------------------------------------------------------- /tests/holistic_net_test.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import, print_function 2 | 3 | import unittest 4 | 5 | import os 6 | import tensorflow as tf 7 | from tensorflow.contrib.layers.python.layers import regularizers 8 | 9 | from niftynet.network.holistic_net import HolisticNet 10 | from tests.niftynet_testcase import NiftyNetTestCase 11 | 12 | 13 | class HolisticNetTest(NiftyNetTestCase): 14 | def test_3d_reg_shape(self): 15 | input_shape = (2, 20, 20, 20, 1) 16 | x = tf.ones(input_shape) 17 | 18 | holistic_net_instance = HolisticNet( 19 | num_classes=3, 20 | w_regularizer=regularizers.l2_regularizer(0.5), 21 | b_regularizer=regularizers.l2_regularizer(0.5)) 22 | out = holistic_net_instance(x, is_training=False) 23 | # print(tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)) 24 | 25 | with self.cached_session() as sess: 26 | sess.run(tf.global_variables_initializer()) 27 | out = sess.run(out) 28 | self.assertAllClose((2, 20, 20, 20, 3), out.shape) 29 | 30 | def test_2d_reg_shape(self): 31 | input_shape = (2, 20, 20, 1) 32 | x = tf.ones(input_shape) 33 | 34 | holistic_net_instance = HolisticNet( 35 | num_classes=3, 36 | w_regularizer=regularizers.l2_regularizer(0.5), 37 | b_regularizer=regularizers.l2_regularizer(0.5)) 38 | out = holistic_net_instance(x, is_training=False) 39 | # print(tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)) 40 | 41 | with self.cached_session() as sess: 42 | sess.run(tf.global_variables_initializer()) 43 | out = sess.run(out) 44 | self.assertAllClose((2, 20, 20, 3), out.shape) 45 | 46 | 47 | 48 | if __name__ == "__main__": 49 | tf.test.main() 50 | -------------------------------------------------------------------------------- /tests/image_loader_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import absolute_import, print_function 3 | 4 | import os 5 | import numpy as np 6 | import tensorflow as tf 7 | import niftynet.io.image_loader as image_loader 8 | from tests.niftynet_testcase import NiftyNetTestCase 9 | 10 | CASE_NIBABEL_3D = 'testing_data/FLAIR_1023.nii.gz' 11 | CASE_LOGO_2D = 'niftynet-logo.png' 12 | 13 | class ImageLoaderTest(NiftyNetTestCase): 14 | def test_nibabel_3d(self): 15 | data = image_loader.load_image_obj(CASE_NIBABEL_3D).get_data() 16 | self.assertAllClose(data.shape, (256, 168, 256)) 17 | 18 | def load_2d_image(self, loader=None): 19 | data = image_loader.load_image_obj(CASE_LOGO_2D, loader=loader).get_data() 20 | self.assertAllClose(data.shape, (400, 677, 1, 1, 4)) 21 | 22 | def test_convert_bool(self): 23 | boolarr=np.ones((256,256,256),np.bool) 24 | img=image_loader.image2nibabel(boolarr) 25 | 26 | def test_2d_loaders(self): 27 | with self.assertRaisesRegexp(ValueError, ''): 28 | self.load_2d_image('test') 29 | self.load_2d_image() 30 | for _loader in image_loader.AVAILABLE_LOADERS.keys(): 31 | print('testing {}'.format(_loader)) 32 | if _loader == 'nibabel': 33 | continue # skip nibabel for 2d image 34 | if _loader == 'dummy': 35 | continue # skip the toy example 36 | self.load_2d_image(_loader) 37 | 38 | def test_all_data(self): 39 | folder = 'testing_data' 40 | all_files = [ 41 | os.path.join(folder, f) 42 | for f in os.listdir(folder) 43 | if os.path.isfile(os.path.join(folder, f))] 44 | 45 | for f in all_files: 46 | if f.endswith('nii.gz'): 47 | loaded_shape = image_loader.load_image_obj(f).get_data().shape 48 | print(loaded_shape) 49 | self.assertGreaterEqual(5, len(loaded_shape)) 50 | else: 51 | with self.assertRaisesRegexp(ValueError, ''): 52 | image_loader.load_image_obj(f) 53 | 54 | 55 | if __name__ == "__main__": 56 | tf.test.main() 57 | -------------------------------------------------------------------------------- /tests/interventional_affine_net_test.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import, print_function 2 | 3 | import tensorflow as tf 4 | 5 | from niftynet.network.toynet import ToyNet 6 | from niftynet.network.interventional_affine_net import INetAffine 7 | from tests.niftynet_testcase import NiftyNetTestCase 8 | 9 | 10 | class INetAffineTest(NiftyNetTestCase): 11 | def test_3d_shape(self): 12 | input_shape = (2, 32, 32, 32, 1) 13 | x = tf.ones(input_shape) 14 | 15 | affinenet_instance = INetAffine() 16 | out = affinenet_instance(x, x, is_training=True) 17 | print(affinenet_instance) 18 | 19 | with self.cached_session() as sess: 20 | sess.run(tf.global_variables_initializer()) 21 | out = sess.run(out) 22 | self.assertAllClose((2, 32, 32, 32, 3), out.shape) 23 | 24 | def test_2d_shape(self): 25 | input_shape = (2, 32, 32, 1) 26 | x = tf.ones(input_shape) 27 | 28 | affinenet_instance = INetAffine() 29 | out = affinenet_instance(x, x, is_training=True) 30 | print(affinenet_instance) 31 | 32 | with self.cached_session() as sess: 33 | sess.run(tf.global_variables_initializer()) 34 | out = sess.run(out) 35 | self.assertAllClose((2, 32, 32, 2), out.shape) 36 | 37 | 38 | if __name__ == "__main__": 39 | tf.test.main() 40 | -------------------------------------------------------------------------------- /tests/loss_classification_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import absolute_import, print_function 3 | 4 | import numpy as np 5 | import tensorflow as tf 6 | 7 | from niftynet.layer.loss_classification import LossFunction 8 | from tests.niftynet_testcase import NiftyNetTestCase 9 | 10 | 11 | class CrossEntropyTests(NiftyNetTestCase): 12 | def test_cross_entropy_value(self): 13 | # test value is -0.5 * [1 * log(e / (1+e)) + 1 * log(e^2 / (e^2 + 1))] 14 | with self.cached_session(): 15 | predicted = tf.constant( 16 | [[0, 1], [2, 0]], 17 | dtype=tf.float32, name='predicted') 18 | labels = tf.constant([1, 0], dtype=tf.int64, name='labels') 19 | test_loss_func = LossFunction(2, loss_type='CrossEntropy') 20 | computed_cross_entropy = test_loss_func(predicted, labels) 21 | self.assertAlmostEqual( 22 | computed_cross_entropy.eval(), 23 | -.5 * (np.log(np.e / (1 + np.e)) + np.log( 24 | np.e ** 2 / (1 + np.e ** 2)))) 25 | 26 | 27 | class LossFunctionErrorsTest(NiftyNetTestCase): 28 | """ 29 | These tests check that a ValueError is called 30 | for non-existent loss functions. 31 | They also check that suggestions are returned 32 | if the name is close to a real one. 33 | """ 34 | 35 | def test_value_error_for_bad_loss_function(self): 36 | with self.cached_session(): 37 | with self.assertRaises(ValueError): 38 | LossFunction(0, loss_type='wrong answer') 39 | 40 | # Note: sensitive to precise wording of ValueError message. 41 | def test_suggestion_for_dice_typo(self): 42 | with self.cached_session(): 43 | with self.assertRaisesRegexp(ValueError, 'CrossEntropy'): 44 | LossFunction(0, loss_type='cross_entropy') 45 | 46 | 47 | if __name__ == '__main__': 48 | tf.test.main() 49 | -------------------------------------------------------------------------------- /tests/niftynet_testcase.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | 3 | # This UGLY solution is done to bypass the issue 4 | # outlined in the NiftyNet issue #381 and Tensorflow 5 | # issue #29439 6 | # 7 | # https://github.com/NifTK/NiftyNet/issues/381 8 | # https://github.com/tensorflow/tensorflow/issues/29439 9 | 10 | try: 11 | delattr(tf.test.TestCase,'test_session') 12 | except AttributeError: 13 | pass 14 | 15 | 16 | class NiftyNetTestCase(tf.test.TestCase): 17 | pass -------------------------------------------------------------------------------- /tests/post_processing_test.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import, print_function 2 | 3 | import tensorflow as tf 4 | 5 | from niftynet.layer.post_processing import PostProcessingLayer 6 | from tests.niftynet_testcase import NiftyNetTestCase 7 | 8 | class PostProcessingTest(NiftyNetTestCase): 9 | def get_3d_input(self): 10 | input_shape = (2, 16, 16, 16, 8) 11 | x = tf.ones(input_shape) 12 | return x 13 | 14 | def get_2d_input(self): 15 | input_shape = (2, 16, 16, 8) 16 | x = tf.ones(input_shape) 17 | return x 18 | 19 | def test_3d_shape(self): 20 | x = self.get_3d_input() 21 | post_process_layer = PostProcessingLayer("SOFTMAX") 22 | print(post_process_layer) 23 | out_post = post_process_layer(x) 24 | print(post_process_layer) 25 | 26 | with self.cached_session() as sess: 27 | out = sess.run(out_post) 28 | x_shape = tuple(x.shape.as_list()) 29 | self.assertAllClose(x_shape, out.shape) 30 | 31 | def test_2d_shape(self): 32 | x = self.get_2d_input() 33 | post_process_layer = PostProcessingLayer("IDENTITY") 34 | out_post = post_process_layer(x) 35 | print(post_process_layer) 36 | 37 | with self.cached_session() as sess: 38 | out = sess.run(out_post) 39 | x_shape = tuple(x.shape.as_list()) 40 | self.assertAllClose(x_shape, out.shape) 41 | 42 | def test_3d_argmax_shape(self): 43 | x = self.get_3d_input() 44 | post_process_layer = PostProcessingLayer("ARGMAX") 45 | out_post = post_process_layer(x) 46 | print(post_process_layer) 47 | 48 | with self.cached_session() as sess: 49 | out = sess.run(out_post) 50 | x_shape = tuple(x.shape.as_list()[:-1]) 51 | self.assertAllClose(x_shape + (1,), out.shape) 52 | 53 | 54 | if __name__ == "__main__": 55 | tf.test.main() 56 | -------------------------------------------------------------------------------- /tests/rand_rotation_test.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import, print_function 2 | 3 | import numpy as np 4 | import tensorflow as tf 5 | 6 | from niftynet.layer.rand_rotation import RandomRotationLayer 7 | from tests.niftynet_testcase import NiftyNetTestCase 8 | 9 | 10 | class RandRotationTest(NiftyNetTestCase): 11 | def get_4d_input(self): 12 | input_4d = {'testdata': np.ones((16, 16, 16, 8))} 13 | interp_order = {'testdata': (3,) * 8} 14 | return input_4d, interp_order 15 | 16 | def get_5d_input(self): 17 | input_5d = {'testdata': np.ones((32, 32, 32, 8, 1))} 18 | interp_order = {'testdata': (3,)} 19 | return input_5d, interp_order 20 | 21 | def test_4d_shape(self): 22 | x, interp_orders = self.get_4d_input() 23 | rand_rotation_layer = RandomRotationLayer() 24 | rand_rotation_layer.init_uniform_angle((-10.0, 10.0)) 25 | rand_rotation_layer.randomise() 26 | out = rand_rotation_layer(x, interp_orders) 27 | 28 | def test_5d_shape(self): 29 | x, interp_orders = self.get_5d_input() 30 | rand_rotation_layer = RandomRotationLayer() 31 | rand_rotation_layer.init_uniform_angle((-10.0, 10.0)) 32 | rand_rotation_layer.randomise() 33 | out = rand_rotation_layer(x, interp_orders) 34 | 35 | 36 | if __name__ == "__main__": 37 | tf.test.main() 38 | -------------------------------------------------------------------------------- /tests/rand_spatial_scaling_test.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import, print_function 2 | 3 | import numpy as np 4 | import tensorflow as tf 5 | 6 | from niftynet.layer.rand_spatial_scaling import RandomSpatialScalingLayer 7 | from tests.niftynet_testcase import NiftyNetTestCase 8 | 9 | 10 | class RandRotationTest(NiftyNetTestCase): 11 | def get_4d_input(self): 12 | input_4d = {'testdata': np.ones((16, 16, 16, 8))} 13 | interp_order = {'testdata': (3,) * 8} 14 | return input_4d, interp_order 15 | 16 | def get_5d_input(self): 17 | input_5d = {'testdata': np.ones((32, 32, 32, 8, 1))} 18 | interp_order = {'testdata': (1,)} 19 | return input_5d, interp_order 20 | 21 | def test_4d_shape(self): 22 | x, interp = self.get_4d_input() 23 | rand_layer = RandomSpatialScalingLayer(min_percentage=-10.0, 24 | max_percentage=10.0) 25 | rand_layer.randomise() 26 | out = rand_layer(x, interp) 27 | 28 | def test_5d_shape(self): 29 | x, interp = self.get_5d_input() 30 | rand_layer = RandomSpatialScalingLayer(min_percentage=-10.0, 31 | max_percentage=10.0) 32 | rand_layer.randomise() 33 | out = rand_layer(x, interp) 34 | 35 | 36 | if __name__ == "__main__": 37 | tf.test.main() 38 | -------------------------------------------------------------------------------- /tests/segmentation_evaluator_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import absolute_import, print_function 3 | 4 | import numpy as np 5 | import tensorflow as tf 6 | 7 | from niftynet.evaluation.segmentation_evaluator import SegmentationEvaluator 8 | from niftynet.io.misc_io import set_logger 9 | from tests.niftynet_testcase import NiftyNetTestCase 10 | 11 | class SegmentationEvaluatorTest(NiftyNetTestCase): 12 | def test_basic(self): 13 | class NS(object): 14 | def __init__(self, dict): 15 | self.__dict__.update(dict) 16 | segmentation_param=NS({'evaluation_units':'foreground,cc', 17 | 'num_classes':2, 18 | 'output_prob':False}) 19 | eval_param=NS({'evaluations':'Dice'}) 20 | mask = np.reshape(np.abs(np.linspace(0.,2.,64)-1)>.8,[4,4,4,1,1]) 21 | data_dict = {'label':mask,'inferred':mask} 22 | interp_orders = {'label':0,'inferred':0} 23 | image_folder = '.' 24 | e = SegmentationEvaluator(None, segmentation_param, eval_param) 25 | 26 | def generator(): 27 | yield ('test',data_dict,interp_orders) 28 | 29 | result_dict = e.evaluate_from_generator(generator()) 30 | self.assertIn(('subject_id', 'label'), result_dict) 31 | self.assertIn(('subject_id', 'cc_id'), result_dict) 32 | self.assertEqual(tuple(result_dict[('subject_id', 'label')].index.names), 33 | ('subject_id', 'label')) 34 | self.assertEqual(tuple(result_dict[('subject_id', 'cc_id')].index.names), 35 | ('subject_id', 'cc_id')) 36 | print(result_dict[('subject_id', 'cc_id')].to_dict('index')) 37 | self.assertEqual(result_dict[('subject_id', 'label')].to_dict('index'), 38 | {('test', 1): {'dice': 1.}}) 39 | self.assertEqual(result_dict[('subject_id', 'cc_id')].to_dict('index'), 40 | {('test', 'r1_s1'): {'dice': 1.}, 41 | ('test', 'r2_s2'): {'dice': 1.}}) 42 | 43 | 44 | if __name__ == "__main__": 45 | set_logger() 46 | # _run_test_application() 47 | tf.test.main() 48 | -------------------------------------------------------------------------------- /tests/simple_gan_test.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import, print_function 2 | 3 | import unittest 4 | 5 | import os 6 | import tensorflow as tf 7 | from tensorflow.contrib.layers.python.layers import regularizers 8 | 9 | from niftynet.network.simple_gan import SimpleGAN 10 | from tests.niftynet_testcase import NiftyNetTestCase 11 | 12 | class SimpleGANTest(NiftyNetTestCase): 13 | def test_3d_reg_shape(self): 14 | input_shape = (2, 32, 32, 32, 1) 15 | noise_shape = (2, 512) 16 | x = tf.ones(input_shape) 17 | r = tf.ones(noise_shape) 18 | 19 | simple_gan_instance = SimpleGAN() 20 | out = simple_gan_instance(r, x, is_training=True) 21 | 22 | with self.cached_session() as sess: 23 | sess.run(tf.global_variables_initializer()) 24 | out = sess.run(out) 25 | self.assertAllClose(input_shape, out[0].shape) 26 | self.assertAllClose((2, 1), out[1].shape) 27 | self.assertAllClose((2, 1), out[2].shape) 28 | 29 | def test_2d_reg_shape(self): 30 | input_shape = (2, 64, 64, 1) 31 | noise_shape = (2, 512) 32 | x = tf.ones(input_shape) 33 | r = tf.ones(noise_shape) 34 | 35 | simple_gan_instance = SimpleGAN() 36 | out = simple_gan_instance(r, x, is_training=True) 37 | 38 | with self.cached_session() as sess: 39 | sess.run(tf.global_variables_initializer()) 40 | out = sess.run(out) 41 | self.assertAllClose(input_shape, out[0].shape) 42 | self.assertAllClose((2, 1), out[1].shape) 43 | self.assertAllClose((2, 1), out[2].shape) 44 | 45 | 46 | 47 | if __name__ == "__main__": 48 | tf.test.main() 49 | -------------------------------------------------------------------------------- /tests/toynet_test.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import, print_function 2 | 3 | import tensorflow as tf 4 | 5 | from niftynet.network.toynet import ToyNet 6 | from tests.niftynet_testcase import NiftyNetTestCase 7 | 8 | class ToyNetTest(NiftyNetTestCase): 9 | def test_3d_shape(self): 10 | input_shape = (2, 32, 32, 32, 1) 11 | x = tf.ones(input_shape) 12 | 13 | toynet_instance = ToyNet(num_classes=160) 14 | out = toynet_instance(x, is_training=True) 15 | 16 | with self.cached_session() as sess: 17 | sess.run(tf.global_variables_initializer()) 18 | out = sess.run(out) 19 | self.assertAllClose((2, 32, 32, 32, 160), out.shape) 20 | 21 | def test_2d_shape(self): 22 | input_shape = (2, 32, 32, 1) 23 | x = tf.ones(input_shape) 24 | 25 | toynet_instance = ToyNet(num_classes=160) 26 | out = toynet_instance(x, is_training=True) 27 | 28 | with self.cached_session() as sess: 29 | sess.run(tf.global_variables_initializer()) 30 | out = sess.run(out) 31 | self.assertAllClose((2, 32, 32, 160), out.shape) 32 | 33 | 34 | if __name__ == "__main__": 35 | tf.test.main() 36 | -------------------------------------------------------------------------------- /tests/unet_2d_test.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import, print_function 2 | 3 | import os 4 | import unittest 5 | 6 | import tensorflow as tf 7 | from tensorflow.contrib.layers.python.layers import regularizers 8 | 9 | from niftynet.network.unet_2d import UNet2D 10 | from tests.niftynet_testcase import NiftyNetTestCase 11 | 12 | @unittest.skipIf(os.environ.get('QUICKTEST', "").lower() == "true", 13 | 'Skipping slow tests') 14 | class UNet3DTest(NiftyNetTestCase): 15 | def test_2d_shape(self): 16 | #input_shape = (2, 572, 572, 3) 17 | input_shape = (2, 180, 180, 3) 18 | x = tf.ones(input_shape) 19 | 20 | unet_instance = UNet2D(num_classes=2) 21 | out = unet_instance(x, is_training=True) 22 | print(unet_instance.num_trainable_params()) 23 | 24 | with self.cached_session() as sess: 25 | sess.run(tf.global_variables_initializer()) 26 | out = sess.run(out) 27 | #self.assertAllClose((2, 388, 388, 2), out.shape) 28 | self.assertAllClose((2, 4, 4, 2), out.shape) 29 | 30 | def test_2d_reg_shape(self): 31 | #input_shape = (2, 572, 572, 5) 32 | input_shape = (2, 180, 180, 5) 33 | x = tf.ones(input_shape) 34 | 35 | unet_instance = UNet2D(num_classes=2, 36 | w_regularizer=regularizers.l2_regularizer(0.4)) 37 | out = unet_instance(x, is_training=True) 38 | print(unet_instance.num_trainable_params()) 39 | 40 | with self.cached_session() as sess: 41 | sess.run(tf.global_variables_initializer()) 42 | out = sess.run(out) 43 | #self.assertAllClose((2, 388, 388, 2), out.shape) 44 | self.assertAllClose((2, 4, 4, 2), out.shape) 45 | 46 | 47 | if __name__ == "__main__": 48 | tf.test.main() 49 | -------------------------------------------------------------------------------- /tests/user_parameters_default_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import absolute_import, print_function 3 | 4 | import argparse 5 | 6 | import tensorflow as tf 7 | 8 | from niftynet.utilities.user_parameters_default import * 9 | from tests.niftynet_testcase import NiftyNetTestCase 10 | 11 | class TestUserParameters(NiftyNetTestCase): 12 | def test_list_all(self): 13 | test_parser = argparse.ArgumentParser(conflict_handler='resolve') 14 | test_parser = add_application_args(test_parser) 15 | test_parser = add_network_args(test_parser) 16 | test_parser = add_training_args(test_parser) 17 | test_parser = add_input_data_args(test_parser) 18 | test_parser = add_inference_args(test_parser) 19 | 20 | for opt in test_parser._actions: 21 | print(opt_to_string(opt)) 22 | 23 | 24 | def opt_to_string(opt): 25 | summary = 'opt: [{}]\n'.format(opt.dest) 26 | summary += '---- type: {}\n'.format(opt.type) 27 | summary += '---- default: {}\n'.format(opt.default) 28 | summary += '---- description: {}\n'.format(opt.help) 29 | return summary 30 | 31 | 32 | if __name__ == "__main__": 33 | tf.test.main() 34 | -------------------------------------------------------------------------------- /tests/user_parameters_regex_test.py: -------------------------------------------------------------------------------- 1 | from __future__ import unicode_literals 2 | 3 | import re 4 | 5 | import tensorflow as tf 6 | 7 | from niftynet.utilities.user_parameters_regex import STATEMENT 8 | from tests.niftynet_testcase import NiftyNetTestCase 9 | 10 | class UserParameterRegexTest(NiftyNetTestCase): 11 | def run_match(self, string_to_match, expected_output): 12 | regex = re.compile(STATEMENT) 13 | matched_str = regex.match(string_to_match) 14 | if matched_str: 15 | filtered_groups = list(filter(None, matched_str.groups())) 16 | if filtered_groups: 17 | values = [v.strip() for v in filtered_groups[0].split(',')] 18 | self.assertEqual(values, expected_output) 19 | else: 20 | self.assertEqual(expected_output, False) 21 | 22 | def test_cases(self): 23 | self.run_match('c:\program files', [u'c:\\program files']) 24 | self.run_match('2.0, ( 6.0, 9.0', False) 25 | self.run_match('{ 32.0, 32.0}', [u'32.0', u'32.0']) 26 | self.run_match('a, c, b, f, d, e', [u'a', u'c', u'b', u'f', u'd', u'e']) 27 | self.run_match('(), ()', False) 28 | self.run_match('{), (}', False) 29 | self.run_match('(),', False) 30 | self.run_match('()', False) 31 | self.run_match('{}', False) 32 | self.run_match('32, (32),', False) 33 | self.run_match('32, (),', False) 34 | self.run_match('32', [u'32']) 35 | self.run_match('({)', False) 36 | self.run_match('(()', False) 37 | self.run_match('', False) 38 | self.run_match('32, 32', [u'32', u'32']) 39 | self.run_match('32,', False) 40 | self.run_match('-32', [u'-32']) 41 | self.run_match('-32.0, a', [u'-32.0', 'a']) 42 | self.run_match('-a, 32.0', [u'-a', '32.0']) 43 | self.run_match('(-32,a)', [u'-32', u'a']) 44 | self.run_match('-32.0', [u'-32.0']) 45 | self.run_match('(-a)', [u'-a']) 46 | self.run_match('(-32.0, 10.0, 2.99987, 5.6, 3.5, 5.6)', 47 | [u'-32.0', u'10.0', u'2.99987', u'5.6', u'3.5', u'5.6']) 48 | 49 | 50 | if __name__ == "__main__": 51 | tf.test.main() 52 | -------------------------------------------------------------------------------- /tests/util_import_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import tensorflow as tf 3 | 4 | from niftynet.utilities.util_import import require_module 5 | from tests.niftynet_testcase import NiftyNetTestCase 6 | 7 | class OptionalPackageTest(NiftyNetTestCase): 8 | def test_installed(self): 9 | require_module('tensorflow') 10 | 11 | def test_installed_min_version(self): 12 | require_module('tensorflow', 1.0) 13 | 14 | def test_no_package(self): 15 | with self.assertRaisesRegexp(ImportError, ''): 16 | require_module('foobar_wrong_case', mandatory=True) 17 | 18 | def test_wrong_version(self): 19 | with self.assertRaisesRegexp(AssertionError, ''): 20 | require_module('tensorflow', 100, mandatory=True) 21 | 22 | def test_self_version(self): 23 | require_module('importlib') 24 | 25 | def test_no_version_info(self): 26 | require_module('importlib', 0) 27 | 28 | def test_no_input(self): 29 | with self.assertRaisesRegexp(ImportError, ''): 30 | require_module([], mandatory=True) 31 | with self.assertRaisesRegexp(ImportError, ''): 32 | require_module(None, mandatory=True) 33 | 34 | 35 | if __name__ == "__main__": 36 | tf.test.main() 37 | -------------------------------------------------------------------------------- /tests/versioning_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import absolute_import, print_function 3 | 4 | import tensorflow as tf 5 | 6 | from niftynet.utilities.versioning import check_pep_440 7 | from niftynet.utilities.versioning import get_niftynet_version_string 8 | from tests.niftynet_testcase import NiftyNetTestCase 9 | 10 | 11 | class VersioningTest(NiftyNetTestCase): 12 | def test_version(self): 13 | version_str = get_niftynet_version_string() 14 | expected_string = "NiftyNet version " 15 | self.assertEqual(version_str[:len(expected_string)], expected_string) 16 | 17 | check_pep_440() 18 | 19 | 20 | if __name__ == "__main__": 21 | tf.test.main() 22 | -------------------------------------------------------------------------------- /train_modality_classification.ini: -------------------------------------------------------------------------------- 1 | [image] 2 | path_to_search = /home/tom/data/BRATS_18_SPLITS/train 3 | filename_contains = 4 | filename_not_contains =seg 5 | spatial_window_size = (32, 32, 1) 6 | axcodes=(A, R, S) 7 | interp_order = 1 8 | 9 | [label] 10 | csv_data_file = ./modality_labels.csv 11 | to_ohe = False 12 | 13 | 14 | ############################## system configuration sections 15 | [SYSTEM] 16 | cuda_devices = "" 17 | num_threads = 2 18 | num_gpus = 1 19 | model_dir = ./models/model_highres3dnet 20 | 21 | [NETWORK] 22 | name = resnet 23 | activation_function = relu 24 | batch_size = 1 25 | decay = 0 26 | reg_type = L2 27 | 28 | # volume level preprocessing 29 | volume_padding_size = 21 30 | # histogram normalisation 31 | histogram_ref_file = ./example_volumes/monomodal_parcellation/standardisation_models.txt 32 | norm_type = percentile 33 | cutoff = (0.01, 0.99) 34 | normalisation = True 35 | whitening = True 36 | normalise_foreground_only=True 37 | foreground_type = otsu_plus 38 | multimod_foreground_type = and 39 | 40 | queue_length = 1 41 | window_sampling = resize 42 | 43 | [TRAINING] 44 | sample_per_volume = 32 45 | rotation_angle = (-10.0, 10.0) 46 | scaling_percentage = (-10.0, 10.0) 47 | lr = 0.0001 48 | loss_type = CrossEntropy 49 | starting_iter = 0 50 | save_every_n = 5 51 | max_iter = 6 52 | max_checkpoints = 20 53 | 54 | [INFERENCE] 55 | border = (5, 5, 5) 56 | #inference_iter = 10 57 | save_seg_dir = ./output/highres3dnet 58 | output_interp_order = 0 59 | spatial_window_size = (0, 0, 3) 60 | 61 | ############################ custom configuration sections 62 | [CLASSIFICATION] 63 | image = image 64 | label = label 65 | output_prob = False 66 | num_classes = 4 67 | label_normalisation = False 68 | --------------------------------------------------------------------------------