--- title: Utility functions keywords: fastai sidebar: home_sidebar summary: "Utility functions for deepflash2" description: "Utility functions for deepflash2" nb_path: "nbs/06_utils.ipynb" ---
{% raw %}
{% endraw %} {% raw %}
{% endraw %}

Data Download and Archive Extraction

{% raw %}

unzip[source]

unzip(path, zip_file)

Unzip and structure archive

{% endraw %} {% raw %}
{% endraw %} {% raw %}

download_sample_data[source]

download_sample_data(base_url, name, dest, extract=False, timeout=4, show_progress=True)

{% endraw %} {% raw %}
{% endraw %}

Install packages on demand

{% raw %}

install_package[source]

install_package(package, version=None)

{% endraw %} {% raw %}
{% endraw %} {% raw %}

import_package[source]

import_package(package, version=None)

{% endraw %} {% raw %}
{% endraw %} {% raw %}

compose_albumentations[source]

compose_albumentations(gamma_limit_lower=0, gamma_limit_upper=0, CLAHE_clip_limit=0.0, brightness_limit=0, contrast_limit=0.0, distort_limit=0.0)

Compose albumentations augmentations

{% endraw %} {% raw %}
{% endraw %}

Ensembling

{% raw %}

ensemble_results[source]

ensemble_results(res_dict, file, std=False)

Combines single model predictions.

{% endraw %} {% raw %}
{% endraw %} {% raw %}

plot_results[source]

plot_results(*args, df, hastarget=False, model=None, metric_name='dice_score', unc_metric=None, figsize=(20, 20), **kwargs)

Plot images, (masks), predictions and uncertainties side-by-side.

{% endraw %} {% raw %}
{% endraw %}

Patch to show metrics in Learner

{% raw %}

Recorder.plot_metrics[source]

Recorder.plot_metrics(nrows=None, ncols=None, figsize=None, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None)

{% endraw %} {% raw %}
{% endraw %}

Pixelwise Analysis

{% raw %}

iou[source]

iou(a, b, threshold=0.5, average='macro', **kwargs)

Computes the Intersection-Over-Union metric.

{% endraw %} {% raw %}
{% endraw %} {% raw %}
test_eq(iou(mask, mask), 1)
test_eq(iou(mask, empty_mask), 0)

# Todo: add multiclass tests https://scikit-learn.org/stable/modules/generated/sklearn.metrics.jaccard_score.html
{% endraw %} {% raw %}

dice_score[source]

dice_score(*args, **kwargs)

Computes the Dice coefficient metric.

{% endraw %} {% raw %}
{% endraw %} {% raw %}
test_eq(dice_score(mask, mask), 1)
test_eq(dice_score(mask, empty_mask), 0)
{% endraw %}

ROI-wise Analysis

{% raw %}

label_mask[source]

label_mask(mask, threshold=0.5, connectivity=4, min_pixel=0, do_watershed=False, exclude_border=False)

Analyze regions and return labels

{% endraw %} {% raw %}
{% endraw %} {% raw %}
tst_lbl_a = label_mask(mask, min_pixel=0)
test_eq(tst_lbl_a.max(), 2)
test_eq(tst_lbl_a.min(), 0)
plt.imshow(tst_lbl_a);
{% endraw %} {% raw %}
tst_lbl_b = label_mask(mask, min_pixel=150)
test_eq(tst_lbl_b.max(), 1)
plt.imshow(tst_lbl_b);
{% endraw %} {% raw %}

get_instance_segmentation_metrics[source]

get_instance_segmentation_metrics(a, b, is_binary=False, thresholds=None, **kwargs)

Computes instance segmentation metric based on cellpose/stardist implementation. https://cellpose.readthedocs.io/en/latest/api.html#cellpose.metrics.average_precision

{% endraw %} {% raw %}
{% endraw %} {% raw %}
ap, tp, fp, fn = get_instance_segmentation_metrics(mask, mask, is_binary=True)
test_eq(len(ap),10)
test_eq(tp[0],2)
ap, tp, fp, fn = get_instance_segmentation_metrics(mask, empty_mask, is_binary=True, thresholds=[.5])
test_eq(len(ap),1)
test_eq(fn[0],2)
2021-11-19 08:02:38,278 [INFO] WRITING LOG OUTPUT TO /media/data/home/mag01ud/.cellpose/run.log
{% endraw %}

ROI Export to ImageJ

{% raw %}

export_roi_set[source]

export_roi_set(mask, intensity_image=None, instance_labels=False, name='RoiSet', path=Path('.'), ascending=True, min_pixel=0)

EXPERIMENTAL: Export mask regions to imageJ ROI Set

{% endraw %} {% raw %}
{% endraw %} {% raw %}
path = export_roi_set(mask)
path.unlink()
{% endraw %}

Miscellaneous

{% raw %}

calc_iterations[source]

calc_iterations(n_iter, ds_length, bs)

Calculate the number of required epochs for 'n_iter' iterations.

{% endraw %} {% raw %}
{% endraw %} {% raw %}
test_eq(calc_iterations(100, 8, 4), 50)
{% endraw %} {% raw %}

get_label_fn[source]

get_label_fn(img_path, msk_dir_path)

Infers suffix from mask name and return label_fn

{% endraw %} {% raw %}
{% endraw %} {% raw %}

save_mask[source]

save_mask(mask, path, filetype='.png')

{% endraw %} {% raw %}
def save_mask(mask, path, filetype='.png'):
    mask = mask.astype(np.uint8) if np.max(mask)>1 else (mask*255).astype(np.uint8)
    imageio.imsave(path.with_suffix(filetype), mask)
{% endraw %} {% raw %}

save_unc[source]

save_unc(unc, path, filetype='.png')

{% endraw %} {% raw %}
def save_unc(unc, path, filetype='.png'):
    unc = (unc/unc.max()*255).astype(np.uint8)
    imageio.imsave(path.with_suffix(filetype), unc)
{% endraw %}