├── tests ├── __init__.py ├── img.npy ├── 24_binary.tif └── tests.py ├── CHANGELOG.md ├── feret ├── img.npy ├── 10243_binary.tif ├── 104_binary_verrgroessert.tif ├── 126_binary_verrgroessert.tif ├── 11300_binary_verrgroessert.tif ├── .idea │ ├── misc.xml │ ├── vcs.xml │ ├── .gitignore │ ├── inspectionProfiles │ │ ├── profiles_settings.xml │ │ └── Project_Default.xml │ ├── modules.xml │ └── feret.iml ├── temp.py ├── __init__.py └── main.py ├── README.assets └── plot_method.png ├── CONTRIBUTING.md ├── .idea ├── misc.xml ├── vcs.xml ├── .gitignore ├── inspectionProfiles │ ├── profiles_settings.xml │ └── Project_Default.xml ├── modules.xml └── feret.iml ├── .github └── ISSUE_TEMPLATE │ ├── feature_request.md │ └── bug_report.md ├── LICENSE ├── pyproject.toml ├── .gitignore ├── README.md └── CODE_OF_CONDUCT.md /tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | #### 0.3.3 2 | 3 | minferet90 added -------------------------------------------------------------------------------- /feret/img.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/matthiasnwt/feret/HEAD/feret/img.npy -------------------------------------------------------------------------------- /tests/img.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/matthiasnwt/feret/HEAD/tests/img.npy -------------------------------------------------------------------------------- /tests/24_binary.tif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/matthiasnwt/feret/HEAD/tests/24_binary.tif -------------------------------------------------------------------------------- /feret/10243_binary.tif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/matthiasnwt/feret/HEAD/feret/10243_binary.tif -------------------------------------------------------------------------------- /README.assets/plot_method.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/matthiasnwt/feret/HEAD/README.assets/plot_method.png -------------------------------------------------------------------------------- /feret/104_binary_verrgroessert.tif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/matthiasnwt/feret/HEAD/feret/104_binary_verrgroessert.tif -------------------------------------------------------------------------------- /feret/126_binary_verrgroessert.tif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/matthiasnwt/feret/HEAD/feret/126_binary_verrgroessert.tif -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | Hello, 2 | contributions of any kind are welcome. I am myself not sure about the direction this should take. 3 | -------------------------------------------------------------------------------- /feret/11300_binary_verrgroessert.tif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/matthiasnwt/feret/HEAD/feret/11300_binary_verrgroessert.tif -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /feret/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /feret/.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | # Editor-based HTTP Client requests 5 | /httpRequests/ 6 | # Datasource local storage ignored files 7 | /dataSources/ 8 | /dataSources.local.xml 9 | -------------------------------------------------------------------------------- /feret/.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | # Editor-based HTTP Client requests 5 | /httpRequests/ 6 | # Datasource local storage ignored files 7 | /dataSources/ 8 | /dataSources.local.xml 9 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /feret/.idea/inspectionProfiles/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /feret/.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /feret/temp.py: -------------------------------------------------------------------------------- 1 | import os, glob 2 | import feret 3 | import tifffile as tif 4 | 5 | path = r"D:\Arbeit\nPSize\Auswertungen\Biypramiden_FEI_Nov_2020\Results" 6 | 7 | for i, file in enumerate(glob.glob(os.path.join(path, '*_binary.tif'))): 8 | # if i != 22: continue 9 | img = tif.imread(file) 10 | # print(file) 11 | res = feret.calc(img) 12 | 13 | 14 | -------------------------------------------------------------------------------- /feret/.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | -------------------------------------------------------------------------------- /feret/.idea/feret.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 12 | -------------------------------------------------------------------------------- /.idea/feret.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 12 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Matthias Nwt 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "feret" 3 | version = "1.3.1" 4 | description = "Calculate the maximum and minimum Feret diameter." 5 | authors = ["matthiasnwt <62239991+matthiasnwt@users.noreply.github.com>"] 6 | license = "MIT" 7 | readme = "README.md" 8 | 9 | 10 | repository = "https://github.com/matthiasnwt/feret" 11 | homepage = "https://github.com/matthiasnwt/feret" 12 | 13 | keywords = ["feret", "feretdiameter", "maxferet", "diameter", "maximum", "caliper", "caliper diameter", "python", "minferet", "minimum", "feret diameter"] 14 | 15 | classifiers = [ 16 | "Development Status :: 5 - Production/Stable", 17 | "Operating System :: Microsoft :: Windows", 18 | "Operating System :: Unix", 19 | "Operating System :: MacOS", 20 | "Programming Language :: Python", 21 | "Topic :: Scientific/Engineering", 22 | "Topic :: Scientific/Engineering :: Physics", 23 | "Topic :: Scientific/Engineering :: Image Processing", 24 | "Topic :: Scientific/Engineering :: Information Analysis", 25 | "Topic :: Scientific/Engineering :: Visualization", 26 | "Topic :: Utilities" 27 | ] 28 | 29 | [tool.poetry.dependencies] 30 | python = "^3" 31 | numpy = "^1.22.3" 32 | scipy = "^1.8.0" 33 | matplotlib = "^3.5.1" 34 | opencv-python = "^4.5" 35 | 36 | 37 | [tool.poetry.dev-dependencies] 38 | 39 | [build-system] 40 | requires = ["poetry-core>=1.0.0"] 41 | build-backend = "poetry.core.masonry.api" 42 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 23 | -------------------------------------------------------------------------------- /tests/tests.py: -------------------------------------------------------------------------------- 1 | import feret 2 | import numpy as np 3 | import matplotlib.pyplot as plt 4 | import time 5 | 6 | img = np.load('img.npy') 7 | 8 | 9 | 10 | ###### 11 | # Testing without edge 12 | edge = False 13 | 14 | # Test calc-method 15 | t0 = time.time() 16 | f = feret.calc(img, edge) 17 | print(f'calc-method succesful. {time.time() - t0} secs') 18 | 19 | # Test all-method 20 | t0 = time.time() 21 | maxf, minf = feret.all(img, edge) 22 | print(f'all-method succesful. {time.time() - t0} secs') 23 | 24 | # Test max-method 25 | t0 = time.time() 26 | maxf = feret.max(img, edge) 27 | print(f'max-method succesful. {time.time() - t0} secs') 28 | 29 | # Test min-method 30 | t0 = time.time() 31 | minf = feret.min(img, edge) 32 | print(f'min-method succesful. {time.time() - t0} secs') 33 | 34 | print(f'\nMaxFeret: {maxf}\nMinFeret: {minf}') 35 | 36 | 37 | ###### 38 | # Testing with edge 39 | edge = True 40 | 41 | # Test calc-method 42 | t0 = time.time() 43 | f = feret.calc(img, edge) 44 | print(f'calc-method succesful. {time.time() - t0} secs') 45 | 46 | # Test all-method 47 | t0 = time.time() 48 | maxf, minf = feret.all(img, edge) 49 | print(f'all-method succesful. {time.time() - t0} secs') 50 | 51 | # Test max-method 52 | t0 = time.time() 53 | maxf = feret.max(img, edge) 54 | print(f'max-method succesful. {time.time() - t0} secs') 55 | 56 | # Test min-method 57 | t0 = time.time() 58 | minf = feret.min(img, edge) 59 | print(f'min-method succesful. {time.time() - t0} secs') 60 | 61 | print(f'\nMaxFeret: {maxf}\nMinFeret: {minf}') -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ 161 | © 2022 GitHub, Inc. 162 | Terms 163 | Privacy 164 | Security 165 | Status 166 | Docs 167 | Contact GitHub 168 | Pricing 169 | API 170 | Training 171 | Blog 172 | About 173 | -------------------------------------------------------------------------------- /feret/__init__.py: -------------------------------------------------------------------------------- 1 | # 2 | from matplotlib import pyplot as plt 3 | 4 | # from main import Calculater 5 | 6 | from feret.main import Calculater 7 | 8 | 9 | def calc(img, edge=False): 10 | """ 11 | Calculate the true maximum feret diameter (minf) 12 | and the approximated minimum feret diameter (minf). 13 | 14 | result = calc(img) 15 | maxf, minf = result.maxf, result.minf 16 | 17 | Args: 18 | img (numpy.ndarray): binary-image 19 | edge (boolean): use edges (vertices) or centers 20 | 21 | Returns: 22 | Calculater (object): calculator class. 23 | """ 24 | feret_calc = Calculater(img, edge) 25 | feret_calc.calculate_minferet() 26 | feret_calc.calculate_minferet90() 27 | feret_calc.calculate_maxferet() 28 | feret_calc.calculate_maxferet90() 29 | return feret_calc 30 | 31 | 32 | def all(img, edge=False): 33 | """ 34 | Calculate the true maximum feret diameter (minf) 35 | and the approximated minimum feret diameter (minf). 36 | 37 | Args: 38 | img (numpy.ndarray): binary-image 39 | edge (boolean): use edges (vertices) or centers 40 | 41 | Returns: 42 | maxf (float): maximum feret diameter 43 | minf (float): minimum feret diameter 44 | """ 45 | 46 | feret_calc = calc(img, edge) 47 | return feret_calc.maxf, feret_calc.minf, feret_calc.minf90, feret_calc.maxf90 48 | 49 | 50 | def plot(img, edge=False): 51 | """ 52 | Plot of the results. 53 | 54 | Args: 55 | img (numpy.ndarray): binary-image 56 | edge (boolean): use edges (vertices) or centers 57 | 58 | """ 59 | feret_calc = calc(img, edge) 60 | feret_calc.plot() 61 | 62 | 63 | def max(img, edge=False): 64 | """ 65 | Calculate the true maximum feret diameter (minf). 66 | 67 | Args: 68 | img (numpy.ndarray): binary-image 69 | edge (boolean): use edges (vertices) or centers 70 | 71 | Returns: 72 | maxf (float): maximum feret diameter 73 | """ 74 | 75 | feret_calc = Calculater(img, edge) 76 | feret_calc.calculate_maxferet() 77 | return feret_calc.maxf 78 | 79 | 80 | def min(img, edge=False): 81 | """ 82 | Calculate the approximated minimum feret diameter (minf). 83 | 84 | Args: 85 | img (numpy.ndarray): binary-image 86 | edge (boolean): use edges (vertices) or centers 87 | 88 | Returns: 89 | minf (float): minimum feret diameter 90 | """ 91 | 92 | feret_calc = Calculater(img, edge) 93 | feret_calc.calculate_minferet() 94 | return feret_calc.minf 95 | 96 | 97 | def min90(img, edge=False): 98 | """ 99 | Calculate the approximated feret diameter 90 100 | degree (minf90) to minimum feret diameter (minf). 101 | 102 | Args: 103 | img (numpy.ndarray): binary-image 104 | edge (boolean): use edges (vertices) or centers 105 | 106 | Returns: 107 | minf90 (float): minimum feret diameter 90 degree 108 | """ 109 | 110 | feret_calc = Calculater(img, edge) 111 | feret_calc.calculate_minferet() 112 | feret_calc.calculate_minferet90() 113 | return feret_calc.minf90 114 | 115 | 116 | def max90(img, edge=False): 117 | """ 118 | Calculate the approximated feret diameter 90 119 | degree (maxf90) to maximum feret diameter (minf). 120 | 121 | Args: 122 | img (numpy.ndarray): binary-image 123 | edge (boolean): use edges (vertices) or centers 124 | 125 | Returns: 126 | maxf90 (float): maximum feret diameter 90 degree 127 | """ 128 | 129 | feret_calc = Calculater(img, edge) 130 | feret_calc.calculate_maxferet() 131 | feret_calc.calculate_maxferet90() 132 | return feret_calc.maxf90 133 | 134 | # if __name__ == '__main__': 135 | # 136 | # import numpy as np 137 | # import time 138 | # import tifffile as tif 139 | # # img = np.load('img.npy') 140 | # img = tif.imread('10243_binary.tif').T 141 | # img = tif.imread('11300_binary_verrgroessert.tif') 142 | # 143 | # plot(img, edge=True) 144 | # 145 | # print(min90(img)) 146 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # *Feret*: A Python Module to calculate the Feret Diameter of Binary Images 2 | 3 | 4 | 5 | This python module can calculate the following parameters for binary images: 6 | 7 | * maximum Feret diameter (maxferet, maxf) 8 | * minimum Feret diameter (minferet, minf) 9 | * Feret diameter 90 ° to the minferet (minferet90, minf90) 10 | * Feret diameter 90 ° to maxferet (maxferet90, maxf90) 11 | 12 | See this [Wikipedia page](https://en.wikipedia.org/wiki/Feret_diameter) to get the definition of those parameters. 13 | 14 | This module gives the exact results as ImageJ (use `edge=True` as shown below), all the parameters are exactly calculated and **not** approximated. 15 | 16 | ## Installations 17 | This project is available via pip: 18 | 19 | `pip install feret` 20 | 21 | ## Pieces of Information 22 | 23 | #### Convex Hull 24 | 25 | The definition of the maxferet and minferet uses the image of a caliper. Therefore, only the points which correspond to the convex hull of the object play a role. That is why before any calculations the convex hull is determined to reduce the runtime. 26 | 27 | #### Maxferet 28 | The maxferet is calculated as the maximum Euclidean distance of all pixels. 29 | 30 | #### Minferet 31 | 32 | The minferet is exactly calculated and **not** approximated. My algorithm uses the fact, that the calipers that define the minferet run on one side through two points and on the other through one point. The script iterates over all edge points and defines a line through the point and the one next to it. Then all the distances to the other points are calculated and the maximum is taken. The minimum of all those maximums is the minferet. The maximum of all those maximums is **not** the maxferet, that is the reason it is calculated separately. The runtime of this is already pretty good but hopefully I can improve it in the future. 33 | 34 | ## Use 35 | The module can be used as followed: 36 | 37 | First you need a binary image for which the feret diameter should be calculated. The background has to have the value zero, the object can have any nonzero value. The object doesn't have to be convex. At the moment the module only supports one object per image.This means, that if there are multiple not connected regions, the script will calculate a convexhull which include all regions and for this hull the feret diameter is calculated. 38 | 39 | Thr calls are: 40 | 41 | ```python 42 | import feret 43 | 44 | # tifffile is not required nor included in this module. 45 | import tifffile as tif 46 | img = tif.imread('example.tif') # Image has to be a numpy 2d-array. 47 | 48 | 49 | # get the values 50 | maxf, minf, minf90, maxf90 = feret.all(img) 51 | 52 | # get only maxferet 53 | maxf = feret.max(img) 54 | 55 | # get only minferet 56 | minf = feret.min(img) 57 | 58 | # get only minferet90 59 | minf90 = feret.min90(img) 60 | 61 | # get only maxferet90 62 | maxf90 = feret.max90(img) 63 | 64 | # get all the informations 65 | res = feret.calc(img) 66 | maxf = res.maxf 67 | minf = res.minf 68 | minf90 = res.minf90 69 | minf_angle = res.minf_angle 70 | minf90_angle = res.minf90_angle 71 | maxf_angle = res.maxf_angle 72 | maxf90_angle = res.maxf90_angle 73 | ``` 74 | 75 | There is an option to calculate the Feret diameters for the pixel edges instead of the centers. Just add an `edge=True` in the call as shown below. This works for all calls analogous. 76 | 77 | ```python 78 | import feret 79 | 80 | # tifffile is not required nor included in this module. 81 | import tifffile as tif 82 | img = tif.imread('example.tif') # Image has to be a numpy 2d-array. 83 | 84 | # get only maxferet 85 | maxf = feret.max(img, edge=True) 86 | ``` 87 | 88 | This module can also plot the result. Just use 89 | 90 | ```python 91 | import feret 92 | 93 | # tifffile is not required nor included in this module. 94 | import tifffile as tif 95 | img = tif.imread('example.tif') # Image has to be a numpy 2d-array. 96 | 97 | # plot the result 98 | feret.plot(img) #edge=True can be passed here too 99 | ``` 100 | 101 | 102 | 103 | The reason for the two MinFeret points on the left is described above. The MinFeret line does not have to run in between its two base points or through one of them. MaxFeret and MinFeret do not have to be 90° to each other. To calculate the 90° to MaxFeret and MinFeret use `feret.max90(img)` and `feret.min90(img)` methods. 104 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | @matthiasnwt. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /feret/main.py: -------------------------------------------------------------------------------- 1 | import cv2 as cv 2 | import matplotlib.pyplot as plt 3 | import numpy as np 4 | from numpy.linalg import norm 5 | from scipy import ndimage 6 | from scipy.spatial.distance import pdist, squareform 7 | 8 | 9 | class Calculater(): 10 | def __init__(self, img, edge): 11 | self.img = img.astype(float) 12 | self.edge = edge 13 | 14 | self.find_convexhull() 15 | self.y0, self.x0 = ndimage.center_of_mass(self.hull) 16 | 17 | def find_convexhull(self): 18 | # Method calculates convexhull. 19 | # If edge flag is set, it uses the corners not centers 20 | if self.edge: 21 | ys, xs = np.nonzero(self.img) 22 | new_xs = np.concatenate( 23 | (xs + 0.5, xs + 0.5, xs - 0.5, xs - 0.5, xs, xs + 0.5, xs - 0.5, xs, xs)) 24 | new_ys = np.concatenate( 25 | (ys + 0.5, ys - 0.5, ys + 0.5, ys - 0.5, ys, ys, ys, ys + 0.5, ys - 0.5)) 26 | new_ys, new_xs = (new_ys * 2).astype(int), (new_xs * 2).astype(int) 27 | self.hull = cv.convexHull(np.array([new_ys, new_xs]).T).T.reshape(2, -1).astype(float) 28 | else: 29 | self.hull = cv.convexHull(np.transpose(np.nonzero(self.img))).T.reshape(2, -1).astype(float) 30 | 31 | def plot(self): 32 | """ 33 | This method plots the particle, the maxferet and minferet coordinates 34 | and the lines which run through the maxferet and minferet. 35 | 36 | """ 37 | 38 | plt.figure(dpi=100, figsize=(10, 10)) 39 | plt.title(f'MinFeret: {self.minf:.6f} ||| MaxFeret: {self.maxf:.6f}') 40 | plt.imshow(self.img, origin='lower') 41 | 42 | ymax, xmax = self.img.shape 43 | xs = np.linspace(0, xmax, 2) 44 | 45 | def draw_lines(name, coord1, coord2, color, angle, t, coords, marker): 46 | """ This method draws the lines which run through the maxferet and minferet. """ 47 | plt.scatter(coords.T[1], coords.T[0], c=color, label=name + ' coordinates', marker=marker) 48 | if angle == np.pi / 2: 49 | plt.axhline(coord1[0], linestyle='--', color=color, label=name + ' Baseline') 50 | plt.axhline(coord2[0], linestyle='--', color=color) 51 | plt.axvline(coord1[1], color=color, label=name + ' Line') 52 | elif angle == 0: 53 | plt.axvline(coord1[1], linestyle='--', color=color, label=name + ' Baseline') 54 | plt.axvline(coord2[1], linestyle='--', color=color) 55 | plt.axhline(coord1[0], color=color, label=name + ' Line') 56 | else: 57 | base_m = np.tan(angle + np.pi / 2) 58 | base_t = coord1[0] - base_m * coord1[1] 59 | anker_t = coord2[0] - base_m * coord2[1] 60 | 61 | base_ys = base_m * xs + base_t 62 | anker_ys = base_m * xs + anker_t 63 | ys = np.tan(angle) * xs + t 64 | 65 | plt.plot(xs, base_ys, linestyle='--', color=color, label=name + ' Baseline') 66 | plt.plot(xs, anker_ys, linestyle='--', color=color) 67 | plt.plot(xs, ys, color=color, label=name + ' Line') 68 | 69 | draw_lines('MinFeret', self.minf_coords[0], self.minf_coords[2], 'red', self.minf_angle, self.minf_t, 70 | self.minf_coords, 'o') 71 | draw_lines('MaxFeret', self.maxf_coords[0], self.maxf_coords[1], 'blue', self.maxf_angle, self.maxf_t, 72 | self.maxf_coords, 'o') 73 | draw_lines('MaxFeret90', self.maxf90_coords[0], self.maxf90_coords[1], 'green', self.maxf90_angle, 74 | self.maxf90_t, self.maxf90_coords, 'o') 75 | draw_lines('MinFeret90', self.minf90_coords[0], self.minf90_coords[1], 'orange', self.minf90_angle, 76 | self.minf90_t, self.minf90_coords, 'o') 77 | 78 | plt.ylim(0, ymax) 79 | plt.xlim(0, xmax) 80 | plt.legend() 81 | plt.show() 82 | 83 | def calculate_minferet(self): 84 | """ Method calculates the exact minimum feret diameter. The result is equal to imagejs minferet. """ 85 | length = len(self.hull.T) 86 | 87 | Ds = np.empty(length) 88 | ps = np.empty((length, 3, 2)) 89 | 90 | for i in range(length): 91 | p1 = self.hull.T[i] 92 | p2 = self.hull.T[(i + 1) % length] 93 | 94 | ds = np.abs(np.cross(p2 - p1, p1 - self.hull.T) / norm(p2 - p1)) 95 | 96 | Ds[i] = np.max(ds) 97 | 98 | d_i = np.where(ds == Ds[i])[0][0] 99 | p3 = self.hull.T[d_i] 100 | ps[i] = np.array((p1, p2, p3)) 101 | 102 | self.minf = np.min(Ds) 103 | 104 | minf_index = np.where(Ds == self.minf)[0][0] 105 | 106 | (y0, x0), (y1, x1), (y2, x2) = ps[minf_index] 107 | 108 | if x0 == x1: 109 | self.minf_angle = 0 110 | else: 111 | m = (y0 - y1) / (x0 - x1) 112 | t = y0 - m * x0 113 | self.minf_angle = np.arctan(m) + np.pi / 2 114 | 115 | self.minf_coords = np.array(((y0, x0), (y1, x1), (y2, x2))) 116 | 117 | if self.minf_angle < 0: 118 | self.minf_angle += np.pi 119 | 120 | if self.edge: 121 | self.minf /= 2. 122 | self.minf_coords /= 2. 123 | 124 | if x0 == x1: 125 | self.minf_t = self.minf_coords.T[0][2] 126 | else: 127 | self.minf_t = self.minf_coords.T[0][2] - np.tan(self.minf_angle) * self.minf_coords.T[1][2] 128 | 129 | def calculate_maxferet(self): 130 | """ 131 | The maxferet is defined as the maximum euclidean distance between two points. pdist calculates 132 | all the distances between the points and than the maximum is taken from all those. 133 | """ 134 | pdists = pdist(self.hull.T, "euclidean") 135 | 136 | self.maxf = np.max(pdists) 137 | 138 | maxf_coords_index = np.where(squareform(pdists) == self.maxf)[0] 139 | 140 | # If there are more than one maxferet-combination, this two lines 141 | # sort them in x and y and chooses the first element. 142 | maxf_coords_index_y = maxf_coords_index[:len(maxf_coords_index) // 2][0] 143 | maxf_coords_index_x = maxf_coords_index[len(maxf_coords_index) // 2:][0] 144 | 145 | self.maxf_coords = self.hull.T[np.array((maxf_coords_index_x, maxf_coords_index_y))] 146 | 147 | ((y0, x0), (y1, x1)) = self.maxf_coords 148 | 149 | if x1 == x0: 150 | self.maxf_angle = np.pi / 2 151 | else: 152 | m = (y0 - y1) / (x0 - x1) 153 | t = y0 - m * x0 154 | 155 | self.maxf_angle = np.arctan(m) 156 | 157 | if self.maxf_angle < 0: 158 | self.maxf_angle += np.pi 159 | 160 | if self.edge: 161 | self.maxf /= 2. 162 | self.maxf_coords /= 2 163 | 164 | if x1 == x0: 165 | self.maxf_t = -np.inf 166 | else: 167 | self.maxf_t = self.maxf_coords.T[0][1] - np.tan(self.maxf_angle) * self.maxf_coords.T[1][1] 168 | 169 | def calculate_maxferet90(self): 170 | """ 171 | Method calculates the feret diameter which 172 | is 90 degree to the maximum feret diameter. 173 | It first checks if the angle of the maximum 174 | feret diameter is already calculatet. If not 175 | it calls the maxferet function. 176 | 177 | """ 178 | self.maxf90_angle = self.maxf_angle + np.pi / 2 179 | self.maxf90, self.maxf90_coords = self.calculate_distances(self.maxf90_angle - np.pi / 2) 180 | 181 | if self.edge: 182 | self.maxf90 /= 2 183 | self.maxf90_coords /= 2 184 | 185 | if self.maxf90_angle == 0 or self.maxf90_angle == np.pi: 186 | self.maxf90_t = self.maxf90_coords.T[0][0] 187 | elif self.maxf90_angle == np.pi / 2: 188 | self.maxf90_t = np.inf 189 | else: 190 | self.maxf90_t = self.maxf90_coords.T[0][1] - np.tan(self.maxf90_angle) * self.maxf90_coords.T[1][1] 191 | 192 | def calculate_minferet90(self): 193 | """ 194 | Method calculates the feret diameter which 195 | is 90 degree to the minimum feret diameter. 196 | It first checks if the angle of the minimum 197 | feret diameter is already calculatet. If not 198 | it calls the minferet function. 199 | 200 | """ 201 | self.minf90_angle = self.minf_angle + np.pi / 2 202 | self.minf90, self.minf90_coords = self.calculate_distances(self.minf90_angle - np.pi / 2) 203 | 204 | if self.edge: 205 | self.minf90 /= 2 206 | self.minf90_coords /= 2 207 | 208 | if self.minf90_angle == 0 or self.minf90_angle == np.pi: 209 | self.minf90_t = self.minf90_coords[0][0] 210 | elif self.minf90_angle == np.pi / 2: 211 | self.minf90_t = np.inf 212 | else: 213 | self.minf90_t = self.minf90_coords.T[0][1] - np.tan(self.minf90_angle) * self.minf90_coords.T[1][1] 214 | 215 | def calculate_distances(self, a): 216 | """ 217 | Method calculates the distance of two points at a givin angle. 218 | 219 | Args: 220 | a (float): angle (in rad) 221 | 222 | Returns: 223 | distance (float): caliper distance for angle a 224 | """ 225 | m = np.tan(a) 226 | ds = np.cos(a) * (self.y0 - self.hull[0]) - np.sin(a) * (self.x0 - self.hull[1]) 227 | max_i = np.argmax(ds) 228 | min_i = np.argmin(ds) 229 | 230 | t_max = self.hull.T[max_i][0] - m * self.hull.T[max_i][1] 231 | t_min = self.hull.T[min_i][0] - m * self.hull.T[min_i][1] 232 | 233 | max_xy = [self.hull[0][max_i], self.hull[1][max_i]] 234 | min_xy = [self.hull[0][min_i], self.hull[1][min_i]] 235 | 236 | distance = np.abs(t_max - t_min) / np.sqrt(1 + m ** 2) 237 | 238 | return distance, np.array([max_xy, min_xy]) 239 | --------------------------------------------------------------------------------