From 663861392b8dab0a619713a051c36f3d5bcabe7e Mon Sep 17 00:00:00 2001 From: Jirka Borovec Date: Thu, 9 Apr 2020 12:29:24 +0200 Subject: [PATCH] strict & fixing Docs (#24) * fix sphinx docs * sphinx versions * fix sphinx warn * optimize imports * add doc ignores * fix docs paths * fix notebook * docs: drop SVG & GIF --- MANIFEST.in | 2 +- README.md | 33 ++++---- circle.yml | 26 +++++- docs/requirements.txt | 5 +- .../source/_figures}/imag-disk-20_gmm.jpg | Bin .../source/_figures}/imag-disk-20_train.jpg | Bin .../source/_figures}/insitu7544_ellipses.jpg | Bin .../source/_figures}/insitu7545.jpg | Bin .../_figures}/insitu7545_RG2SP-gc-mm.png | Bin .../_figures}/insitu7545_RG2SP_animation.gif | Bin .../_figures}/insitu7545_center_clusters.jpg | Bin .../_figures}/insitu7545_ellipse_fit.png | Bin .../source/_figures}/insitu7545_gc.png | Bin .../_figures}/insitu7545_user-annot-segm.jpg | Bin .../_figures}/schema_slic-fts-clf-gc.jpg | Bin .../_figures}/segm-visual_D03_sy04_100x.jpg | Bin .../source/_figures}/visual_img_43_debug.jpg | Bin docs/source/conf.py | 78 +++++++++++------- docs/source/examples.rst | 2 +- .../gui_annot_center_correction.py | 13 +-- .../run_center_candidate_training.py | 10 +-- .../run_center_clustering.py | 6 +- .../run_center_evaluation.py | 8 +- .../run_center_prediction.py | 4 +- .../run_create_annotation.py | 5 +- .../run_RG2Sp_estim_shape-models.py | 6 +- .../run_cut_segmented_objects.py | 4 +- .../run_egg_swap_orientation.py | 4 +- .../run_ellipse_annot_match.py | 8 +- .../run_ellipse_cut_scale.py | 6 +- .../run_export_user-annot-segm.py | 6 +- .../run_ovary_egg-segmentation.py | 7 +- .../run_ovary_segm_evaluation.py | 7 +- .../run_compute_stat_annot_segm.py | 5 +- .../run_eval_superpixels.py | 5 +- .../run_segm_slic_classif_graphcut.py | 7 +- .../run_segm_slic_model_graphcut.py | 11 +-- .../run_image_color_quantization.py | 6 +- .../run_image_convert_label_color.py | 6 +- .../run_overlap_images_segms.py | 7 +- .../run_segm_annot_inpaint.py | 6 +- .../run_segm_annot_relabel.py | 6 +- imsegm/annotation.py | 4 +- imsegm/classification.py | 13 +-- imsegm/descriptors.py | 23 +++--- imsegm/ellipse_fitting.py | 12 ++- imsegm/graph_cuts.py | 15 ++-- imsegm/labeling.py | 2 +- imsegm/pipelines.py | 15 ++-- imsegm/region_growing.py | 3 +- imsegm/utilities/data_io.py | 29 +++---- imsegm/utilities/data_samples.py | 2 +- imsegm/utilities/drawing.py | 11 +-- imsegm/utilities/experiments.py | 8 +- notebooks/RG2Sp_model_region-grow.ipynb | 2 +- notebooks/RG2Sp_region-growing.ipynb | 2 +- tests/test_classification.py | 2 +- tests/test_descriptors.py | 4 +- tests/test_ellipse-fitting.py | 4 +- tests/test_graph-cut.py | 2 +- tests/test_labeling.py | 4 +- tests/test_pipelines.py | 2 +- tests/test_region-growing.py | 7 +- tests/test_superpixels.py | 4 +- tests/test_utilities.py | 2 +- 65 files changed, 257 insertions(+), 214 deletions(-) rename {figures => docs/source/_figures}/imag-disk-20_gmm.jpg (100%) rename {figures => docs/source/_figures}/imag-disk-20_train.jpg (100%) rename {figures => docs/source/_figures}/insitu7544_ellipses.jpg (100%) rename {figures => docs/source/_figures}/insitu7545.jpg (100%) rename {figures => docs/source/_figures}/insitu7545_RG2SP-gc-mm.png (100%) rename {figures => docs/source/_figures}/insitu7545_RG2SP_animation.gif (100%) rename {figures => docs/source/_figures}/insitu7545_center_clusters.jpg (100%) rename {figures => docs/source/_figures}/insitu7545_ellipse_fit.png (100%) rename {figures => docs/source/_figures}/insitu7545_gc.png (100%) rename {figures => docs/source/_figures}/insitu7545_user-annot-segm.jpg (100%) rename {figures => docs/source/_figures}/schema_slic-fts-clf-gc.jpg (100%) rename {figures => docs/source/_figures}/segm-visual_D03_sy04_100x.jpg (100%) rename {figures => docs/source/_figures}/visual_img_43_debug.jpg (100%) diff --git a/MANIFEST.in b/MANIFEST.in index 9a817a8f..b8889c26 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -34,7 +34,7 @@ recursive-include experiments_* *.py *.yml recursive-include handling_annotations *.py # Include the figures -recursive-include figures *.gif *.jpg *.png +recursive-include docs/source/_figures *.gif *.jpg *.png # Include the sample images include data_images/others/lena.png diff --git a/README.md b/README.md index 548d3e20..0d3d5372 100755 --- a/README.md +++ b/README.md @@ -17,9 +17,11 @@ ## Superpixel segmentation with GraphCut regularisation -Image segmentation is widely used as an initial phase of many image processing tasks in computer vision and image analysis. Many recent segmentation methods use superpixels because they reduce the size of the segmentation problem by order of magnitude. Also, features on superpixels are much more robust than features on pixels only. We use spatial regularisation on superpixels to make segmented regions more compact. The segmentation pipeline comprises (i) computation of superpixels; (ii) extraction of descriptors such as colour and texture; (iii) soft classification, using a standard classifier for supervised learning, or the Gaussian Mixture Model for unsupervised learning; (iv) final segmentation using Graph Cut. We use this segmentation pipeline on real-world applications in medical imaging (see a sample [images](./data_images)). We also show that [unsupervised segmentation](notebooks/segment-2d_slic-fts-clust-gc.ipynb) is sufficient for some situations, and provides similar results to those obtained using [trained segmentation](notebooks/segment-2d_slic-fts-classif-gc.ipynb). +Image segmentation is widely used as an initial phase of many image processing tasks in computer vision and image analysis. Many recent segmentation methods use superpixels because they reduce the size of the segmentation problem by order of magnitude. Also, features on superpixels are much more robust than features on pixels only. We use spatial regularisation on superpixels to make segmented regions more compact. The segmentation pipeline comprises (i) computation of superpixels; (ii) extraction of descriptors such as colour and texture; (iii) soft classification, using a standard classifier for supervised learning, or the Gaussian Mixture Model for unsupervised learning; (iv) final segmentation using Graph Cut. We use this segmentation pipeline on real-world applications in medical imaging (see [sample images](data_images/). + We also show that [unsupervised segmentation](notebooks/segment-2d_slic-fts-clust-gc.ipynb) is sufficient for some situations, + and provides similar results to those obtained using [trained segmentation](notebooks/segment-2d_slic-fts-classif-gc.ipynb). -![schema](figures/schema_slic-fts-clf-gc.jpg) +![schema](docs/source/_figures/schema_slic-fts-clf-gc.jpg) **Sample ipython notebooks:** * [Supervised segmentation](notebooks/segment-2d_slic-fts-classif-gc.ipynb) requires training annotation @@ -28,15 +30,16 @@ Image segmentation is widely used as an initial phase of many image processing t **Illustration** -![input image](figures/insitu7545.jpg) -![segmentation](figures/insitu7545_gc.png) +![input image](docs/source/_figures/insitu7545.jpg) +![segmentation](docs/source/_figures/insitu7545_gc.png) Reference: _Borovec J., Svihlik J., Kybic J., Habart D. (2017). **Supervised and unsupervised segmentation using superpixels, model estimation, and Graph Cut.** In: Journal of Electronic Imaging._ ## Object centre detection and Ellipse approximation -An image processing pipeline to detect and localize Drosophila egg chambers that consists of the following steps: (i) superpixel-based image segmentation into relevant tissue classes (see above); (ii) detection of egg center candidates using label histograms and ray features; (iii) clustering of center candidates and; (iv) area-based maximum likelihood ellipse model fitting. See our [Poster](http://cmp.felk.cvut.cz/~borovji3/documents/poster-MLMI2017.compressed.pdf) related to this work. +An image processing pipeline to detect and localize Drosophila egg chambers that consists of the following steps: (i) superpixel-based image segmentation into relevant tissue classes (see above); (ii) detection of egg center candidates using label histograms and ray features; (iii) clustering of center candidates and; (iv) area-based maximum likelihood ellipse model fitting. + See our [Poster](http://cmp.felk.cvut.cz/~borovji3/documents/poster-MLMI2017.compressed.pdf) related to this work. **Sample ipython notebooks:** * [Center detection](notebooks/egg-center_candidates-clustering.ipynb) consists of center candidate training and prediction, and candidate clustering. @@ -44,8 +47,8 @@ An image processing pipeline to detect and localize Drosophila egg chambers that **Illustration** -![estimated centres](figures/insitu7545_center_clusters.jpg) -![ellipse fitting](figures/insitu7545_ellipse_fit.png) +![estimated centres](docs/source/_figures/insitu7545_center_clusters.jpg) +![ellipse fitting](docs/source/_figures/insitu7545_ellipse_fit.png) Reference: _Borovec J., Kybic J., Nava R. (2017) **Detection and Localization of Drosophila Egg Chambers in Microscopy Images.** In: Machine Learning in Medical Imaging._ @@ -60,8 +63,8 @@ Region growing is a classical image segmentation method based on hierarchical re **Illustration** -![growing RG](figures/insitu7545_RG2SP_animation.gif) -![ellipse fitting](figures/insitu7545_RG2SP-gc-mm.png) +![growing RG](docs/source/_figures/insitu7545_RG2SP_animation.gif) +![ellipse fitting](docs/source/_figures/insitu7545_RG2SP-gc-mm.png) Reference: _Borovec J., Kybic J., Sugimoto, A. (2017). **Region growing using superpixels with learned shape prior.** In: Journal of Electronic Imaging._ @@ -164,7 +167,7 @@ We introduce some useful tools for work with image annotation and segmentation. ### Semantic (un/semi)supervised segmentation We utilise (un)supervised segmentation according to given training examples or some expectations. -![vusial debug](figures/visual_img_43_debug.jpg) +![vusial debug](docs/source/_figures/visual_img_43_debug.jpg) * Evaluate superpixels (with given SLIC parameters) quality against given segmentation. It helps to find out the best SLIC configuration. ```bash @@ -188,7 +191,7 @@ We utilise (un)supervised segmentation according to given training examples or s -cfg ./experiments_segmentation/sample_config.yml \ -o ./results -n langIsl --nb_classes 3 --visual --nb_workers 2 ``` - ![unsupervised](figures/imag-disk-20_gmm.jpg) + ![unsupervised](docs/source/_figures/imag-disk-20_gmm.jpg) * Perform **Supervised** segmentation with afterwards evaluation. ```bash python experiments_segmentation/run_segm_slic_classif_graphcut.py \ @@ -197,7 +200,7 @@ We utilise (un)supervised segmentation according to given training examples or s --path_config ./experiments_segmentation/sample_config.yml \ -o ./results -n Ovary --img_type 2d_split --visual --nb_workers 2 ``` - ![supervised](figures/imag-disk-20_train.jpg) + ![supervised](docs/source/_figures/imag-disk-20_train.jpg) * Perform **Semi-Supervised** is using the the supervised pipeline with not fully annotated images. * For both experiment you can evaluate segmentation results. ```bash @@ -207,7 +210,7 @@ We utilise (un)supervised segmentation according to given training examples or s -i "./data_images/drosophila_ovary_slice/image/*.jpg" \ -o ./results/evaluation --visual ``` - ![vusial](figures/segm-visual_D03_sy04_100x.jpg) + ![vusial](docs/source/_figures/segm-visual_D03_sy04_100x.jpg) The previous two (un)segmentation accept [configuration file](experiments_segmentation/sample_config.yml) (YAML) by parameter `-cfg` with some extra parameters which was not passed in arguments, for instance: ```yaml @@ -283,7 +286,7 @@ In general, the input is a formatted list (CSV file) of input images and annotat -out ~/Medical-drosophila/RESULTS/atlas_datasets/ovary_images/stage_3 ``` -![ellipse fitting](figures/insitu7544_ellipses.jpg) +![ellipse fitting](docs/source/_figures/insitu7544_ellipses.jpg) ### Region growing with a shape prior @@ -333,7 +336,7 @@ pip install --user git+https://github.com/Borda/morph-snakes.git ```bash python experiments_ovary_detect/run_export_user-annot-segm.py ``` - ![user-annnot](figures/insitu7545_user-annot-segm.jpg) + ![user-annnot](docs/source/_figures/insitu7545_user-annot-segm.jpg) --- diff --git a/circle.yml b/circle.yml index 4737dbea..c6e33fdf 100755 --- a/circle.yml +++ b/circle.yml @@ -45,8 +45,12 @@ references: command: | sudo apt-get install pandoc sudo pip install -r docs/requirements.txt - # sphinx-apidoc -o ./docs/source ./imsegm ./tests/* --force --follow-links - cd docs; make html + # sphinx-apidoc -o ./docs/source ./imsegm **/test_* --force --follow-links + python setup.py build_ext --inplace + cd docs + make html --debug --jobs 2 SPHINXOPTS="-W" + make latexpdf + jobs: Py3-Tests: @@ -61,8 +65,6 @@ jobs: - *build_project # TESTING - *test_coverage - # DOCUMENTATION - - *make_docs # PASSING - run: @@ -106,6 +108,21 @@ jobs: - image: circleci/python:2.7 steps: *steps_expt + Build-Docs: + docker: + - image: circleci/python:3.6 + steps: + - checkout + - run: + name: TexLive + command: | + sudo apt-get update -qq + sudo apt-get install -y imagemagick ghostscript latexmk texlive texlive-latex-recommended texlive-fonts-recommended texlive-formats-extra + # INSTALLATION + - *install_pips + # DOCUMENTATION + - *make_docs + workflows: version: 2 build: @@ -114,3 +131,4 @@ workflows: - Py3-Tests - Py2-Experiments - Py3-Experiments + - Build-Docs diff --git a/docs/requirements.txt b/docs/requirements.txt index 392d1213..2f0f7f67 100644 --- a/docs/requirements.txt +++ b/docs/requirements.txt @@ -1,6 +1,7 @@ -sphinx>=1.4 +sphinx>=2.0, <3.0 recommonmark # fails with badges m2r # fails with multi-line text nbsphinx pandoc -docutils<0.15 # higher version breaks py2 \ No newline at end of file +docutils<0.15 # higher version breaks py2 +ipython \ No newline at end of file diff --git a/figures/imag-disk-20_gmm.jpg b/docs/source/_figures/imag-disk-20_gmm.jpg similarity index 100% rename from figures/imag-disk-20_gmm.jpg rename to docs/source/_figures/imag-disk-20_gmm.jpg diff --git a/figures/imag-disk-20_train.jpg b/docs/source/_figures/imag-disk-20_train.jpg similarity index 100% rename from figures/imag-disk-20_train.jpg rename to docs/source/_figures/imag-disk-20_train.jpg diff --git a/figures/insitu7544_ellipses.jpg b/docs/source/_figures/insitu7544_ellipses.jpg similarity index 100% rename from figures/insitu7544_ellipses.jpg rename to docs/source/_figures/insitu7544_ellipses.jpg diff --git a/figures/insitu7545.jpg b/docs/source/_figures/insitu7545.jpg similarity index 100% rename from figures/insitu7545.jpg rename to docs/source/_figures/insitu7545.jpg diff --git a/figures/insitu7545_RG2SP-gc-mm.png b/docs/source/_figures/insitu7545_RG2SP-gc-mm.png similarity index 100% rename from figures/insitu7545_RG2SP-gc-mm.png rename to docs/source/_figures/insitu7545_RG2SP-gc-mm.png diff --git a/figures/insitu7545_RG2SP_animation.gif b/docs/source/_figures/insitu7545_RG2SP_animation.gif similarity index 100% rename from figures/insitu7545_RG2SP_animation.gif rename to docs/source/_figures/insitu7545_RG2SP_animation.gif diff --git a/figures/insitu7545_center_clusters.jpg b/docs/source/_figures/insitu7545_center_clusters.jpg similarity index 100% rename from figures/insitu7545_center_clusters.jpg rename to docs/source/_figures/insitu7545_center_clusters.jpg diff --git a/figures/insitu7545_ellipse_fit.png b/docs/source/_figures/insitu7545_ellipse_fit.png similarity index 100% rename from figures/insitu7545_ellipse_fit.png rename to docs/source/_figures/insitu7545_ellipse_fit.png diff --git a/figures/insitu7545_gc.png b/docs/source/_figures/insitu7545_gc.png similarity index 100% rename from figures/insitu7545_gc.png rename to docs/source/_figures/insitu7545_gc.png diff --git a/figures/insitu7545_user-annot-segm.jpg b/docs/source/_figures/insitu7545_user-annot-segm.jpg similarity index 100% rename from figures/insitu7545_user-annot-segm.jpg rename to docs/source/_figures/insitu7545_user-annot-segm.jpg diff --git a/figures/schema_slic-fts-clf-gc.jpg b/docs/source/_figures/schema_slic-fts-clf-gc.jpg similarity index 100% rename from figures/schema_slic-fts-clf-gc.jpg rename to docs/source/_figures/schema_slic-fts-clf-gc.jpg diff --git a/figures/segm-visual_D03_sy04_100x.jpg b/docs/source/_figures/segm-visual_D03_sy04_100x.jpg similarity index 100% rename from figures/segm-visual_D03_sy04_100x.jpg rename to docs/source/_figures/segm-visual_D03_sy04_100x.jpg diff --git a/figures/visual_img_43_debug.jpg b/docs/source/_figures/visual_img_43_debug.jpg similarity index 100% rename from figures/visual_img_43_debug.jpg rename to docs/source/_figures/visual_img_43_debug.jpg diff --git a/docs/source/conf.py b/docs/source/conf.py index 69d01881..7dd3ea80 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -12,11 +12,12 @@ # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. -import os -import sys import glob -import shutil import inspect +import os +import shutil +import sys +import re import m2r @@ -26,6 +27,22 @@ import imsegm # noqa: E402 +# -- Project information ----------------------------------------------------- + +project = 'ImSegm' +copyright = imsegm.__copyright__ +author = imsegm.__author__ + +# The short X.Y version +version = imsegm.__version__ +# The full version, including alpha/beta/rc tags +release = imsegm.__version__ + +# Options for the linkcode extension +# ---------------------------------- +github_user = 'Borda' +github_repo = 'pyImSegm' + # -- Project documents ------------------------------------------------------- # export the documentation @@ -38,29 +55,25 @@ with open(os.path.join(PATH_ROOT, 'README.md'), 'r') as fp: readme = fp.read() # replace all paths to relative -for ndir in (os.path.basename(p) for p in glob.glob(os.path.join(PATH_ROOT, '*')) - if os.path.isdir(p)): - readme = readme.replace('](%s/' % ndir, '](%s/%s/' % (PATH_ROOT, ndir)) +readme = readme.replace('](docs/source/', '](') +readme = re.sub(r' \[(.*)\]\((?!http)(.*)\)', + r' [\1](https://github.com/%s/%s/blob/master/\2)' % (github_user, github_repo), + readme) +# TODO: temp fix removing SVG badges and GIF, because PDF cannot show them +readme = re.sub(r'(\[!\[.*\))', '', readme) +readme = re.sub(r'(!\[.*.gif\))', '', readme) +# for dir_name in (os.path.basename(p) for p in glob.glob(os.path.join(PATH_ROOT, '*')) +# if os.path.isdir(p)): +# readme = readme.replace('](%s/' % dir_name, '](%s/%s/' % (PATH_ROOT, dir_name)) with open('readme.md', 'w') as fp: fp.write(readme) -# -- Project information ----------------------------------------------------- - -project = 'ImSegm' -copyright = imsegm.__copyright__ -author = imsegm.__author__ - -# The short X.Y version -version = imsegm.__version__ -# The full version, including alpha/beta/rc tags -release = imsegm.__version__ - # -- General configuration --------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = '1.4' +needs_sphinx = '2.2' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom @@ -75,6 +88,7 @@ 'sphinx.ext.linkcode', 'sphinx.ext.napoleon', 'sphinx.ext.autosummary', + # 'sphinxcontrib.rsvgconverter' 'recommonmark', # 'm2r', 'nbsphinx', @@ -109,7 +123,13 @@ # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. -exclude_patterns = ['*tests.*', '*.test_*'] +exclude_patterns = [ + 'data_images', + '*tests.*', '*.test_*', + '*.so', '*.dll', + 'modules.rst', + '*/transform-img-plane_inter-circle.ipynb' +] # The name of the Pygments (syntax highlighting) style to use. pygments_style = None @@ -131,7 +151,7 @@ # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] +html_static_path = ['_figures'] # , '_static', 'notebooks' # Custom sidebar templates, must be a dictionary that maps document names # to template names. @@ -255,12 +275,12 @@ def setup(app): # copy all notebooks to local folder -path_nbs = os.path.join(PATH_HERE, 'notebooks') -if not os.path.isdir(path_nbs): - os.mkdir(path_nbs) -for path_ipynb in glob.glob(os.path.join(PATH_ROOT, 'notebooks', '*.ipynb')): - path_ipynb2 = os.path.join(path_nbs, os.path.basename(path_ipynb)) - shutil.copy(path_ipynb, path_ipynb2) +path_docs_nbs = os.path.join(PATH_HERE, 'notebooks') +if not os.path.isdir(path_docs_nbs): + os.mkdir(path_docs_nbs) +for path_ipynb_in in glob.glob(os.path.join(PATH_ROOT, 'notebooks', '*.ipynb')): + path_ipynb_new = os.path.join(path_docs_nbs, os.path.basename(path_ipynb_in)) + shutil.copy(path_ipynb_in, path_ipynb_new) # Ignoring Third-party packages @@ -278,12 +298,6 @@ def setup(app): autodoc_mock_imports = MOCK_MODULES + ['sklearn', 'skimage', 'gco', 'yaml'] -# Options for the linkcode extension -# ---------------------------------- -github_user = 'Borda' -github_repo = 'pyImSegm' - - # Resolve function # This function is used to populate the (source) links in the API def linkcode_resolve(domain, info): diff --git a/docs/source/examples.rst b/docs/source/examples.rst index 57fa5a41..1a8bc357 100644 --- a/docs/source/examples.rst +++ b/docs/source/examples.rst @@ -13,4 +13,4 @@ Examples notebooks/egg_segment_graphcut.ipynb notebooks/egg-center_candidates-clustering.ipynb - notebooks/egg-detect_ellipse-fitting.ipynb \ No newline at end of file + notebooks/egg-detect_ellipse-fitting.ipynb diff --git a/experiments_ovary_centres/gui_annot_center_correction.py b/experiments_ovary_centres/gui_annot_center_correction.py index 00f19686..587c53c6 100755 --- a/experiments_ovary_centres/gui_annot_center_correction.py +++ b/experiments_ovary_centres/gui_annot_center_correction.py @@ -26,18 +26,19 @@ Copyright (C) 2016 Jiri Borovec """ -import os -import sys +import argparse import glob import logging -import argparse +import os +import sys +# from planar import line as pl_line +import matplotlib +import matplotlib.pylab as plt import numpy as np import pandas as pd -import matplotlib.pylab as plt from scipy import ndimage, spatial -# from planar import line as pl_line -import matplotlib + matplotlib.use('GTKAgg') # or >> matplotlib.rcsetup.all_backends diff --git a/experiments_ovary_centres/run_center_candidate_training.py b/experiments_ovary_centres/run_center_candidate_training.py index 9fc09002..61db0dd3 100755 --- a/experiments_ovary_centres/run_center_candidate_training.py +++ b/experiments_ovary_centres/run_center_candidate_training.py @@ -24,18 +24,18 @@ Copyright (C) 2016-2017 Jiri Borovec """ +import argparse +import logging import os import sys -import logging -import argparse from functools import partial -import tqdm -import pandas as pd +import matplotlib import numpy as np +import pandas as pd +import tqdm from scipy import spatial -import matplotlib if os.environ.get('DISPLAY', '') == '' and matplotlib.rcParams['backend'] != 'agg': print('No display found. Using non-interactive Agg backend.') matplotlib.use('Agg') diff --git a/experiments_ovary_centres/run_center_clustering.py b/experiments_ovary_centres/run_center_clustering.py index 8179f936..94157515 100755 --- a/experiments_ovary_centres/run_center_clustering.py +++ b/experiments_ovary_centres/run_center_clustering.py @@ -6,16 +6,16 @@ Copyright (C) 2017 Jiri Borovec """ +import logging import os import sys -import logging from functools import partial -import pandas as pd +import matplotlib import numpy as np +import pandas as pd from sklearn import cluster -import matplotlib if os.environ.get('DISPLAY', '') == '' and matplotlib.rcParams['backend'] != 'agg': print('No display found. Using non-interactive Agg backend.') matplotlib.use('Agg') diff --git a/experiments_ovary_centres/run_center_evaluation.py b/experiments_ovary_centres/run_center_evaluation.py index a0d46c77..a3341495 100755 --- a/experiments_ovary_centres/run_center_evaluation.py +++ b/experiments_ovary_centres/run_center_evaluation.py @@ -13,18 +13,18 @@ Copyright (C) 2016-2017 Jiri Borovec """ +import gc +import logging import os import sys import time -import logging -import gc from functools import partial -import pandas as pd +import matplotlib import numpy as np +import pandas as pd from scipy import ndimage -import matplotlib if os.environ.get('DISPLAY', '') == '' and matplotlib.rcParams['backend'] != 'agg': print('No display found. Using non-interactive Agg backend.') matplotlib.use('Agg') diff --git a/experiments_ovary_centres/run_center_prediction.py b/experiments_ovary_centres/run_center_prediction.py index 7e49ae48..35447e2e 100644 --- a/experiments_ovary_centres/run_center_prediction.py +++ b/experiments_ovary_centres/run_center_prediction.py @@ -13,11 +13,11 @@ Copyright (C) 2016 Jiri Borovec """ +import gc +import logging import os import sys import time -import gc -import logging from functools import partial import pandas as pd diff --git a/experiments_ovary_centres/run_create_annotation.py b/experiments_ovary_centres/run_create_annotation.py index cf92d1ca..5931858c 100644 --- a/experiments_ovary_centres/run_create_annotation.py +++ b/experiments_ovary_centres/run_create_annotation.py @@ -21,10 +21,10 @@ Copyright (C) 2015-2016 Jiri Borovec """ -import os -import sys import glob import logging +import os +import sys from functools import partial import numpy as np @@ -32,7 +32,6 @@ from scipy import ndimage from skimage import morphology, measure, draw - sys.path += [os.path.abspath('.'), os.path.abspath('..')] # Add path to root import imsegm.utilities.data_io as tl_data import imsegm.utilities.experiments as tl_expt diff --git a/experiments_ovary_detect/run_RG2Sp_estim_shape-models.py b/experiments_ovary_detect/run_RG2Sp_estim_shape-models.py index 7c799baf..45df8c8f 100644 --- a/experiments_ovary_detect/run_RG2Sp_estim_shape-models.py +++ b/experiments_ovary_detect/run_RG2Sp_estim_shape-models.py @@ -10,12 +10,12 @@ Copyright (C) 2016-2017 Jiri Borovec """ -import os -import sys +import argparse import glob import logging +import os import pickle -import argparse +import sys import numpy as np import pandas as pd diff --git a/experiments_ovary_detect/run_cut_segmented_objects.py b/experiments_ovary_detect/run_cut_segmented_objects.py index 666f5f6a..7936733d 100644 --- a/experiments_ovary_detect/run_cut_segmented_objects.py +++ b/experiments_ovary_detect/run_cut_segmented_objects.py @@ -10,10 +10,10 @@ """ +import argparse +import logging import os import sys -import logging -import argparse from functools import partial import numpy as np diff --git a/experiments_ovary_detect/run_egg_swap_orientation.py b/experiments_ovary_detect/run_egg_swap_orientation.py index 5592c53b..ac628f50 100644 --- a/experiments_ovary_detect/run_egg_swap_orientation.py +++ b/experiments_ovary_detect/run_egg_swap_orientation.py @@ -10,10 +10,10 @@ Copyright (C) 2016-2018 Jiri Borovec """ -import os -import sys import glob import logging +import os +import sys from functools import partial import numpy as np diff --git a/experiments_ovary_detect/run_ellipse_annot_match.py b/experiments_ovary_detect/run_ellipse_annot_match.py index 25804660..410ca128 100644 --- a/experiments_ovary_detect/run_ellipse_annot_match.py +++ b/experiments_ovary_detect/run_ellipse_annot_match.py @@ -12,15 +12,15 @@ Copyright (C) 2016-2018 Jiri Borovec """ -import os -import sys +import argparse import glob import logging -import argparse +import os +import sys from functools import partial -import pandas as pd import numpy as np +import pandas as pd sys.path += [os.path.abspath('.'), os.path.abspath('..')] # Add path to root import imsegm.utilities.data_io as tl_data diff --git a/experiments_ovary_detect/run_ellipse_cut_scale.py b/experiments_ovary_detect/run_ellipse_cut_scale.py index e3e76894..76609487 100644 --- a/experiments_ovary_detect/run_ellipse_cut_scale.py +++ b/experiments_ovary_detect/run_ellipse_cut_scale.py @@ -11,14 +11,14 @@ Copyright (C) 2016-2018 Jiri Borovec """ -import os -import sys import glob import logging +import os +import sys from functools import partial -import pandas as pd import numpy as np +import pandas as pd from skimage import transform sys.path += [os.path.abspath('.'), os.path.abspath('..')] # Add path to root diff --git a/experiments_ovary_detect/run_export_user-annot-segm.py b/experiments_ovary_detect/run_export_user-annot-segm.py index 5404af44..f1a1af54 100644 --- a/experiments_ovary_detect/run_export_user-annot-segm.py +++ b/experiments_ovary_detect/run_export_user-annot-segm.py @@ -15,14 +15,14 @@ Copyright (C) 2016-2017 Jiri Borovec """ +import argparse +import logging import os import sys -import logging -import argparse from functools import partial - import matplotlib + if os.environ.get('DISPLAY', '') == '' and matplotlib.rcParams['backend'] != 'agg': print('No display found. Using non-interactive Agg backend.') matplotlib.use('Agg') diff --git a/experiments_ovary_detect/run_ovary_egg-segmentation.py b/experiments_ovary_detect/run_ovary_egg-segmentation.py index 3254cf8a..70910a08 100755 --- a/experiments_ovary_detect/run_ovary_egg-segmentation.py +++ b/experiments_ovary_detect/run_ovary_egg-segmentation.py @@ -23,15 +23,16 @@ Copyright (C) 2016-2017 Jiri Borovec """ -import os -import sys -import time import argparse import logging +import os import pickle +import sys +import time from functools import partial import matplotlib + if os.environ.get('DISPLAY', '') == '' and matplotlib.rcParams['backend'] != 'agg': print('No display found. Using non-interactive Agg backend.') matplotlib.use('Agg') diff --git a/experiments_ovary_detect/run_ovary_segm_evaluation.py b/experiments_ovary_detect/run_ovary_segm_evaluation.py index ce3303bd..6fe0c43d 100755 --- a/experiments_ovary_detect/run_ovary_segm_evaluation.py +++ b/experiments_ovary_detect/run_ovary_segm_evaluation.py @@ -13,14 +13,15 @@ Copyright (C) 2016 Jiri Borovec """ -import os -import sys +import argparse import glob import logging -import argparse +import os +import sys from functools import partial import matplotlib + if os.environ.get('DISPLAY', '') == '' and matplotlib.rcParams['backend'] != 'agg': print('No display found. Using non-interactive Agg backend.') matplotlib.use('Agg') diff --git a/experiments_segmentation/run_compute_stat_annot_segm.py b/experiments_segmentation/run_compute_stat_annot_segm.py index eee2c0b0..5c48f624 100644 --- a/experiments_segmentation/run_compute_stat_annot_segm.py +++ b/experiments_segmentation/run_compute_stat_annot_segm.py @@ -13,13 +13,14 @@ Copyright (C) 2016-2018 Jiri Borovec """ +import argparse +import logging import os import sys -import logging -import argparse from functools import partial import matplotlib + if os.environ.get('DISPLAY', '') == '' and matplotlib.rcParams['backend'] != 'agg': print('No display found. Using non-interactive Agg backend.') matplotlib.use('Agg') diff --git a/experiments_segmentation/run_eval_superpixels.py b/experiments_segmentation/run_eval_superpixels.py index 75973c91..cb4e2f7d 100644 --- a/experiments_segmentation/run_eval_superpixels.py +++ b/experiments_segmentation/run_eval_superpixels.py @@ -14,13 +14,14 @@ Copyright (C) 2017 Jiri Borovec """ -import os -import sys import argparse import logging +import os +import sys from functools import partial import matplotlib + if os.environ.get('DISPLAY', '') == '' and matplotlib.rcParams['backend'] != 'agg': print('No display found. Using non-interactive Agg backend.') matplotlib.use('Agg') diff --git a/experiments_segmentation/run_segm_slic_classif_graphcut.py b/experiments_segmentation/run_segm_slic_classif_graphcut.py index 9836b209..382b7385 100644 --- a/experiments_segmentation/run_segm_slic_classif_graphcut.py +++ b/experiments_segmentation/run_segm_slic_classif_graphcut.py @@ -28,15 +28,16 @@ Copyright (C) 2016-2018 Jiri Borovec """ +import gc +import glob +import logging import os import sys -import logging -import glob import time -import gc from functools import partial import matplotlib + if os.environ.get('DISPLAY', '') == '': print('No display found. Using non-interactive Agg backend.') matplotlib.use('Agg') diff --git a/experiments_segmentation/run_segm_slic_model_graphcut.py b/experiments_segmentation/run_segm_slic_model_graphcut.py index e91e746e..556d58e9 100644 --- a/experiments_segmentation/run_segm_slic_model_graphcut.py +++ b/experiments_segmentation/run_segm_slic_model_graphcut.py @@ -21,17 +21,18 @@ Copyright (C) 2016-2018 Jiri Borovec """ -import os -import sys -import glob -import pickle import argparse +import gc +import glob import logging +import os +import pickle +import sys import time -import gc from functools import partial import matplotlib + if os.environ.get('DISPLAY', '') == '': print('No display found. Using non-interactive Agg backend.') matplotlib.use('Agg') diff --git a/handling_annotations/run_image_color_quantization.py b/handling_annotations/run_image_color_quantization.py index c61a4a02..17448048 100644 --- a/handling_annotations/run_image_color_quantization.py +++ b/handling_annotations/run_image_color_quantization.py @@ -16,11 +16,11 @@ """ -import os -import sys +import argparse import glob import logging -import argparse +import os +import sys from functools import partial import numpy as np diff --git a/handling_annotations/run_image_convert_label_color.py b/handling_annotations/run_image_convert_label_color.py index 2901b39c..ae00e401 100644 --- a/handling_annotations/run_image_convert_label_color.py +++ b/handling_annotations/run_image_convert_label_color.py @@ -12,12 +12,12 @@ """ -import os -import sys +import argparse import glob import json import logging -import argparse +import os +import sys from functools import partial import numpy as np diff --git a/handling_annotations/run_overlap_images_segms.py b/handling_annotations/run_overlap_images_segms.py index 4b3d7a10..54c78bf5 100644 --- a/handling_annotations/run_overlap_images_segms.py +++ b/handling_annotations/run_overlap_images_segms.py @@ -13,14 +13,15 @@ """ -import os -import sys +import argparse import glob import logging -import argparse +import os +import sys from functools import partial import matplotlib + if os.environ.get('DISPLAY', '') == '' and matplotlib.rcParams['backend'] != 'agg': print('No display found. Using non-interactive Agg backend.') matplotlib.use('Agg') diff --git a/handling_annotations/run_segm_annot_inpaint.py b/handling_annotations/run_segm_annot_inpaint.py index 8925ee9e..9e1a383a 100644 --- a/handling_annotations/run_segm_annot_inpaint.py +++ b/handling_annotations/run_segm_annot_inpaint.py @@ -11,11 +11,11 @@ """ -import os -import sys +import argparse import glob import logging -import argparse +import os +import sys from functools import partial import numpy as np diff --git a/handling_annotations/run_segm_annot_relabel.py b/handling_annotations/run_segm_annot_relabel.py index 66609b35..247230bd 100644 --- a/handling_annotations/run_segm_annot_relabel.py +++ b/handling_annotations/run_segm_annot_relabel.py @@ -12,11 +12,11 @@ """ -import os -import sys +import argparse import glob import logging -import argparse +import os +import sys from functools import partial import numpy as np diff --git a/imsegm/annotation.py b/imsegm/annotation.py index d15fb425..9e78680b 100755 --- a/imsegm/annotation.py +++ b/imsegm/annotation.py @@ -4,12 +4,12 @@ Copyright (C) 2014-2018 Jiri Borovec """ -import os import logging +import os -import tqdm import numpy as np import pandas as pd +import tqdm from PIL import Image # from skimage import io from scipy import interpolate diff --git a/imsegm/classification.py b/imsegm/classification.py index 8aa890b6..2fbcee26 100755 --- a/imsegm/classification.py +++ b/imsegm/classification.py @@ -5,12 +5,12 @@ Copyright (C) 2014-2018 Jiri Borovec """ +import collections +import itertools +import logging import os import pickle -import logging import random -import collections -import itertools from functools import partial import numpy as np @@ -20,12 +20,13 @@ from scipy import interp from scipy.stats import randint as sp_randint from scipy.stats import uniform as sp_random -from sklearn.base import clone -from sklearn import preprocessing, feature_selection, decomposition from sklearn import cluster, metrics from sklearn import ensemble, neighbors, svm, tree -from sklearn import pipeline, linear_model, neural_network from sklearn import model_selection +from sklearn import pipeline, linear_model, neural_network +from sklearn import preprocessing, feature_selection, decomposition +from sklearn.base import clone + try: # due to some chnages in between versions from sklearn.grid_search import GridSearchCV, RandomizedSearchCV except Exception: diff --git a/imsegm/descriptors.py b/imsegm/descriptors.py index e776624f..f07fc341 100755 --- a/imsegm/descriptors.py +++ b/imsegm/descriptors.py @@ -14,12 +14,13 @@ import numpy as np from scipy import ndimage, interpolate, optimize, spatial from scipy.ndimage.filters import gaussian_filter, gaussian_filter1d, gaussian_laplace -from sklearn import preprocessing from skimage import morphology -# from numba.decorators import jit -# from numba import int32, int64, float32 +from sklearn import preprocessing from imsegm.utilities.data_io import convert_img_color_from_rgb + +# from numba.decorators import jit +# from numba import int32, int64, float32 try: import imsegm.features_cython as fts_cython # logging.debug('try to load Cython implementation') # CRASH logger @@ -499,7 +500,7 @@ def cython_img3d_gray_energy(img, seg): :param ndarray img: input RGB image :param ndarray seg: segmentation og the image - :return:np.array vector of mean colour per segment + :return: np.array vector of mean colour per segment .. seealso:: :func:`imsegm.descriptors.numpy_img3d_gray_energy` @@ -529,7 +530,7 @@ def cython_img3d_gray_std(img, seg, mean=None): :param ndarray img: input RGB image :param ndarray seg: segmentation og the image :param ndarray mean: precomputed feature means - :return:np.array vector of mean colour per segment + :return: np.array vector of mean colour per segment .. seealso:: :func:`imsegm.descriptors.numpy_img3d_gray_std` @@ -1484,8 +1485,7 @@ def compute_label_hist_segm(segm, position, struc_elem, nb_labels): def cython_label_hist_seg2d(segm_select, struc_elem, nb_labels): """ compute histogram of labels for set of centric annulus - :param ndarray segm: np.array - :param tuple(float,float) position: position in the segmentation + :param ndarray segm_select: np.array :param ndarray struc_elem: np.array :param int nb_labels: total number of labels in the segmentation :return list(float): @@ -1493,10 +1493,11 @@ def cython_label_hist_seg2d(segm_select, struc_elem, nb_labels): .. seealso:: :func:`imsegm.descriptors.compute_label_hist_segm` .. note:: output of this function should be equal to - ``` - for lb in range(nb_labels): - hist[lb] = np.sum(np.logical_and(segm_select == lb, struc_elem == 1)) - ``` + :: + + for lb in range(nb_labels): + hist[lb] = np.sum(np.logical_and(segm_select == lb, struc_elem == 1)) + >>> segm = np.zeros((10, 10), dtype=int) >>> segm[1:9, 2:8] = 1 diff --git a/imsegm/ellipse_fitting.py b/imsegm/ellipse_fitting.py index afbbe556..c5c4b5ee 100755 --- a/imsegm/ellipse_fitting.py +++ b/imsegm/ellipse_fitting.py @@ -7,14 +7,14 @@ import numpy as np from scipy import ndimage, spatial from skimage import morphology - from skimage.measure import fit as sk_fit -# from skimage.measure.fit import EllipseModel # fix in future skimage>0.13.0 -from imsegm.utilities.drawing import ellipse + from imsegm.descriptors import ( reduce_close_points, compute_ray_features_segm_2d, reconstruct_ray_features_2d) from imsegm.superpixels import ( segment_slic_img2d, superpixel_centers, make_graph_segm_connect_grid2d_conn4) +# from skimage.measure.fit import EllipseModel # fix in future skimage>0.13.0 +from imsegm.utilities.drawing import ellipse # INIT_MASK_BORDER = 50. #: define minimal size of estimated ellipse @@ -185,10 +185,8 @@ def ransac_segm(points, model_class, points_all, weights, labels, table_prob, inliers : (N, ) array Boolean mask of inliers classified as ``True``. - References - ---------- - .. [1] "RANSAC", Wikipedia, http://en.wikipedia.org/wiki/RANSAC - + Examples + -------- >>> seg = np.zeros((120, 150), dtype=int) >>> ell_params = 60, 75, 40, 65, np.deg2rad(30) >>> seg = add_overlap_ellipse(seg, ell_params, 1) diff --git a/imsegm/graph_cuts.py b/imsegm/graph_cuts.py index aaa15553..891a1f08 100755 --- a/imsegm/graph_cuts.py +++ b/imsegm/graph_cuts.py @@ -7,6 +7,7 @@ import logging import numpy as np + try: from gco import cut_general_graph except Exception: @@ -256,7 +257,7 @@ def estim_class_model_kmeans(features, nb_classes, init_type='k-means++', max_it """ from all features estimate Gaussian from k-means clustering :param [[float]] features: list of features per segment - :param int nb_classes:, number of classes + :param int nb_classes: number of classes :param str init_type: initialization :param int max_iter: maximal number of iterations :return [[float]]: probabilities that each feature belongs to each class @@ -388,16 +389,16 @@ def compute_edge_model(edges, proba, metric='l_T'): """ compute the edge weight from the feature space small differences are large weights, diff close 0 appears to be 1 - setting min weight ~ max difference in proba as weight - meaning if two vertexes have same proba to all classes the diff is 0 + setting min weight ~ max difference in proba as weight + meaning if two vertexes have same proba to all classes the diff is 0 and weights are 1 on the other hand if there is [0.7, 0.1, 0.2] and [0.2, 0.7, 0.1] gives large diff [0.5, 0.6, 0.1] in 1. and 2. diff and zero in 3 leading to weights [0.5, 0.4, 0.9] - and so we take the min valus + and so we take the min values - :param [(int, int)] edges: - :param [[float]] proba: - :param str metric: + :param [(int, int)] edges: edges + :param [[float]] proba: probablilitirs + :param str metric: define metric :return list(float): diff --git a/imsegm/labeling.py b/imsegm/labeling.py index e215e433..28e4f7d0 100755 --- a/imsegm/labeling.py +++ b/imsegm/labeling.py @@ -7,8 +7,8 @@ import logging import numpy as np -from scipy import ndimage import skimage.segmentation as sk_segm +from scipy import ndimage from imsegm.utilities.data_io import get_image2d_boundary_color diff --git a/imsegm/pipelines.py b/imsegm/pipelines.py index 5383e390..ee9e63dd 100755 --- a/imsegm/pipelines.py +++ b/imsegm/pipelines.py @@ -9,18 +9,19 @@ import numpy as np import skimage.color as sk_color -# from sklearn import mixture -from imsegm.utilities.experiments import WrapExecuteSequence, nb_workers -from imsegm.graph_cuts import segment_graph_cut_general, estim_class_model -from imsegm.superpixels import segment_slic_img2d, segment_slic_img3d_gray +from imsegm.classification import ( + DEFAULT_CLASSIF_NAME, DEFAULT_CLUSTERING, convert_set_features_labels_2_dataset, + CrossValidateGroups, create_classif_search_train_export) from imsegm.descriptors import ( FEATURES_SET_COLOR, norm_features, compute_selected_features_img2d, compute_selected_features_gray3d) +from imsegm.graph_cuts import segment_graph_cut_general, estim_class_model from imsegm.labeling import histogram_regions_labels_norm -from imsegm.classification import ( - DEFAULT_CLASSIF_NAME, DEFAULT_CLUSTERING, convert_set_features_labels_2_dataset, - CrossValidateGroups, create_classif_search_train_export) +from imsegm.superpixels import segment_slic_img2d, segment_slic_img3d_gray +from imsegm.utilities.experiments import WrapExecuteSequence, nb_workers + +# from sklearn import mixture #: select basic features extracted from superpixels FTS_SET_SIMPLE = FEATURES_SET_COLOR diff --git a/imsegm/region_growing.py b/imsegm/region_growing.py index f26c208d..62f92afb 100755 --- a/imsegm/region_growing.py +++ b/imsegm/region_growing.py @@ -10,8 +10,9 @@ import numpy as np from scipy import stats, ndimage, interpolate -from sklearn import cluster, mixture from skimage import morphology +from sklearn import cluster, mixture + try: from gco import cut_general_graph, cut_grid_graph except Exception: diff --git a/imsegm/utilities/data_io.py b/imsegm/utilities/data_io.py index 74d19985..648bcda0 100644 --- a/imsegm/utilities/data_io.py +++ b/imsegm/utilities/data_io.py @@ -4,20 +4,20 @@ Copyright (C) 2015-2018 Jiri Borovec """ -import os -import re import glob import logging +import os +import re import warnings from functools import wraps +import nibabel import numpy as np import pandas as pd from PIL import Image # import libtiff, nibabel from scipy import ndimage from skimage import exposure, io, color, measure -import nibabel from imsegm.utilities.read_zvi import load_image as load_zvi @@ -347,8 +347,7 @@ def load_image_2d(path_img): :param str path_img: path to the input image :return str, ndarray: image name, image as matrix - PNG image - --------- + >>> # PNG image >>> img_name = 'testing-image' >>> img = np.random.randint(0, 255, size=(20, 20, 3)) >>> path_img = export_image(os.path.join('.', img_name), img, @@ -370,8 +369,7 @@ def load_image_2d(path_img): (65, 50) >>> os.remove(path_img) - TIFF image - ---------- + >>> # TIFF image >>> img_name = 'testing-image' >>> img = np.random.randint(0, 255, size=(5, 20, 20)) >>> path_img = export_image(os.path.join('.', img_name), img, @@ -419,8 +417,7 @@ def export_image(path_img, img, stretch_range=True): :param bool stretch_range: :return str: path to the image - PNG image - --------- + >>> # PNG image >>> np.random.seed(0) >>> img = np.random.random([5, 10]) >>> path_img = export_image(os.path.join('.', 'testing-image'), img) @@ -439,8 +436,7 @@ def export_image(path_img, img, stretch_range=True): [ 93, 113, 181, 15, 173, 174, 54, 33, 82, 94]], dtype=uint8) >>> os.remove(path_img) - TIFF image - ---------- + >>> # TIFF image >>> img = np.random.random([5, 20, 25]) >>> path_img = export_image(os.path.join('.', 'testing-image'), img) >>> path_img @@ -1057,12 +1053,6 @@ def add_padding(img_size, padding, min_row, min_col, max_row, max_col): return min_row, min_col, max_row, max_col -# prepare a simple mask with one horizontal segment -prop = measure.regionprops(np.array([[0] * 20, [1] * 20, [0] * 20], dtype=int))[0] -#: according to skimage version the major axis are swapped -PROP_ROTATION_OFFSET = prop.orientation - - def cut_object(img, mask, padding, use_mask=False, bg_color=None, allow_rotate=True): """ cut an object from image according binary object segmentation @@ -1095,6 +1085,11 @@ def cut_object(img, mask, padding, use_mask=False, bg_color=None, allow_rotate=T """ assert mask.shape[:2] == img.shape[:2] + # prepare a simple mask with one horizontal segment + prop = measure.regionprops(np.array([[0] * 20, [1] * 20, [0] * 20], dtype=int))[0] + #: according to skimage version the major axis are swapped + PROP_ROTATION_OFFSET = prop.orientation + prop = measure.regionprops(mask.astype(int))[0] bg_pixels = np.hstack([mask[0, :], mask[:, 0], mask[-1, :], mask[:, -1]]) bg_mask = np.argmax(np.bincount(bg_pixels)) diff --git a/imsegm/utilities/data_samples.py b/imsegm/utilities/data_samples.py index 1b829d1d..240bfde3 100644 --- a/imsegm/utilities/data_samples.py +++ b/imsegm/utilities/data_samples.py @@ -10,8 +10,8 @@ Copyright (C) 2015-2018 Jiri Borovec """ -import os import logging +import os # from PIL import Image import numpy as np diff --git a/imsegm/utilities/drawing.py b/imsegm/utilities/drawing.py index 2a416a51..da5629f9 100644 --- a/imsegm/utilities/drawing.py +++ b/imsegm/utilities/drawing.py @@ -4,10 +4,11 @@ Copyright (C) 2016-2018 Jiri Borovec """ -import os import logging +import os import matplotlib + if os.environ.get('DISPLAY', '') == '' and matplotlib.rcParams['backend'] != 'agg': print('No display found. Using non-interactive Agg backend.') matplotlib.use('Agg') @@ -799,13 +800,13 @@ def merge_object_masks(masks, overlap_thr=0.7): def draw_image_segm_points(ax, img, points, labels=None, slic=None, color_slic='w', lut_label_marker=DICT_LABEL_MARKER, seg_contour=None): - """ on plane draw background image or segmentation, overlap with slic - contours, add contour of adative segmentation like annot. for centers - plot point with specific property (shape and colour) according label + """ on plane draw background image or segmentation, overlap with SLIC + contours, add contour of adative segmentation like annot. for centers + plot point with specific property (shape and colour) according label :param ax: figure axis :param ndarray img: image - :param list(tuple(int,int)) points:collection of points + :param list(tuple(int,int)) points: collection of points :param list(int) labels: LUT labels for superpixels :param ndarray slic: superpixel segmentation :param str color_slic: color dor superpixels diff --git a/imsegm/utilities/experiments.py b/imsegm/utilities/experiments.py index c05c59f3..f2cc46a9 100644 --- a/imsegm/utilities/experiments.py +++ b/imsegm/utilities/experiments.py @@ -4,17 +4,17 @@ Copyright (C) 2014-2018 Jiri Borovec """ -import os import copy +import logging +import multiprocessing as mproc +import os import time import types -import logging import uuid -import multiprocessing as mproc from functools import wraps -import yaml import tqdm +import yaml from sklearn import metrics #: total number of avalaible CPUs/treads diff --git a/notebooks/RG2Sp_model_region-grow.ipynb b/notebooks/RG2Sp_model_region-grow.ipynb index ff3e06ac..3c103dac 100755 --- a/notebooks/RG2Sp_model_region-grow.ipynb +++ b/notebooks/RG2Sp_model_region-grow.ipynb @@ -569,7 +569,7 @@ "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", - "pygments_lexer": "ipython2", + "pygments_lexer": "ipython3", "version": "2.7.12" } }, diff --git a/notebooks/RG2Sp_region-growing.ipynb b/notebooks/RG2Sp_region-growing.ipynb index f50d8f70..3f2983b0 100755 --- a/notebooks/RG2Sp_region-growing.ipynb +++ b/notebooks/RG2Sp_region-growing.ipynb @@ -1081,7 +1081,7 @@ "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", - "pygments_lexer": "ipython2", + "pygments_lexer": "ipython3", "version": "2.7.12" } }, diff --git a/tests/test_classification.py b/tests/test_classification.py index e37e3340..434db5b1 100644 --- a/tests/test_classification.py +++ b/tests/test_classification.py @@ -4,10 +4,10 @@ Copyright (C) 2014-2018 Jiri Borovec """ +import logging import os import sys import unittest -import logging import numpy as np from sklearn import metrics diff --git a/tests/test_descriptors.py b/tests/test_descriptors.py index 1f3c1ee6..d72b61d7 100644 --- a/tests/test_descriptors.py +++ b/tests/test_descriptors.py @@ -4,15 +4,15 @@ Copyright (C) 2014-2018 Jiri Borovec """ +import logging import os import sys import time -import logging import unittest +import matplotlib.pyplot as plt import numpy as np from skimage import draw, transform -import matplotlib.pyplot as plt sys.path.append(os.path.abspath(os.path.join('..', '..'))) # Add path to root from imsegm.utilities.data_samples import (IMAGE_LENNA, load_sample_image, diff --git a/tests/test_ellipse-fitting.py b/tests/test_ellipse-fitting.py index 32e87577..375c76a6 100644 --- a/tests/test_ellipse-fitting.py +++ b/tests/test_ellipse-fitting.py @@ -4,14 +4,14 @@ Copyright (C) 2014-2018 Jiri Borovec """ +import logging import os import sys -import logging import unittest +import matplotlib.pyplot as plt import numpy as np import pandas as pd -import matplotlib.pyplot as plt from sklearn.metrics import adjusted_rand_score sys.path.append(os.path.abspath(os.path.join('..', '..'))) # Add path to root diff --git a/tests/test_graph-cut.py b/tests/test_graph-cut.py index 4656635b..883e9661 100644 --- a/tests/test_graph-cut.py +++ b/tests/test_graph-cut.py @@ -4,10 +4,10 @@ Copyright (C) 2014-2018 Jiri Borovec """ +import logging import os import sys import unittest -import logging import numpy as np import pandas as pd diff --git a/tests/test_labeling.py b/tests/test_labeling.py index 11ffd156..c643f817 100644 --- a/tests/test_labeling.py +++ b/tests/test_labeling.py @@ -5,13 +5,13 @@ Copyright (C) 2014-2018 Jiri Borovec """ +import logging import os import sys import unittest -import logging -import numpy as np import matplotlib.pyplot as plt +import numpy as np sys.path.append(os.path.abspath(os.path.join('..', '..'))) # Add path to root from imsegm.utilities.data_samples import sample_segment_vertical_2d diff --git a/tests/test_pipelines.py b/tests/test_pipelines.py index 2d89d377..c6fe96b5 100644 --- a/tests/test_pipelines.py +++ b/tests/test_pipelines.py @@ -4,10 +4,10 @@ Copyright (C) 2014-2018 Jiri Borovec """ +import copy import logging import os import sys -import copy import unittest import matplotlib.pyplot as plt diff --git a/tests/test_region-growing.py b/tests/test_region-growing.py index 6df4f685..e23a6490 100644 --- a/tests/test_region-growing.py +++ b/tests/test_region-growing.py @@ -4,18 +4,19 @@ Copyright (C) 2014-2018 Jiri Borovec """ +import glob import logging import os import sys -import glob import unittest -# import pickle +import matplotlib.pyplot as plt import numpy as np import pandas as pd -import matplotlib.pyplot as plt from sklearn.metrics import adjusted_rand_score +# import pickle + sys.path.append(os.path.abspath(os.path.join('..', '..'))) # Add path to root from imsegm.utilities.data_io import update_path, load_image_2d from imsegm.utilities.drawing import draw_rg2sp_results, figure_rg2sp_debug_complete diff --git a/tests/test_superpixels.py b/tests/test_superpixels.py index f9ac2576..6e2da5f3 100644 --- a/tests/test_superpixels.py +++ b/tests/test_superpixels.py @@ -4,13 +4,13 @@ Copyright (C) 2014-2018 Jiri Borovec """ +import logging import os import sys import unittest -import logging -import numpy as np import matplotlib.pyplot as plt +import numpy as np sys.path.append(os.path.abspath(os.path.join('..', '..'))) # Add path to root from imsegm.utilities.data_samples import (IMAGE_LENNA, load_sample_image, diff --git a/tests/test_utilities.py b/tests/test_utilities.py index 83f5599d..1daba797 100644 --- a/tests/test_utilities.py +++ b/tests/test_utilities.py @@ -5,10 +5,10 @@ Copyright (C) 2014-2018 Jiri Borovec """ +import logging import os import sys import unittest -import logging sys.path.append(os.path.abspath(os.path.join('..', '..'))) # Add path to root from imsegm.utilities.experiments import try_decorator