Skip to main content

The easy way to manipulate medical images.

Project description

EasyMedicalImages

The easy way to manipulate medical images

---------------------------------------------------------------------------

This is a library that focuses on taking CT scans and transforming them into arrays in python; giving the user easy ways to manipulate them as well. This can easily be used for downstream usage of CT images within a Python script.

Installation

Requires Python 3.12 or newer.

pip install easy-medical-images

The high-level batch loader (HighLevel) is a compiled C++ extension. The published wheels include it, so a normal pip install is all you need.

Expected data layout

Each case lives in its own folder containing an image and a segmentation. By default these are named image.nii.gz and tumor_segmentation_v2.nii.gz, but you can override both names (see image_path and seg_path below).

parent_folder/
├── case_0001/
│   ├── image.nii.gz
│   └── tumor_segmentation_v2.nii.gz
├── case_0002/
│   ├── image.nii.gz
│   └── tumor_segmentation_v2.nii.gz
└── ...

Remeber to put the proper root for the input directory path! For example, if your files live on a cloud.

CTImagesLibrary operates on a single case folder. HighLevel operates on a parent folder and loads every case folder inside it.

How it fits together

Generally, this library assumes the user wants a batch of something rather than a specific image. This is reflected in how you first load in your specific instance, and then can add modifiers how you wish.

There are two main sub libraries:

  1. HighLevel: point it at a parent directory and it loads every case in parallel (after the method 'run_on_directory' is called on the instance). This will return a list of (image, seg) array pairs. Use this to pull a whole dataset into memory quickly.
  2. CTImagesLibrary: load one case and get the full manipulation toolkit (slicing, cropping, reorientation, display). Use this when you want to work with an individual scan. See below for examples.

Quick start: load a whole directory

import EasyMedicalImages as EMI

path_to_folder_of_ct_scans = input("Input path to CT scans: ")
instance = EMI.HighLevel(path_to_folder=path_to_folder_of_ct_scans)

img_seg_pairs_mega_list = instance.run_on_directory()  # list of (image, seg) array pairs
'''
img_seg_pairs_mega_list=[(img1, seg1),(img2, seg2)...]
'''

# Each entry is one case
img, seg = img_seg_pairs_mega_list[0]
print(f"{len(img_seg_pairs_mega_list)} cases loaded")
print(f"First image shape: {img.shape}, seg shape: {seg.shape}")

Every entry in img_seg_pairs_mega_list is a tuple of two NumPy float32 arrays: the image and its segmentation. Both are already resampled to isotropic spacing and reoriented to RAS, so they are ready to use.

To access all of the images or all of the segs while keeping order, one can simply do:

all_images=[images for images,_ in img_seg_pairs_mega_list]
all_segmentations=[segmentations for _, segmentations in img_seg_pairs_mega_list]

# Both of the below will print the entire array
print(f"Images: {all_images}")
print(f"Segmentation Masks: {all_segmentations}")

# This just shows the shape, easier to comprehend.
print([(img.shape, seg.shape) for img, seg in img_seg_pairs_mega_list])

Working with a single case

from EasyMedicalImages import CTImagesLibrary
 
case = CTImagesLibrary(path_to_folder="path/to/one/case")
 
# The voxels are automatically processed upon calling of the instance, unlike the batch version.
print(case.mutated_img_data.shape)
print(case.mutated_seg_data.shape)
 
# Display three orthogonal slices (slice numbers are 1-based, ordered X, Y, Z)
case.display_slice(slice_number=(175, 279, 57), img_or_seg="img")
 
# Get those same slices back as arrays
slice_x, slice_y, slice_z = case.return_slice(slice_number=(175, 279, 57), img_or_seg="img")
 
# Crop the whole volume down to the segmented region (modifies the mutated arrays in place)
case.apply_seg_crop_to_image(img_or_seg="both")
print(case.mutated_img_data.shape)  # smaller now

As stated earlier, building CTImagesLibrary automatically: changes the working directory into path_to_folder, loads the image and segmentation, and builds isotropic, RAS-reoriented copies. After construction, both the raw and processed arrays are available as attributes via your_instancename.raw_img_data, or for seg your_instancename.raw_seg_data.

Further detail

This section goes one level deeper on each of the two sublibraries: how you construct it, and what you can call on it once you have an instance. Both are reached through the top-level package (import EasyMedicalImages as EMI, then EMI.HighLevel or EMI.CTImagesLibrary).

HighLevel

The batch sublibrary. Point it at a parent folder, call run_on_directory, and get every case back as (image, seg) array pairs. This is the one to reach for when you want a whole dataset in memory at once.

Construct it (default parameters):

HighLevel(
    path_to_folder,
    image_path="image.nii.gz",
    seg_path="tumor_segmentation_v2.nii.gz",
    verbose=False,
    thread_deadline_time=66.0,
    verbose_workers=True,
)
  • path_to_folder: parent folder whose immediate subfolders are individual cases.
  • image_path, seg_path: file names to look for inside each case folder.
  • verbose: passed through to each worker for extra logging.
  • thread_deadline_time: per-case wall-clock budget in seconds. A worker that runs longer is killed and that case is skipped. This is to prevent a thread, which is just stalling or trying to load a not image, from stoping the whole process.
  • verbose_workers: print per-worker progress (which case each worker picked up, load confirmations, and the final count).

Methods:

  • run_on_directory(directory_path="") Loads every case in the directory and returns a list of (image, seg) tuples, one per case, in the same order as the folders on disk. Both elements are NumPy float32 arrays, already resampled to isotropic spacing and reoriented to RAS. If directory_path is given it overrides path_to_folder for that one call. Cases that fail to load or exceed thread_deadline_time are dropped, so the returned list can be shorter than the number of folders in theory (so don't set this too low).

Loading runs in parallel: one worker subprocess per case, across roughly 80 percent of the available hardware threads. On Linux it respects the CPU affinity set by schedulers such as SLURM, so it behaves correctly on a cluster node. Note that this method returns images and segmentations only; it does not return affines.

  • how_many_threads_available() Returns the number of hardware threads detected (the figure the worker pool is sized from). Honors SLURM cpuset limits on Linux and falls back sensibly when the OS reports nothing.

  • processed_run_on_directory() A special version of run_on_directory that applies a method to all items loaded. Presently, only apply_seg_crop_to_image is allowed. Example:

    hl = HighLevel(r"W:\...\dataset")           # or however you construct it
    
    pairs = hl.run_on_directory()               # unchanged plain load
    
    pairs = hl.processed_run_on_directory(     # crop every case to the seg bbox
    "apply_seg_crop_to_image",
    {"img_or_seg": "both", "pad": 5},
    )
    # -> list[tuple[np.ndarray, np.ndarray]]
    
  • go_one_level_deep() A method which will display all of the items in a directory, be them folders, files, or both. If no perameter is specified for directory_path it will simply use the root given at HighLevels class construction. Example:

    hl = HighLevel(root, "image.nii.gz", "tumor_segmentation_v2.nii.gz")
    hl.go_one_level_deep()                          # -> list[str] of subfolder paths
    hl.go_one_level_deep(options="files")           # regular files only
    hl.go_one_level_deep(options="all")             # everything
    hl.go_one_level_deep(directory_path=other_dir)  # scan a different dir this call onl
    

CTImagesLibrary

The single-case sublibrary. Construct it on one case folder and the data is processed and waiting on the instance; from there you slice, crop, reorient, and display. This is the toolkit HighLevel runs under the hood for each case, so the arrays you get out of either path match.

Construct it (default parameters):

CTImagesLibrary(
    path_to_folder,
    image_path="image.nii.gz",
    seg_path="tumor_segmentation_v2.nii.gz",
    verbose=True,
    return_affines=False,
)

The image and segmentation are loaded and processed during construction, so the attributes below are ready as soon as the instance exists.

Attributes on the instance:

  • raw_img_data, raw_seg_data: the original voxel arrays as loaded.
  • raw_img_affine, raw_seg_affine: the original 4x4 affine matrices.
  • mutated_img_data, mutated_seg_data: isotropic, RAS-reoriented copies. These are usually what you want for machine learning.
  • mutated_img_affine, mutated_seg_affine: affines describing the processed grid.

methods:

  • display_slice(slice_number=(), cmap="viridis", view_axes=("X", "Y", "Z"), load_mutated=True, crop=False, pad=5, img_or_seg="img") Shows one slice per requested axis side by side with matplotlib. slice_number is a 1-based (X, Y, Z) tuple and must contain exactly three values. Set load_mutated=False to view the original (non-isotropic) volume, crop=True to trim each slice to its own non-background region (with pad voxels of margin), and img_or_seg="seg" to view the segmentation instead.

  • return_slice(slice_number=(), view_axes=("X", "Y", "Z"), load_mutated=True, one_list=False, crop=False, pad=5, img_or_seg="img") Returns slices as arrays instead of displaying them. With the default three axes it returns (slice_x, slice_y, slice_z); set one_list=True to get them as a single array of three instead (convenient for batching). Request a single axis (for example view_axes=("Z",)) to get just that one slice back. The arrays match exactly what display_slice shows.

  • apply_seg_crop_to_image(pad=5, return_data=False, img_or_seg="both") Crops the full 3D volume in place to the bounding box of the segmentation, keeping pad voxels of margin. This overwrites mutated_img_data and mutated_seg_data (and their affines) with the cropped versions. Use img_or_seg to crop only "img", only "seg", or "both" (the default). If the segmentation is empty, nothing is cropped. Set return_data=True to also return the cropped arrays.

  • apply_seg_crop_to_slice(slice_number=(), one_list=False, pad=5, img_or_seg="img") The 2D version: returns the X, Y, and Z slices cropped to the segmentation's footprint in each plane. Unlike the 3D version, this runs on the image or the segmentation, not both at once (img_or_seg is "img" by default). slice_number is the same 1-based (X, Y, Z) tuple.

Notes on orientation

The processed arrays (mutated_img_data and friends) are in proper RAS orientation. The slices produced by display_slice and return_slice add a 90-degree flip on the Z axis so they read naturally in matplotlib (similar to how ITK displays them). In short: use the instance arrays when you need correct anatomical orientation, and use return_slice when you want something that looks right on screen.

PyPI link: PyPI

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

easy_medical_images-1.1.0.tar.gz (52.4 kB view details)

Uploaded Source

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

easy_medical_images-1.1.0-cp314-cp314-win_amd64.whl (577.1 kB view details)

Uploaded CPython 3.14Windows x86-64

easy_medical_images-1.1.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl (234.5 kB view details)

Uploaded CPython 3.14manylinux: glibc 2.27+ x86-64manylinux: glibc 2.28+ x86-64

easy_medical_images-1.1.0-cp314-cp314-macosx_11_0_arm64.whl (134.4 kB view details)

Uploaded CPython 3.14macOS 11.0+ ARM64

easy_medical_images-1.1.0-cp314-cp314-macosx_10_15_x86_64.whl (141.5 kB view details)

Uploaded CPython 3.14macOS 10.15+ x86-64

easy_medical_images-1.1.0-cp313-cp313-win_amd64.whl (557.2 kB view details)

Uploaded CPython 3.13Windows x86-64

easy_medical_images-1.1.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl (234.5 kB view details)

Uploaded CPython 3.13manylinux: glibc 2.27+ x86-64manylinux: glibc 2.28+ x86-64

easy_medical_images-1.1.0-cp313-cp313-macosx_11_0_arm64.whl (134.2 kB view details)

Uploaded CPython 3.13macOS 11.0+ ARM64

easy_medical_images-1.1.0-cp313-cp313-macosx_10_15_x86_64.whl (141.4 kB view details)

Uploaded CPython 3.13macOS 10.15+ x86-64

easy_medical_images-1.1.0-cp312-cp312-win_amd64.whl (557.3 kB view details)

Uploaded CPython 3.12Windows x86-64

easy_medical_images-1.1.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl (234.4 kB view details)

Uploaded CPython 3.12manylinux: glibc 2.27+ x86-64manylinux: glibc 2.28+ x86-64

easy_medical_images-1.1.0-cp312-cp312-macosx_11_0_arm64.whl (134.1 kB view details)

Uploaded CPython 3.12macOS 11.0+ ARM64

easy_medical_images-1.1.0-cp312-cp312-macosx_10_15_x86_64.whl (141.3 kB view details)

Uploaded CPython 3.12macOS 10.15+ x86-64

File details

Details for the file easy_medical_images-1.1.0.tar.gz.

File metadata

  • Download URL: easy_medical_images-1.1.0.tar.gz
  • Upload date:
  • Size: 52.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for easy_medical_images-1.1.0.tar.gz
Algorithm Hash digest
SHA256 3ad59dd9854991f6b40f5080f2298d9abdf1d49b52df43e90927ba608b80388f
MD5 53a133523cc3059a99dc1637325b17c8
BLAKE2b-256 144206d1aeed69b3b3bb3b075e1864f1b2747a0dbe2200f733ee2b8ee365fbef

See more details on using hashes here.

Provenance

The following attestation bundles were made for easy_medical_images-1.1.0.tar.gz:

Publisher: publish.yml on AIM-HI-Lab/EasyMedicalImages

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file easy_medical_images-1.1.0-cp314-cp314-win_amd64.whl.

File metadata

File hashes

Hashes for easy_medical_images-1.1.0-cp314-cp314-win_amd64.whl
Algorithm Hash digest
SHA256 0d627eb6235bce73a1808d5fc451e6331b53c3e3c684f1f840501b304cefcf20
MD5 d0fa293c7de84d35752246c2e6e549e0
BLAKE2b-256 c983d68b166a47daa3d80cb961d2fff936221b72cf05da362c4cee9a2da3fb5c

See more details on using hashes here.

Provenance

The following attestation bundles were made for easy_medical_images-1.1.0-cp314-cp314-win_amd64.whl:

Publisher: publish.yml on AIM-HI-Lab/EasyMedicalImages

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file easy_medical_images-1.1.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl.

File metadata

File hashes

Hashes for easy_medical_images-1.1.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 1c9bccb5e3d7e9c7f41332cda3b04ab787d95ec87ffbed31b680b664a7bb91cc
MD5 dcfea150667b135fa834c2030bc90f65
BLAKE2b-256 fd2c43eda4af9b5816c3b6240b2b19069eb914f7fc1b4ef66bbdc91ab8ef4f87

See more details on using hashes here.

Provenance

The following attestation bundles were made for easy_medical_images-1.1.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl:

Publisher: publish.yml on AIM-HI-Lab/EasyMedicalImages

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file easy_medical_images-1.1.0-cp314-cp314-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for easy_medical_images-1.1.0-cp314-cp314-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 5ac3bc4cc1fcab2809950fe39fe24e50244b2267b9d676c2655e9d8ee1b59623
MD5 ecb7020ba78df22c2cce02da45527ae2
BLAKE2b-256 fc6f7192617893ffe78115743fea51fc28610edd744a74d43f1a082660c98d0f

See more details on using hashes here.

Provenance

The following attestation bundles were made for easy_medical_images-1.1.0-cp314-cp314-macosx_11_0_arm64.whl:

Publisher: publish.yml on AIM-HI-Lab/EasyMedicalImages

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file easy_medical_images-1.1.0-cp314-cp314-macosx_10_15_x86_64.whl.

File metadata

File hashes

Hashes for easy_medical_images-1.1.0-cp314-cp314-macosx_10_15_x86_64.whl
Algorithm Hash digest
SHA256 6bb4b2455c88b94133f29d5743900fe2ea71f5c0856628596234f837a021e74d
MD5 532f5d947d30adde174860c69b1c3db0
BLAKE2b-256 0b9f203a5b15b9c8c4071acd5fe23c43746eb1c8b09de4618b06b55d373ce6e3

See more details on using hashes here.

Provenance

The following attestation bundles were made for easy_medical_images-1.1.0-cp314-cp314-macosx_10_15_x86_64.whl:

Publisher: publish.yml on AIM-HI-Lab/EasyMedicalImages

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file easy_medical_images-1.1.0-cp313-cp313-win_amd64.whl.

File metadata

File hashes

Hashes for easy_medical_images-1.1.0-cp313-cp313-win_amd64.whl
Algorithm Hash digest
SHA256 8959ac1d7d9a9cbd0a06d111955a5a2e5c958f165de270e6fbb6570fe4c2ab15
MD5 373fc69e2df19f5697fbe33f2485a82b
BLAKE2b-256 a1a11c0fb3287d0b8599d484343320ac1737c3f2f97eb0c65d7f48a5f8a6577b

See more details on using hashes here.

Provenance

The following attestation bundles were made for easy_medical_images-1.1.0-cp313-cp313-win_amd64.whl:

Publisher: publish.yml on AIM-HI-Lab/EasyMedicalImages

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file easy_medical_images-1.1.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl.

File metadata

File hashes

Hashes for easy_medical_images-1.1.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 83cd44f1a3c5fa3c3c722b5ee99c32e47115cc5a72072dc5c9dc1af6b0e10b73
MD5 f0eeb53b165913c7db40f77691bdf12d
BLAKE2b-256 dd19a9e866cd8cdb831c6d80ca579708b505ad1fe8865ea9b7b77a6d2ac45938

See more details on using hashes here.

Provenance

The following attestation bundles were made for easy_medical_images-1.1.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl:

Publisher: publish.yml on AIM-HI-Lab/EasyMedicalImages

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file easy_medical_images-1.1.0-cp313-cp313-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for easy_medical_images-1.1.0-cp313-cp313-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 dc3893d3c51d876e154a3cc7d28fcaa06ce0c7dddf084650840677dd23623edd
MD5 e2d7a2edfc8fe0a807a756742ea467bc
BLAKE2b-256 37257ecb59ae8d438f43da60ee37c5b4a7ad44bd1c14ec7991c1283532811fe9

See more details on using hashes here.

Provenance

The following attestation bundles were made for easy_medical_images-1.1.0-cp313-cp313-macosx_11_0_arm64.whl:

Publisher: publish.yml on AIM-HI-Lab/EasyMedicalImages

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file easy_medical_images-1.1.0-cp313-cp313-macosx_10_15_x86_64.whl.

File metadata

File hashes

Hashes for easy_medical_images-1.1.0-cp313-cp313-macosx_10_15_x86_64.whl
Algorithm Hash digest
SHA256 17545bdd37c8537c3e1442e043221e36506118f1025f2ae90949e6e6cf7f3b96
MD5 60dd0ff8334591b67ba0e2d7ad32cd41
BLAKE2b-256 e83240c8b6c1fdd2322d33cba088df8de1134008992693a32cfb3a96b96fcc71

See more details on using hashes here.

Provenance

The following attestation bundles were made for easy_medical_images-1.1.0-cp313-cp313-macosx_10_15_x86_64.whl:

Publisher: publish.yml on AIM-HI-Lab/EasyMedicalImages

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file easy_medical_images-1.1.0-cp312-cp312-win_amd64.whl.

File metadata

File hashes

Hashes for easy_medical_images-1.1.0-cp312-cp312-win_amd64.whl
Algorithm Hash digest
SHA256 e311e457103fbad65bb4e7ab8b3e104cc298de9c84f8f792b739baae56def589
MD5 705466b536866107cbd230a01bc16471
BLAKE2b-256 bb3152beedfb0fea4900e11686f7f8728472739a7ad50c1f40b6c2a124a9b8ab

See more details on using hashes here.

Provenance

The following attestation bundles were made for easy_medical_images-1.1.0-cp312-cp312-win_amd64.whl:

Publisher: publish.yml on AIM-HI-Lab/EasyMedicalImages

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file easy_medical_images-1.1.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl.

File metadata

File hashes

Hashes for easy_medical_images-1.1.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 0526d1e0c6ba72e5ee70ffc13fa1fe715a8fb890a97b79e2b92cc63c2c900b4b
MD5 4d03043118a35b7830737908280c0b7f
BLAKE2b-256 e400da09ffd521a90363f943a153917a8283551a70c21734ef7f1d8a10a05a31

See more details on using hashes here.

Provenance

The following attestation bundles were made for easy_medical_images-1.1.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl:

Publisher: publish.yml on AIM-HI-Lab/EasyMedicalImages

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file easy_medical_images-1.1.0-cp312-cp312-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for easy_medical_images-1.1.0-cp312-cp312-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 b20b4deae2f6de9b6fc0f919cebe01f55fff94f49072253377e50bfce590fe59
MD5 297e94259ce8dee223e1860349f550b0
BLAKE2b-256 aa1fa4d3d73bba03dda16a1bd0a7ebee22a9e7249f5e300b6e06853d4bd417bc

See more details on using hashes here.

Provenance

The following attestation bundles were made for easy_medical_images-1.1.0-cp312-cp312-macosx_11_0_arm64.whl:

Publisher: publish.yml on AIM-HI-Lab/EasyMedicalImages

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file easy_medical_images-1.1.0-cp312-cp312-macosx_10_15_x86_64.whl.

File metadata

File hashes

Hashes for easy_medical_images-1.1.0-cp312-cp312-macosx_10_15_x86_64.whl
Algorithm Hash digest
SHA256 10fa5ce611243cc54676c0258d981d5ccaba51cc5ce79943c4ece7d5d73be2a5
MD5 f3db04bc997c91e59272b9cda96c6c63
BLAKE2b-256 e7730eb6c3287afee6046b5940e8413d1ebd99051462cb335f04c25d2245febe

See more details on using hashes here.

Provenance

The following attestation bundles were made for easy_medical_images-1.1.0-cp312-cp312-macosx_10_15_x86_64.whl:

Publisher: publish.yml on AIM-HI-Lab/EasyMedicalImages

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page