General How-To
Download data, work with annotations as dataframes, and build masks
The examples on this page assume a connected client. See Getting Started.
import mdai
DOMAIN = "public.md.ai"
ACCESS_TOKEN = "YOUR_ACCESS_TOKEN"
PROJECT_ID = "MwBe19Br" # from the annotator's Info panel
DATASET_ID = "D_ao3XWQ"
LABEL_GROUP_ID = "G_P914ZY" # for label-group examples
MODEL_ID = "M_0N3ADm" # for model-output examples
mdai_client = mdai.Client(domain=DOMAIN, access_token=ACCESS_TOKEN)Download data
Images and annotations
# All datasets and label groups
p = mdai_client.project(PROJECT_ID, path=".")
# One dataset
p = mdai_client.project(PROJECT_ID, dataset_id=DATASET_ID, path=".")
# One label group's annotations
p = mdai_client.project(PROJECT_ID, label_group_id=LABEL_GROUP_ID, path=".")Annotations only
mdai_client.project(PROJECT_ID, path=".", annotations_only=True)
mdai_client.project(PROJECT_ID, dataset_id=DATASET_ID, path=".", annotations_only=True)
mdai_client.project(PROJECT_ID, label_group_id=LABEL_GROUP_ID, path=".", annotations_only=True)These save the annotations JSON to path and return None.
Model outputs
# All models
mdai_client.download_model_outputs(PROJECT_ID, DATASET_ID, path=".")
# One model
mdai_client.download_model_outputs(PROJECT_ID, DATASET_ID, MODEL_ID, path=".")DICOM metadata
mdai_client.download_dicom_metadata(PROJECT_ID, DATASET_ID, format="json", path=".") # or format="csv"The files follow the export formats. Pass force_download=True to download again even if the files are up to date.
Annotations as a dataframe
Convert an annotations export, downloaded with the client or from the Export panel, into pandas dataframes:
results = mdai.common_utils.json_to_dataframe("mdai_public_project_MwBe19Br_annotations_labelgroup_all_2020-09-23-214038.json")
annotations = results["annotations"]
studies = results["studies"]
labels = results["labels"]
annotations.to_csv("annotations.csv", index=False)To include only some datasets, pass datasets=["D_ao3XWQ"].
Check annotations
List the users who annotated, and the labels used:
users = annotations.createdById.unique()
label_names = annotations.labelName.unique()Find exams where readers chose none, or more than one, of a set of mutually exclusive labels:
pick_one = {"Stage 1", "Stage 2", "Stage 3", "Stage 4"}
for uid, exam in annotations.groupby("StudyInstanceUID"):
found = set(exam.labelName) & pick_one
if len(found) != 1:
problem = "missing" if not found else "conflict"
print(f"{problem}: dataset {exam.dataset.iloc[0]}, exam {exam.number.iloc[0]}, {sorted(found)}")Images
from mdai import visualize
# Show images
visualize.display_images(image_ids, titles=None, cols=3, cmap="gray")
# Get an image's pixel array
pixels = visualize.load_dicom_image(image_id, to_RGB=False, rescale=True)to_RGB=True returns three channels. rescale=True rescales high-bit-depth images toward 8 bits; for exact 0–255 output, use mdai.transforms.rescale_to_8bit.
Masks
Masks for an image
With a prepared dataset, load the local annotations on an image as a stack of binary masks. Mask-mode annotations need mdai 0.16.1 or later; in earlier versions, load_mask and get_image_ground_truth fail on them. You can also use annotation_to_mask below.
masks, class_ids = visualize.load_mask(image_id, dataset) # masks: height × width × N
image = visualize.load_dicom_image(image_id, to_RGB=True, rescale=True)
overlay = visualize.apply_mask(image, masks[:, :, 0], color=(1.0, 0.0, 0.0), alpha=0.3)class_ids are the classes you set with set_labels_dict.
To get an image with all its boxes and masks, and display them:
image, class_ids, bboxes, masks = visualize.get_image_ground_truth(image_id, dataset)
visualize.display_annotations(image, bboxes, masks, class_ids)Mask from one annotation
To turn a single annotation, a row of the annotations dataframe, into a binary mask without the Project helpers:
import cv2
import numpy as np
def annotation_to_mask(row):
mask = np.zeros((int(row.height), int(row.width)), dtype=np.uint8)
data = row.data
if row.annotationMode == "bbox":
x, y = int(data["x"]), int(data["y"])
w, h = int(data["width"]), int(data["height"])
cv2.rectangle(mask, (x, y), (x + w, y + h), 1, -1)
elif row.annotationMode in ("freeform", "polygon"):
cv2.fillPoly(mask, [np.array(data["vertices"], dtype=np.int32)], 1)
elif row.annotationMode == "line":
cv2.polylines(mask, [np.array(data["vertices"], dtype=np.int32)], False, 1, 12)
elif row.annotationMode == "location":
cv2.circle(mask, (int(data["x"]), int(data["y"])), 7, 1, -1)
elif row.annotationMode == "mask":
for polygon in data["foreground"] or []:
cv2.fillPoly(mask, [np.array(polygon, dtype=np.int32)], 1)
for polygon in data["background"] or []:
cv2.fillPoly(mask, [np.array(polygon, dtype=np.int32)], 0)
return mask.astype(bool)
local = annotations[annotations.annotationMode.notna()]
mask = annotation_to_mask(local.iloc[0])Line and location annotations are drawn with a fixed thickness and radius; adjust them for your data.
Edit a dataset's annotations
To train on a modified set of annotations, edit the dataset's data and create a new Dataset from it:
from mdai.preprocess import Dataset
dataset.dataset_data["annotations"] = [
a for a in dataset.all_annotations if a["labelId"] != "L_unwanted"
]
dataset_custom = Dataset(dataset.dataset_data, dataset.images_dir)
dataset_custom.classes_dict = dataset.classes_dict
dataset_custom.prepare()Get UIDs from your original files
Map your local files to their DICOM UIDs, for example to match them with exported annotations:
from pathlib import Path
import pydicom
uids = {}
for path in Path("MY_PATH").glob("**/*.dcm"):
ds = pydicom.dcmread(path, stop_before_pixels=True)
uids[path] = (ds.StudyInstanceUID, ds.SeriesInstanceUID, ds.SOPInstanceUID)Example notebooks
- Download and import annotations: export annotations, convert them to a dataframe, and import data back.
- Create assignments and get user info, using the CLI.