datamint 2.49.0__tar.gz → 2.50.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {datamint-2.49.0 → datamint-2.50.0}/PKG-INFO +1 -1
- {datamint-2.49.0 → datamint-2.50.0}/datamint/client_cmd_tools/datamint_download.py +15 -4
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/annotations/geometry.py +99 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/resource.py +36 -0
- datamint-2.50.0/datamint/utils/visualization.py +382 -0
- {datamint-2.49.0 → datamint-2.50.0}/pyproject.toml +1 -1
- datamint-2.49.0/datamint/utils/visualization.py +0 -159
- {datamint-2.49.0 → datamint-2.50.0}/README.md +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/__init__.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/__main__.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/_repr_utils.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/api/__init__.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/api/base_api.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/api/client.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/api/dto/__init__.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/api/dto/annotation_dto.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/api/dto/inference_prompts.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/api/dto/save_results_options.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/api/endpoints/__init__.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/api/endpoints/annotations_api.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/api/endpoints/annotationsets_api.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/api/endpoints/datasetsinfo_api.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/api/endpoints/deploy_model_api.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/api/endpoints/inference_api.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/api/endpoints/model_types.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/api/endpoints/models_api.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/api/endpoints/pod_logs_api.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/api/endpoints/projects_api.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/api/endpoints/resources_api.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/api/endpoints/users_api.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/api/endpoints/validation_studies_api.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/api/entity_base_api.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/client_cmd_tools/__init__.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/client_cmd_tools/datamint_config.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/client_cmd_tools/datamint_example.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/client_cmd_tools/datamint_import.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/client_cmd_tools/datamint_inference.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/client_cmd_tools/datamint_init.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/client_cmd_tools/datamint_train.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/client_cmd_tools/datamint_upload.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/configs.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/dataset/__init__.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/dataset/annotation_processor.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/dataset/base.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/dataset/factory.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/dataset/image_dataset.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/dataset/multiframe_dataset.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/dataset/sliced_dataset.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/dataset/sliced_video_dataset.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/dataset/split_result.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/dataset/video_dataset.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/dataset/volume_dataset.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/default_project.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/__init__.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/annotation_worklist.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/annotations/__init__.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/annotations/annotation.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/annotations/annotation_spec.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/annotations/base_geometry.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/annotations/base_segmentation.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/annotations/box_annotation.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/annotations/category_annotation.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/annotations/image_classification.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/annotations/image_segmentation.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/annotations/label_annotation.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/annotations/line_annotation.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/annotations/numeric_annotation.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/annotations/point_annotation.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/annotations/region_annotation.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/annotations/text_annotation.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/annotations/types.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/annotations/volume_segmentation.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/base_entity.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/buildlog.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/cache_manager.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/channel.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/datasetinfo.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/deployjob.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/inferencejob.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/pod.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/project.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/project_resource_split.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/resources/__init__.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/resources/dicom_resource.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/resources/image_resource.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/resources/nifti_resource.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/resources/video_resource.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/resources/volume_resource.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/sliced_resource.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/sliced_resource_base.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/sliced_video_resource.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/user.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/entities/validation_study.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/evaluate/__init__.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/evaluate/evaluator.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/evaluate/metrics/__init__.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/evaluate/metrics/classification.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/evaluate/metrics/detection.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/evaluate/metrics/segmentation.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/examples/__init__.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/examples/_common.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/examples/_download.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/examples/bccd_dataset.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/examples/busi_dataset.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/examples/example_projects.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/examples/fracatlas_dataset.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/examples/synapse_dataset.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/exceptions.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/importers/__init__.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/importers/_common.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/importers/_detect.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/importers/coco.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/importers/pascal_voc.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/importers/yolo.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/lightning/__init__.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/lightning/benchmark.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/lightning/datamodule.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/lightning/trainers/__init__.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/lightning/trainers/base_trainer.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/lightning/trainers/classification_trainer.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/lightning/trainers/detection_trainer.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/lightning/trainers/lightning_modules/__init__.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/lightning/trainers/lightning_modules/base.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/lightning/trainers/lightning_modules/classification_module.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/lightning/trainers/lightning_modules/detection_modules/__init__.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/lightning/trainers/lightning_modules/detection_modules/yolox_module.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/lightning/trainers/lightning_modules/segmentation_module.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/lightning/trainers/lightning_modules/segmentation_modules/__init__.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/lightning/trainers/lightning_modules/segmentation_modules/deeplabv3plus.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/lightning/trainers/lightning_modules/segmentation_modules/smp_module.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/lightning/trainers/lightning_modules/segmentation_modules/transunet.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/lightning/trainers/lightning_modules/segmentation_modules/unetpp.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/lightning/trainers/lightning_modules/segmentation_modules/unetrpp.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/lightning/trainers/seg2d_trainer.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/lightning/trainers/seg3d_trainer.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/lightning/trainers/segmentation_trainer.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/lightning/trainers/specialized/__init__.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/lightning/trainers/specialized/deeplabv3plus.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/lightning/trainers/specialized/efficientnetv2.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/lightning/trainers/specialized/nnunet/__init__.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/lightning/trainers/specialized/nnunet/_nnunet_trainer_bridge.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/lightning/trainers/specialized/nnunet/data_export.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/lightning/trainers/specialized/nnunet/data_import.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/lightning/trainers/specialized/nnunet/inference_model.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/lightning/trainers/specialized/nnunet/trainer.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/lightning/trainers/specialized/transunet.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/lightning/trainers/specialized/unetpp.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/lightning/trainers/specialized/unetrpp.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/lightning/trainers/specialized/yolox.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/lightning/trainers/vol_seg_trainer.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/logging.yaml +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/mlflow/__init__.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/mlflow/artifact/__init__.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/mlflow/artifact/datamint_artifacts_repo.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/mlflow/data/__init__.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/mlflow/data/datamint_dataset.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/mlflow/env_utils.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/mlflow/env_vars.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/mlflow/flavors/__init__.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/mlflow/flavors/annotation_specs.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/mlflow/flavors/datamint_flavor.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/mlflow/flavors/model.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/mlflow/flavors/model_loader.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/mlflow/flavors/model_parser.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/mlflow/flavors/prediction_modes.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/mlflow/flavors/prediction_router.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/mlflow/flavors/task_type.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/mlflow/flavors/validation.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/mlflow/lightning/callbacks/__init__.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/mlflow/lightning/callbacks/modelcheckpoint.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/mlflow/models/Dockerfile.template +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/mlflow/models/__init__.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/mlflow/models/datamint_model_store.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/mlflow/models/docker_build.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/mlflow/models/local_inference.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/mlflow/models/serve.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/mlflow/models/tags.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/mlflow/store_utils.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/mlflow/tracking/datamint_store.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/mlflow/tracking/default_experiment.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/mlflow/tracking/fluent.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/mlflow/tracking/offline_buffer.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/types.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/utils/annotation_agreement.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/utils/collection_utils.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/utils/date_utils.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/utils/env.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/utils/logging_utils.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/utils/nifti_utils.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/utils/torchmetrics.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/utils/uncertainty.py +0 -0
- {datamint-2.49.0 → datamint-2.50.0}/datamint/utils/urls.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: datamint
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.50.0
|
|
4
4
|
Summary: A library for interacting with the Datamint API, designed for efficient data management, processing and Deep Learning workflows.
|
|
5
5
|
Keywords: medical-imaging,dicom,nifti,pytorch,mlflow,lightning,datasets,annotation
|
|
6
6
|
Author: SonanceAI
|
|
@@ -24,8 +24,9 @@ def _build_parser(subparsers: argparse._SubParsersAction | None = None) -> argpa
|
|
|
24
24
|
'description': "Download and cache a Datamint project's dataset locally.",
|
|
25
25
|
'epilog': """
|
|
26
26
|
Examples:
|
|
27
|
-
datamint download
|
|
28
|
-
datamint download
|
|
27
|
+
datamint download MyProject # cache the dataset locally
|
|
28
|
+
datamint download MyProject -o ./my_data_folder # also create a browsable view
|
|
29
|
+
datamint download --project MyProject # same as the first, using the --project flag
|
|
29
30
|
|
|
30
31
|
More Documentation: https://sonanceai.github.io/datamint-python-api/command_line_tools.html
|
|
31
32
|
""",
|
|
@@ -35,8 +36,11 @@ More Documentation: https://sonanceai.github.io/datamint-python-api/command_line
|
|
|
35
36
|
parser = subparsers.add_parser('download', **kwargs)
|
|
36
37
|
else:
|
|
37
38
|
parser = argparse.ArgumentParser(**kwargs)
|
|
38
|
-
parser.add_argument('
|
|
39
|
+
parser.add_argument('project', nargs='?', metavar='PROJECT',
|
|
39
40
|
help='Name of the Datamint project to download.')
|
|
41
|
+
# --project option also works
|
|
42
|
+
parser.add_argument('--project', dest='project_flag', type=str, metavar='PROJECT',
|
|
43
|
+
help='Name of the Datamint project.')
|
|
40
44
|
parser.add_argument('-o', '--output', type=str, default=None,
|
|
41
45
|
help='Optional folder for a browsable view of the downloaded files '
|
|
42
46
|
'(symlinks into the SDK cache; requires symlink support).')
|
|
@@ -49,7 +53,14 @@ def _parse_args() -> argparse.Namespace:
|
|
|
49
53
|
parser = _build_parser()
|
|
50
54
|
import argcomplete
|
|
51
55
|
argcomplete.autocomplete(parser)
|
|
52
|
-
|
|
56
|
+
args = parser.parse_args()
|
|
57
|
+
|
|
58
|
+
if args.project is not None and args.project_flag is not None:
|
|
59
|
+
parser.error("Both positional project and --project flag provided. Use only one.")
|
|
60
|
+
args.project = args.project or args.project_flag
|
|
61
|
+
if args.project is None:
|
|
62
|
+
parser.error("Project name is required. Provide it as a positional argument or use --project flag.")
|
|
63
|
+
return args
|
|
53
64
|
|
|
54
65
|
|
|
55
66
|
def _export_view(resources, output_dir: Path) -> None:
|
|
@@ -10,6 +10,7 @@ from medimgkit import ViewPlane, dicom_utils, nifti_utils
|
|
|
10
10
|
from medimgkit.dicom_utils import get_slice_orientation
|
|
11
11
|
from nibabel.nifti1 import Nifti1Image
|
|
12
12
|
from pydantic import BaseModel, ConfigDict, field_validator
|
|
13
|
+
from typing_extensions import Self
|
|
13
14
|
|
|
14
15
|
CoordinateSystem: TypeAlias = Literal['pixel', 'patient']
|
|
15
16
|
Point3D: TypeAlias = tuple[int | float, int | float, int | float]
|
|
@@ -97,6 +98,31 @@ def _pixel_to_patient_point(
|
|
|
97
98
|
raise TypeError(f'Unsupported metadata type: {type(metadata)}')
|
|
98
99
|
|
|
99
100
|
|
|
101
|
+
def _patient_to_pixel_points(
|
|
102
|
+
points: Sequence[Point3D],
|
|
103
|
+
*,
|
|
104
|
+
slice_plane: ViewPlane | None = None,
|
|
105
|
+
metadata: pydicom.Dataset | Nifti1Image,
|
|
106
|
+
) -> np.ndarray:
|
|
107
|
+
"""(P, 3) patient points -> (P, 3) pixel points (x, y, slice index) on ``slice_plane``.
|
|
108
|
+
|
|
109
|
+
Inverts ``_pixel_to_patient_point``, so both directions follow the same convention.
|
|
110
|
+
"""
|
|
111
|
+
origin, right, down = (
|
|
112
|
+
np.asarray(_pixel_to_patient_point(p, frame_index=0, slice_plane=slice_plane, metadata=metadata), dtype=float)
|
|
113
|
+
for p in [(0, 0), (1, 0), (0, 1)]
|
|
114
|
+
)
|
|
115
|
+
dx = right - origin
|
|
116
|
+
dy = down - origin
|
|
117
|
+
try:
|
|
118
|
+
next_slice = _pixel_to_patient_point((0, 0), frame_index=1, slice_plane=slice_plane, metadata=metadata)
|
|
119
|
+
dz = np.asarray(next_slice, dtype=float) - origin
|
|
120
|
+
except Exception:
|
|
121
|
+
dz = np.cross(dx, dy) # single slice
|
|
122
|
+
inv = np.linalg.inv(np.column_stack([dx, dy, dz]))
|
|
123
|
+
return (np.asarray(points, dtype=float) - origin) @ inv.T
|
|
124
|
+
|
|
125
|
+
|
|
100
126
|
def _normalize_vector(vector: np.ndarray | list | tuple | None) -> Vector3D | None:
|
|
101
127
|
if vector is None:
|
|
102
128
|
return None
|
|
@@ -121,10 +147,40 @@ class Geometry(BaseModel):
|
|
|
121
147
|
model_config = ConfigDict(arbitrary_types_allowed=True, extra='ignore')
|
|
122
148
|
|
|
123
149
|
type: ClassVar[str]
|
|
150
|
+
points: tuple[Point3D, ...]
|
|
124
151
|
viewPlaneNormal: Vector3D | None = None
|
|
125
152
|
viewUp: Vector3D | None = None
|
|
126
153
|
coordinate_system: CoordinateSystem = 'patient'
|
|
127
154
|
|
|
155
|
+
def to_pixel_coordinates(self,
|
|
156
|
+
metadata: pydicom.Dataset | Nifti1Image | None = None,
|
|
157
|
+
slice_plane: ViewPlane | None = None) -> Self:
|
|
158
|
+
"""Copy with points as (x, y, slice index) on ``slice_plane`` (the native plane if None)."""
|
|
159
|
+
if self.coordinate_system == 'pixel':
|
|
160
|
+
return self.model_copy()
|
|
161
|
+
if metadata is None: # 2D images without geometry: patient and pixel are the same
|
|
162
|
+
return self.model_copy(update={'coordinate_system': 'pixel'})
|
|
163
|
+
points = _patient_to_pixel_points(self.points, slice_plane=slice_plane, metadata=metadata)
|
|
164
|
+
return self.model_copy(update={'points': tuple(_normalize_point(p) for p in points),
|
|
165
|
+
'coordinate_system': 'pixel'})
|
|
166
|
+
|
|
167
|
+
def to_patient_coordinates(self,
|
|
168
|
+
metadata: pydicom.Dataset | Nifti1Image | None = None,
|
|
169
|
+
slice_plane: ViewPlane | None = None) -> Self:
|
|
170
|
+
"""Copy with points in patient coordinates. The slice index of each point is rounded."""
|
|
171
|
+
if self.coordinate_system == 'patient':
|
|
172
|
+
return self.model_copy()
|
|
173
|
+
if metadata is None: # 2D images without geometry: patient and pixel are the same
|
|
174
|
+
return self.model_copy(update={'coordinate_system': 'patient'})
|
|
175
|
+
points = tuple(
|
|
176
|
+
_normalize_point(_pixel_to_patient_point(p, frame_index=int(round(p[2])), slice_plane=slice_plane,
|
|
177
|
+
metadata=metadata), allow_2d=False)
|
|
178
|
+
for p in self.points
|
|
179
|
+
)
|
|
180
|
+
viewPlaneNormal, viewUp = _TwoPointGeometry._extract_view_parameters(metadata)
|
|
181
|
+
return self.model_copy(update={'points': points, 'coordinate_system': 'patient',
|
|
182
|
+
'viewPlaneNormal': viewPlaneNormal, 'viewUp': viewUp})
|
|
183
|
+
|
|
128
184
|
def to_dict(self) -> dict[str, Any]:
|
|
129
185
|
payload = self.model_dump(exclude={'type', 'coordinate_system'}, warnings='none')
|
|
130
186
|
if 'points' in payload:
|
|
@@ -272,6 +328,11 @@ class _TwoPointGeometry(Geometry):
|
|
|
272
328
|
class LineGeometry(_TwoPointGeometry):
|
|
273
329
|
type: ClassVar[str] = 'line'
|
|
274
330
|
|
|
331
|
+
@property
|
|
332
|
+
def length(self) -> float:
|
|
333
|
+
"""In pixels or mm, following ``coordinate_system``."""
|
|
334
|
+
return float(np.linalg.norm(np.subtract(self.point2, self.point1)))
|
|
335
|
+
|
|
275
336
|
|
|
276
337
|
class PointGeometry(Geometry):
|
|
277
338
|
points: tuple[Point3D]
|
|
@@ -365,6 +426,22 @@ class RegionGeometry(Geometry):
|
|
|
365
426
|
|
|
366
427
|
return tuple(_normalize_point(point) for point in value)
|
|
367
428
|
|
|
429
|
+
@property
|
|
430
|
+
def length(self) -> float:
|
|
431
|
+
"""Polyline length (perimeter if closed), in pixels or mm following ``coordinate_system``."""
|
|
432
|
+
pts = np.asarray(self.points, dtype=float)
|
|
433
|
+
if self.closed:
|
|
434
|
+
pts = np.vstack([pts, pts[:1]])
|
|
435
|
+
return float(np.linalg.norm(np.diff(pts, axis=0), axis=1).sum())
|
|
436
|
+
|
|
437
|
+
@property
|
|
438
|
+
def area(self) -> float:
|
|
439
|
+
"""Area inside a closed region, in pixels² or mm² following ``coordinate_system``."""
|
|
440
|
+
if not self.closed:
|
|
441
|
+
raise ValueError('area is only defined for closed regions')
|
|
442
|
+
pts = np.asarray(self.points, dtype=float)
|
|
443
|
+
return float(np.linalg.norm(np.cross(pts, np.roll(pts, -1, axis=0)).sum(0)) / 2)
|
|
444
|
+
|
|
368
445
|
@classmethod
|
|
369
446
|
def from_coordinates(
|
|
370
447
|
cls,
|
|
@@ -454,6 +531,28 @@ class BoxGeometry(Geometry):
|
|
|
454
531
|
def point2(self) -> Point3D:
|
|
455
532
|
return self.points[3]
|
|
456
533
|
|
|
534
|
+
@property
|
|
535
|
+
def xyxy(self) -> tuple[float, float, float, float]:
|
|
536
|
+
"""(x1, y1, x2, y2) in pixels. Needs pixel coordinates."""
|
|
537
|
+
if self.coordinate_system != 'pixel':
|
|
538
|
+
raise ValueError('xyxy needs pixel coordinates, call to_pixel_coordinates(metadata) first')
|
|
539
|
+
pts = np.asarray(self.points, dtype=float)[:, :2]
|
|
540
|
+
x1, y1 = pts.min(0)
|
|
541
|
+
x2, y2 = pts.max(0)
|
|
542
|
+
return float(x1), float(y1), float(x2), float(y2)
|
|
543
|
+
|
|
544
|
+
@property
|
|
545
|
+
def xywh(self) -> tuple[float, float, float, float]:
|
|
546
|
+
"""(x, y, width, height) in pixels. Needs pixel coordinates."""
|
|
547
|
+
x1, y1, x2, y2 = self.xyxy
|
|
548
|
+
return x1, y1, x2 - x1, y2 - y1
|
|
549
|
+
|
|
550
|
+
@property
|
|
551
|
+
def area(self) -> float:
|
|
552
|
+
"""In pixels² or mm², following ``coordinate_system``."""
|
|
553
|
+
pts = np.asarray(self.points, dtype=float)
|
|
554
|
+
return float(np.linalg.norm(pts[1] - pts[0]) * np.linalg.norm(pts[2] - pts[0]))
|
|
555
|
+
|
|
457
556
|
@classmethod
|
|
458
557
|
def from_coordinates(
|
|
459
558
|
cls,
|
|
@@ -22,6 +22,7 @@ from .cache_manager import CacheManager
|
|
|
22
22
|
|
|
23
23
|
if TYPE_CHECKING:
|
|
24
24
|
import numpy as np
|
|
25
|
+
from matplotlib.axes import Axes
|
|
25
26
|
from medimgkit import ViewPlane
|
|
26
27
|
|
|
27
28
|
from datamint.api.endpoints.resources_api import ResourcesApi
|
|
@@ -627,6 +628,41 @@ class Resource(BaseResource):
|
|
|
627
628
|
"""Open the resource in the default web browser."""
|
|
628
629
|
webbrowser.open(self.url)
|
|
629
630
|
|
|
631
|
+
def plot_segmentations(self,
|
|
632
|
+
index: int | None = None,
|
|
633
|
+
axis: 'ViewPlane' = 'axial',
|
|
634
|
+
alpha: float = 0.5,
|
|
635
|
+
ax: 'Axes | None' = None) -> 'Axes':
|
|
636
|
+
"""Plot one slice (or the 2D image) with all its segmentations on top.
|
|
637
|
+
|
|
638
|
+
``index=None`` picks the slice with the biggest mask. ``axis`` is only used for volumes.
|
|
639
|
+
"""
|
|
640
|
+
from datamint.utils.visualization import plot_segmentations
|
|
641
|
+
|
|
642
|
+
return plot_segmentations(self, index=index, axis=axis, alpha=alpha, ax=ax)
|
|
643
|
+
|
|
644
|
+
def plot_shapes(self,
|
|
645
|
+
axis: 'ViewPlane | None' = None,
|
|
646
|
+
index: int | None = None,
|
|
647
|
+
ax: 'Axes | None' = None) -> 'Axes':
|
|
648
|
+
"""Plot one slice (or the 2D image) with its boxes, lines, points and regions.
|
|
649
|
+
|
|
650
|
+
``axis`` is required for volumes: shapes are only shown on the plane they were drawn on.
|
|
651
|
+
``index=None`` picks the slice with the most shapes.
|
|
652
|
+
"""
|
|
653
|
+
from datamint.utils.visualization import plot_shapes
|
|
654
|
+
|
|
655
|
+
return plot_shapes(self, axis=axis, index=index, ax=ax)
|
|
656
|
+
|
|
657
|
+
def plot_labels(self,
|
|
658
|
+
index: int | None = None,
|
|
659
|
+
axis: 'ViewPlane' = 'axial',
|
|
660
|
+
ax: 'Axes | None' = None) -> 'Axes':
|
|
661
|
+
"""Plot one slice (or the 2D image) with its categories, labels, numbers and texts listed on top."""
|
|
662
|
+
from datamint.utils.visualization import plot_labels
|
|
663
|
+
|
|
664
|
+
return plot_labels(self, index=index, axis=axis, ax=ax)
|
|
665
|
+
|
|
630
666
|
@staticmethod
|
|
631
667
|
def from_local_file(file_path: str | Path):
|
|
632
668
|
"""Create a LocalResource instance from a local file path.
|
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
import colorsys
|
|
2
|
+
import logging
|
|
3
|
+
from collections.abc import Sequence
|
|
4
|
+
from typing import TYPE_CHECKING
|
|
5
|
+
|
|
6
|
+
import matplotlib.pyplot as plt
|
|
7
|
+
import numpy as np
|
|
8
|
+
import torch
|
|
9
|
+
import torchvision.utils
|
|
10
|
+
from matplotlib.axes import Axes
|
|
11
|
+
from matplotlib.patches import Patch
|
|
12
|
+
from torch import Tensor
|
|
13
|
+
from torchvision.transforms import functional as F
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from medimgkit import ViewPlane
|
|
17
|
+
|
|
18
|
+
from datamint.entities.annotations import Annotation
|
|
19
|
+
from datamint.entities.resource import Resource
|
|
20
|
+
|
|
21
|
+
_LOGGER = logging.getLogger(__name__)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def show(imgs: Sequence[Tensor | np.ndarray] | Tensor | np.ndarray,
|
|
25
|
+
figsize: tuple[int, int] | None = None,
|
|
26
|
+
normalize: bool = False,
|
|
27
|
+
ax: Axes | Sequence[Axes] | None = None):
|
|
28
|
+
"""
|
|
29
|
+
Show a list of images in a grid.
|
|
30
|
+
Args:
|
|
31
|
+
imgs (Sequence[Tensor | np.ndarray] | Tensor | np.ndarray): List of images to show.
|
|
32
|
+
Each image should be a tensor of shape (C, H, W) and dtype uint8 or float.
|
|
33
|
+
figsize (tuple[int, int], optional): Size of the figure. Defaults to None.
|
|
34
|
+
normalize (bool, optional): Whether to normalize the images to [0, 1] range by min-max scaling.
|
|
35
|
+
ax (Axes | Sequence[Axes], optional): Matplotlib axes to plot on. If None, new axes are created.
|
|
36
|
+
If a single Axes is provided and multiple images are given, only the first image is shown.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
if not isinstance(imgs, list) and not isinstance(imgs, tuple):
|
|
40
|
+
imgs = [imgs]
|
|
41
|
+
|
|
42
|
+
imgs = [img if isinstance(img, torch.Tensor) else torch.from_numpy(img) for img in imgs]
|
|
43
|
+
|
|
44
|
+
if normalize:
|
|
45
|
+
for i, img in enumerate(imgs):
|
|
46
|
+
img = img.float()
|
|
47
|
+
img = img - img.min()
|
|
48
|
+
img = img / img.max()
|
|
49
|
+
imgs[i] = img
|
|
50
|
+
|
|
51
|
+
if ax is None:
|
|
52
|
+
if figsize is not None:
|
|
53
|
+
_fig, axs = plt.subplots(ncols=len(imgs), squeeze=False, figsize=figsize)
|
|
54
|
+
else:
|
|
55
|
+
_fig, axs = plt.subplots(ncols=len(imgs), squeeze=False)
|
|
56
|
+
axs = axs[0]
|
|
57
|
+
else:
|
|
58
|
+
if isinstance(ax, Axes):
|
|
59
|
+
axs = [ax]
|
|
60
|
+
else:
|
|
61
|
+
axs = list(ax)
|
|
62
|
+
|
|
63
|
+
for i, img in enumerate(imgs):
|
|
64
|
+
if i >= len(axs):
|
|
65
|
+
break
|
|
66
|
+
img = img.detach()
|
|
67
|
+
img = F.to_pil_image(img)
|
|
68
|
+
axs[i].imshow(np.asarray(img))
|
|
69
|
+
axs[i].set(xticklabels=[], yticklabels=[], xticks=[], yticks=[])
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
_COLORS = [(255, 0, 0), (0, 255, 0), (0, 0, 255),
|
|
73
|
+
(200, 128, 0), (128, 200, 0), (0, 128, 200), (200, 0, 128), (128, 0, 200), (0, 200, 128)]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def generate_color_palette(num_objects: int) -> list[tuple[int, int, int]]:
|
|
77
|
+
"""
|
|
78
|
+
Generate a list of colors for segmentation masks.
|
|
79
|
+
|
|
80
|
+
Args:
|
|
81
|
+
num_objects (int): Number of objects to generate colors for.
|
|
82
|
+
|
|
83
|
+
Returns:
|
|
84
|
+
List of RGB colors.
|
|
85
|
+
"""
|
|
86
|
+
if num_objects <= 0:
|
|
87
|
+
raise ValueError("Number of objects must be greater than 0.")
|
|
88
|
+
|
|
89
|
+
colors = _COLORS[:num_objects]
|
|
90
|
+
if len(colors) == num_objects:
|
|
91
|
+
return colors
|
|
92
|
+
|
|
93
|
+
num_objects -= len(colors)
|
|
94
|
+
|
|
95
|
+
# generate random colors
|
|
96
|
+
for _ in range(num_objects):
|
|
97
|
+
hue = np.random.rand()
|
|
98
|
+
rgb = colorsys.hsv_to_rgb(hue, 0.9, 0.9)
|
|
99
|
+
colors.append(tuple(int(c * 255) for c in rgb))
|
|
100
|
+
|
|
101
|
+
return colors
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
@torch.inference_mode()
|
|
105
|
+
def draw_masks(
|
|
106
|
+
image: Tensor | np.ndarray,
|
|
107
|
+
masks: Tensor | np.ndarray,
|
|
108
|
+
alpha: float = 0.5,
|
|
109
|
+
colors: Sequence[str | tuple[int, int, int]] | str | tuple[int, int, int] | None = None,
|
|
110
|
+
) -> Tensor:
|
|
111
|
+
"""
|
|
112
|
+
Draws segmentation masks on given RGB image.
|
|
113
|
+
This is different from `torchvision.utils.draw_segmentation_masks` as overlapping masks are blended together correctly.
|
|
114
|
+
The image values should be uint8 or float.
|
|
115
|
+
|
|
116
|
+
Args:
|
|
117
|
+
image (Tensor): Tensor of shape (3, H, W) or (H, W) and dtype uint8 or float.
|
|
118
|
+
masks (Tensor): Tensor of shape (num_masks, H, W) or (H, W) and dtype bool.
|
|
119
|
+
alpha (float): Float number between 0 and 1 denoting the transparency of the masks.
|
|
120
|
+
0 means full transparency, 1 means no transparency.
|
|
121
|
+
colors (color or list of colors, optional): List containing the colors
|
|
122
|
+
of the masks or single color for all masks. The color can be represented as
|
|
123
|
+
PIL strings e.g. "red" or "#FF00FF", or as RGB tuples e.g. ``(240, 10, 157)``.
|
|
124
|
+
By default, random colors are generated for each mask.
|
|
125
|
+
|
|
126
|
+
Returns:
|
|
127
|
+
img (Tensor[C, H, W]): Image Tensor, with segmentation masks drawn on top.
|
|
128
|
+
"""
|
|
129
|
+
|
|
130
|
+
if isinstance(image, np.ndarray):
|
|
131
|
+
image = torch.from_numpy(image)
|
|
132
|
+
|
|
133
|
+
if isinstance(masks, np.ndarray):
|
|
134
|
+
masks = torch.from_numpy(masks)
|
|
135
|
+
|
|
136
|
+
if masks.ndim == 4:
|
|
137
|
+
_LOGGER.warning(f"In draw_masks: Expected masks to have shape (num_masks, H, W) or (H, W), but got {masks.shape}."
|
|
138
|
+
" It might produce unexpected results. Please check the shape of the masks.")
|
|
139
|
+
|
|
140
|
+
if image.ndim == 3 and image.shape[0] == 1:
|
|
141
|
+
# convert to RGB
|
|
142
|
+
image = image.expand(3, -1, -1)
|
|
143
|
+
if image.ndim == 2:
|
|
144
|
+
# convert to RGB
|
|
145
|
+
image = image.unsqueeze(0).expand(3, -1, -1)
|
|
146
|
+
|
|
147
|
+
if masks.dtype != torch.bool:
|
|
148
|
+
masks = masks.bool()
|
|
149
|
+
|
|
150
|
+
# if image has negative values, scale to [0, 1]
|
|
151
|
+
if image.min() < 0:
|
|
152
|
+
image = image.float()
|
|
153
|
+
image = image - image.min()
|
|
154
|
+
image = image / image.max()
|
|
155
|
+
|
|
156
|
+
if masks.ndim == 2:
|
|
157
|
+
masks = masks.unsqueeze(0)
|
|
158
|
+
|
|
159
|
+
if colors is None:
|
|
160
|
+
colors = generate_color_palette(len(masks))
|
|
161
|
+
|
|
162
|
+
for color, mask in zip(colors, masks):
|
|
163
|
+
image = torchvision.utils.draw_segmentation_masks(image=image,
|
|
164
|
+
masks=mask,
|
|
165
|
+
alpha=alpha,
|
|
166
|
+
colors=color)
|
|
167
|
+
return image
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
# --- Resource plots ---
|
|
171
|
+
|
|
172
|
+
def _std_axis_idx(resource: 'Resource', metainfo, axis: 'ViewPlane') -> int:
|
|
173
|
+
"""Axis of the (N, C, H, W) array that matches the anatomical plane, same as SlicedVolumeResource."""
|
|
174
|
+
from medimgkit import dicom_utils, nifti_utils
|
|
175
|
+
|
|
176
|
+
if resource.is_dicom():
|
|
177
|
+
return dicom_utils.rawplaneaxis2stdplaneaxis_idx(dicom_utils.get_plane_axis(metainfo, axis))
|
|
178
|
+
if resource.is_nifti():
|
|
179
|
+
return nifti_utils.rawplaneaxis2stdplaneaxis_idx(nifti_utils.get_plane_axis(metainfo, axis))
|
|
180
|
+
raise ValueError(f'Unsupported resource type for slicing: {resource.filename}|{resource.mimetype}')
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _load_masks(anns: Sequence['Annotation'], depth: int) -> tuple[np.ndarray | None, list[str]]:
|
|
184
|
+
"""(M, N, H, W) binary masks, one per (author, identifier), and their legend names."""
|
|
185
|
+
from medimgkit.readers import read_array_normalized
|
|
186
|
+
|
|
187
|
+
groups: dict[tuple[str, str], np.ndarray] = {}
|
|
188
|
+
for ann in anns:
|
|
189
|
+
mask = read_array_normalized(ann.fetch_file_data(auto_convert=False, use_cache=True)).any(1) # (N, H, W)
|
|
190
|
+
key = (ann.created_by or getattr(ann, 'created_by_model', None) or 'unknown', ann.identifier)
|
|
191
|
+
if ann.scope == 'frame':
|
|
192
|
+
vol = groups.setdefault(key, np.zeros((depth, *mask.shape[1:]), dtype=bool))
|
|
193
|
+
vol[ann.frame_index] |= mask[0]
|
|
194
|
+
else:
|
|
195
|
+
groups[key] = groups[key] | mask if key in groups else mask
|
|
196
|
+
|
|
197
|
+
if not groups:
|
|
198
|
+
return None, []
|
|
199
|
+
multiple_authors = len({author for author, _ in groups}) > 1
|
|
200
|
+
names = [f'{identifier} ({author})' if multiple_authors else identifier for author, identifier in groups]
|
|
201
|
+
return np.stack(list(groups.values())), names
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
_SHAPE_TYPES = ('square', 'line', 'point', 'region', 'circle', 'spline', 'distance', 'angle', 'area')
|
|
205
|
+
_LABEL_TYPES = ('category', 'label', 'integer', 'float', 'text')
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _read_volume(resource: 'Resource', axis: 'ViewPlane | None'):
|
|
209
|
+
"""(N, C, H, W) array, its metainfo and the array axis to slice along."""
|
|
210
|
+
from medimgkit.readers import read_array_normalized
|
|
211
|
+
|
|
212
|
+
raw = resource.fetch_file_data(auto_convert=False, use_cache=True)
|
|
213
|
+
vol, metainfo = read_array_normalized(raw, return_metainfo=True)
|
|
214
|
+
std_axis = _std_axis_idx(resource, metainfo, axis) if resource.is_volume() else 0
|
|
215
|
+
return vol, metainfo, std_axis
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _get_image(vol: np.ndarray, index: int, std_axis: int) -> np.ndarray:
|
|
219
|
+
"""(C, a, b) slice scaled to [0, 1]."""
|
|
220
|
+
img = np.take(vol, index, axis=std_axis) # (C, a, b), or (a, C, b) when slicing H or W
|
|
221
|
+
if std_axis != 0:
|
|
222
|
+
img = np.moveaxis(img, 1, 0)
|
|
223
|
+
img = img.astype(np.float32)
|
|
224
|
+
return np.ascontiguousarray((img - img.min()) / (img.max() - img.min() + 1e-8))
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _plot_title(resource: 'Resource', axis: 'ViewPlane | None', index: int) -> str:
|
|
228
|
+
return f'{resource.filename} | {axis} {index}' if resource.is_volume() else f'{resource.filename} | {index}'
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def plot_segmentations(resource: 'Resource',
|
|
232
|
+
index: int | None = None,
|
|
233
|
+
axis: 'ViewPlane' = 'axial',
|
|
234
|
+
alpha: float = 0.5,
|
|
235
|
+
ax: Axes | None = None) -> Axes:
|
|
236
|
+
"""Plot one slice (or frame, or the 2D image) of ``resource`` with all its segmentations on top.
|
|
237
|
+
|
|
238
|
+
``index=None`` picks the slice with the biggest mask. ``axis`` is only used for volumes.
|
|
239
|
+
"""
|
|
240
|
+
vol, _, std_axis = _read_volume(resource, axis)
|
|
241
|
+
seg_axis = 0 if std_axis == 0 else std_axis - 1 # masks are (N, H, W), without the channel axis
|
|
242
|
+
|
|
243
|
+
anns = resource.fetch_annotations(annotation_type='segmentation')
|
|
244
|
+
masks, names = _load_masks(anns, depth=vol.shape[0])
|
|
245
|
+
if masks is None:
|
|
246
|
+
_LOGGER.warning(f'No segmentations found for resource {resource.filename!r}')
|
|
247
|
+
|
|
248
|
+
if index is None:
|
|
249
|
+
if masks is None:
|
|
250
|
+
index = 0
|
|
251
|
+
else:
|
|
252
|
+
area = masks.any(0).sum(axis=tuple(a for a in range(3) if a != seg_axis))
|
|
253
|
+
index = int(area.argmax())
|
|
254
|
+
|
|
255
|
+
img = _get_image(vol, index, std_axis)
|
|
256
|
+
if ax is None:
|
|
257
|
+
_fig, ax = plt.subplots()
|
|
258
|
+
|
|
259
|
+
if masks is None:
|
|
260
|
+
show(img, ax=ax)
|
|
261
|
+
else:
|
|
262
|
+
colors = generate_color_palette(len(masks))
|
|
263
|
+
slice_masks = np.ascontiguousarray(np.take(masks, index, axis=seg_axis + 1)) # (M, a, b)
|
|
264
|
+
show(draw_masks(img, slice_masks, alpha=alpha, colors=colors), ax=ax)
|
|
265
|
+
ax.legend(handles=[Patch(color=np.array(c) / 255, label=n) for c, n in zip(colors, names)],
|
|
266
|
+
loc='upper right', fontsize='small')
|
|
267
|
+
|
|
268
|
+
ax.set_title(_plot_title(resource, axis, index), fontsize='small')
|
|
269
|
+
return ax
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _draw_shape(ax: Axes, ann_type: str, pts: np.ndarray, color, closed: bool = False) -> None:
|
|
273
|
+
"""``pts`` are (P, 2) pixel coordinates on the plotted slice."""
|
|
274
|
+
if ann_type == 'point':
|
|
275
|
+
ax.scatter(pts[:, 0], pts[:, 1], color=color, marker='x')
|
|
276
|
+
return
|
|
277
|
+
if ann_type == 'square':
|
|
278
|
+
pts = pts[[0, 1, 3, 2]] # corners are stored as (p1, top right, bottom left, p2)
|
|
279
|
+
closed = True
|
|
280
|
+
if closed:
|
|
281
|
+
pts = np.vstack([pts, pts[:1]])
|
|
282
|
+
ax.plot(pts[:, 0], pts[:, 1], color=color, linewidth=1.5)
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def plot_shapes(resource: 'Resource',
|
|
286
|
+
axis: 'ViewPlane | None' = None,
|
|
287
|
+
index: int | None = None,
|
|
288
|
+
ax: Axes | None = None) -> Axes:
|
|
289
|
+
"""Plot one slice (or the 2D image) of ``resource`` with its boxes, lines, points and regions.
|
|
290
|
+
|
|
291
|
+
``axis`` is required for volumes: shapes are only shown on the plane they were drawn on.
|
|
292
|
+
``index=None`` picks the slice with the most shapes.
|
|
293
|
+
"""
|
|
294
|
+
from datamint.entities.annotations.geometry import Geometry
|
|
295
|
+
|
|
296
|
+
if resource.is_volume() and axis is None:
|
|
297
|
+
raise ValueError("axis is required for volumes, e.g. axis='axial'")
|
|
298
|
+
|
|
299
|
+
vol, metainfo, std_axis = _read_volume(resource, axis)
|
|
300
|
+
plane = axis if resource.is_volume() else None
|
|
301
|
+
|
|
302
|
+
anns = [ann for ann in resource.fetch_annotations() if ann.annotation_type in _SHAPE_TYPES]
|
|
303
|
+
shapes = [] # (annotation, (P, 3) slice coordinates)
|
|
304
|
+
skipped: dict[str, int] = {}
|
|
305
|
+
for ann in anns:
|
|
306
|
+
geom = ann.geometry
|
|
307
|
+
if not isinstance(geom, Geometry):
|
|
308
|
+
skipped[ann.annotation_type] = skipped.get(ann.annotation_type, 0) + 1
|
|
309
|
+
continue
|
|
310
|
+
pts = np.asarray(geom.to_pixel_coordinates(metainfo, plane).points, dtype=float)
|
|
311
|
+
if np.ptp(pts[:, 2]) > 0.5:
|
|
312
|
+
skipped['other plane'] = skipped.get('other plane', 0) + 1
|
|
313
|
+
continue
|
|
314
|
+
shapes.append((ann, pts))
|
|
315
|
+
if skipped:
|
|
316
|
+
_LOGGER.warning(f'Shapes not shown: {skipped}')
|
|
317
|
+
|
|
318
|
+
slice_of = [int(round(pts[0, 2])) for _, pts in shapes]
|
|
319
|
+
if index is None:
|
|
320
|
+
index = max(set(slice_of), key=slice_of.count) if shapes else 0
|
|
321
|
+
|
|
322
|
+
if ax is None:
|
|
323
|
+
_fig, ax = plt.subplots()
|
|
324
|
+
show(_get_image(vol, index, std_axis), ax=ax)
|
|
325
|
+
|
|
326
|
+
names = sorted({ann.identifier for ann in anns})
|
|
327
|
+
colors = {name: np.array(c) / 255 for name, c in zip(names, generate_color_palette(len(names)))} if names else {}
|
|
328
|
+
for (ann, pts), k in zip(shapes, slice_of):
|
|
329
|
+
if k == index:
|
|
330
|
+
_draw_shape(ax, ann.annotation_type, pts[:, :2], colors[ann.identifier],
|
|
331
|
+
closed=getattr(ann.geometry, 'closed', False))
|
|
332
|
+
if colors:
|
|
333
|
+
ax.legend(handles=[Patch(color=c, label=n) for n, c in colors.items()], loc='upper right', fontsize='small')
|
|
334
|
+
|
|
335
|
+
ax.set_title(_plot_title(resource, axis, index), fontsize='small')
|
|
336
|
+
return ax
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def plot_labels(resource: 'Resource',
|
|
340
|
+
index: int | None = None,
|
|
341
|
+
axis: 'ViewPlane' = 'axial',
|
|
342
|
+
ax: Axes | None = None) -> Axes:
|
|
343
|
+
"""Plot one slice (or the 2D image) of ``resource`` with its categories, labels, numbers and texts listed on top.
|
|
344
|
+
|
|
345
|
+
Frame labels are shown on the native slices only.
|
|
346
|
+
``index=None`` picks the first slice with a frame label, or the middle slice.
|
|
347
|
+
"""
|
|
348
|
+
vol, _, std_axis = _read_volume(resource, axis)
|
|
349
|
+
anns = [ann for ann in resource.fetch_annotations() if ann.annotation_type in _LABEL_TYPES]
|
|
350
|
+
|
|
351
|
+
def on_slice(ann, k: int) -> bool:
|
|
352
|
+
if ann.scope != 'frame':
|
|
353
|
+
return True
|
|
354
|
+
if std_axis != 0:
|
|
355
|
+
return False
|
|
356
|
+
if ann.frame_ranges:
|
|
357
|
+
return any(start <= k <= end for start, end in ann.frame_ranges)
|
|
358
|
+
return ann.frame_index == k
|
|
359
|
+
|
|
360
|
+
if index is None:
|
|
361
|
+
frames = sorted(ann.frame_index for ann in anns if ann.scope == 'frame' and ann.frame_index is not None)
|
|
362
|
+
index = frames[0] if frames and std_axis == 0 else vol.shape[std_axis] // 2
|
|
363
|
+
|
|
364
|
+
lines = []
|
|
365
|
+
for ann in anns:
|
|
366
|
+
if not on_slice(ann, index):
|
|
367
|
+
continue
|
|
368
|
+
value = ann.text_value if ann.text_value is not None else ann.numeric_value
|
|
369
|
+
if value is None:
|
|
370
|
+
lines.append(ann.identifier)
|
|
371
|
+
else:
|
|
372
|
+
lines.append(f'{ann.identifier}: {value}' + (f' {ann.units}' if ann.units else ''))
|
|
373
|
+
|
|
374
|
+
if ax is None:
|
|
375
|
+
_fig, ax = plt.subplots()
|
|
376
|
+
show(_get_image(vol, index, std_axis), ax=ax)
|
|
377
|
+
ax.text(0.01, 0.99, '\n'.join(lines) if lines else 'no labels', transform=ax.transAxes,
|
|
378
|
+
va='top', ha='left', fontsize='small', color='white',
|
|
379
|
+
bbox={'facecolor': 'black', 'alpha': 0.6, 'edgecolor': 'none'})
|
|
380
|
+
|
|
381
|
+
ax.set_title(_plot_title(resource, axis, index), fontsize='small')
|
|
382
|
+
return ax
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "datamint"
|
|
3
3
|
description = "A library for interacting with the Datamint API, designed for efficient data management, processing and Deep Learning workflows."
|
|
4
|
-
version = "2.
|
|
4
|
+
version = "2.50.0"
|
|
5
5
|
dynamic = ["dependencies"]
|
|
6
6
|
requires-python = ">=3.10"
|
|
7
7
|
readme = "README.md"
|