├── .github └── workflows │ ├── maxflow-ci.yml │ └── maxflow-deployment.yml ├── .gitignore ├── MANIFEST.in ├── README.rst ├── doc ├── Makefile ├── make.bat └── source │ ├── _static │ ├── a.png │ ├── a2.png │ ├── binary.png │ ├── comparison.png │ ├── graph.png │ ├── graph2.png │ ├── layout_01.png │ ├── layout_02.png │ ├── layout_03.png │ ├── layout_04.png │ ├── layout_05.png │ ├── layout_06.png │ ├── layout_07.png │ ├── montage.png │ └── small_layout_07.png │ ├── conf.py │ ├── index.rst │ ├── maxflow.rst │ └── tutorial.rst ├── examples ├── a2.png ├── binary_restoration.py ├── examples_utils.py ├── layout_example2.py ├── layout_example3D.py ├── layout_examples.py └── simple.py ├── maxflow ├── __init__.py ├── fastmin.py ├── src │ ├── _maxflow.pyx │ ├── core │ │ ├── CHANGES.TXT │ │ ├── GPL.TXT │ │ ├── README.TXT │ │ ├── block.h │ │ ├── graph.h │ │ ├── instances.inc │ │ └── maxflow.cpp │ ├── fastmin.cpp │ ├── fastmin.h │ ├── grid.h │ ├── pyarray_symbol.h │ └── pyarraymodule.h └── version.py ├── pyproject.toml ├── setup.cfg ├── setup.py └── test_maxflow.py /.github/workflows/maxflow-ci.yml: -------------------------------------------------------------------------------- 1 | name: PyMaxflow tests 2 | 3 | on: 4 | push: 5 | branches: [master] 6 | pull_request: 7 | 8 | jobs: 9 | test: 10 | name: Build and test 11 | runs-on: ubuntu-latest 12 | strategy: 13 | matrix: 14 | python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"] 15 | 16 | steps: 17 | - uses: actions/checkout@v3 18 | - name: Set up Python ${{ matrix.python-version }} 19 | uses: actions/setup-python@v4 20 | with: 21 | python-version: ${{ matrix.python-version }} 22 | - name: Install dependencies 23 | run: | 24 | python -m pip install --upgrade pip 25 | - name: Install the package 26 | run: | 27 | python -m pip install -e . 28 | - name: Install dependencies for test 29 | run: | 30 | python -m pip install pytest>=7.2.0 pytest-cov>=4.0 codecov 31 | python -m pip install imageio networkx 32 | - name: Test and coverage 33 | run: | 34 | mkdir output 35 | python -m pytest --cov=maxflow --cov-report=xml 36 | codecov 37 | - name: Flake8 38 | run: | 39 | python -m pip install flake8 40 | flake8 . 41 | -------------------------------------------------------------------------------- /.github/workflows/maxflow-deployment.yml: -------------------------------------------------------------------------------- 1 | name: PyMaxflow deployment 2 | 3 | on: 4 | push: 5 | tags: 'v[0-9]+*' 6 | 7 | jobs: 8 | deploy-sdist: 9 | name: Deploy source distribution 10 | runs-on: ubuntu-latest 11 | env: 12 | TWINE_USERNAME: __token__ 13 | TWINE_PASSWORD: ${{ secrets.PYPI }} 14 | 15 | steps: 16 | - uses: actions/checkout@v3 17 | - name: Set up Python 18 | uses: actions/setup-python@v4 19 | with: 20 | python-version: '3.10' 21 | - name: Install cibuildwheel 22 | run: | 23 | python -m pip install --upgrade pip 24 | python -m pip install build 25 | - name: Build sdist 26 | run: python -m build --sdist 27 | - name: Deploy sdist 28 | run: | 29 | python3 -m pip install twine 30 | python3 -m twine upload --skip-existing dist/* 31 | 32 | deploy-wheels: 33 | name: Deploy wheels on ${{ matrix.os }} 34 | runs-on: ${{ matrix.os }} 35 | env: 36 | CIBW_ARCHS: "auto64" 37 | CIBW_BUILD: "cp39-* cp310-* cp311-* cp312-* cp313-*" 38 | CIBW_SKIP: "*musllinux* pp*-win* pp*-macosx* pp*" 39 | TWINE_USERNAME: __token__ 40 | TWINE_PASSWORD: ${{ secrets.PYPI }} 41 | 42 | strategy: 43 | matrix: 44 | os: [ubuntu-latest, windows-latest, macos-latest, macos-13] 45 | 46 | steps: 47 | - uses: actions/checkout@v3 48 | - name: Set up Python 49 | uses: actions/setup-python@v4 50 | with: 51 | python-version: '3.9' 52 | - name: Install cibuildwheel 53 | run: | 54 | python -m pip install --upgrade pip 55 | python -m pip install cibuildwheel 56 | - name: Build wheels 57 | run: python3 -m cibuildwheel --output-dir wheelhouse 58 | - name: Deploy 59 | run: | 60 | python3 -m pip install twine 61 | python3 -m twine upload --skip-existing wheelhouse/*.whl 62 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | MANIFEST 2 | maxflow/src/_maxflow.cpp 3 | maxflow/src/_maxflow.h 4 | 5 | .vscode 6 | 7 | # Created by https://www.gitignore.io/api/c,osx,c++,linux,python 8 | 9 | ### C ### 10 | # Prerequisites 11 | *.d 12 | 13 | # Object files 14 | *.o 15 | *.ko 16 | *.obj 17 | *.elf 18 | 19 | # Linker output 20 | *.ilk 21 | *.map 22 | *.exp 23 | 24 | # Precompiled Headers 25 | *.gch 26 | *.pch 27 | 28 | # Libraries 29 | *.lib 30 | *.a 31 | *.la 32 | *.lo 33 | 34 | # Shared objects (inc. Windows DLLs) 35 | *.dll 36 | *.so 37 | *.so.* 38 | *.dylib 39 | 40 | # Executables 41 | *.exe 42 | *.out 43 | *.app 44 | *.i*86 45 | *.x86_64 46 | *.hex 47 | 48 | # Debug files 49 | *.dSYM/ 50 | *.su 51 | *.idb 52 | *.pdb 53 | 54 | # Kernel Module Compile Results 55 | *.mod* 56 | *.cmd 57 | .tmp_versions/ 58 | modules.order 59 | Module.symvers 60 | Mkfile.old 61 | dkms.conf 62 | 63 | ### C++ ### 64 | # Prerequisites 65 | 66 | # Compiled Object files 67 | *.slo 68 | 69 | # Precompiled Headers 70 | 71 | # Compiled Dynamic libraries 72 | 73 | # Fortran module files 74 | *.mod 75 | *.smod 76 | 77 | # Compiled Static libraries 78 | *.lai 79 | 80 | # Executables 81 | 82 | ### Linux ### 83 | *~ 84 | 85 | # temporary files which can be created if a process still has a handle open of a deleted file 86 | .fuse_hidden* 87 | 88 | # KDE directory preferences 89 | .directory 90 | 91 | # Linux trash folder which might appear on any partition or disk 92 | .Trash-* 93 | 94 | # .nfs files are created when an open file is removed but is still being accessed 95 | .nfs* 96 | 97 | ### OSX ### 98 | *.DS_Store 99 | .AppleDouble 100 | .LSOverride 101 | 102 | # Icon must end with two \r 103 | Icon 104 | 105 | # Thumbnails 106 | ._* 107 | 108 | # Files that might appear in the root of a volume 109 | .DocumentRevisions-V100 110 | .fseventsd 111 | .Spotlight-V100 112 | .TemporaryItems 113 | .Trashes 114 | .VolumeIcon.icns 115 | .com.apple.timemachine.donotpresent 116 | 117 | # Directories potentially created on remote AFP share 118 | .AppleDB 119 | .AppleDesktop 120 | Network Trash Folder 121 | Temporary Items 122 | .apdisk 123 | 124 | ### Python ### 125 | # Byte-compiled / optimized / DLL files 126 | __pycache__/ 127 | *.py[cod] 128 | *$py.class 129 | 130 | # C extensions 131 | 132 | # Distribution / packaging 133 | .Python 134 | build/ 135 | develop-eggs/ 136 | dist/ 137 | downloads/ 138 | eggs/ 139 | .eggs/ 140 | lib/ 141 | lib64/ 142 | parts/ 143 | sdist/ 144 | var/ 145 | wheels/ 146 | *.egg-info/ 147 | .installed.cfg 148 | *.egg 149 | 150 | # PyInstaller 151 | # Usually these files are written by a python script from a template 152 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 153 | *.manifest 154 | *.spec 155 | 156 | # Installer logs 157 | pip-log.txt 158 | pip-delete-this-directory.txt 159 | 160 | # Unit test / coverage reports 161 | htmlcov/ 162 | .tox/ 163 | .coverage 164 | .coverage.* 165 | .cache 166 | .pytest_cache/ 167 | nosetests.xml 168 | coverage.xml 169 | *.cover 170 | .hypothesis/ 171 | 172 | # Translations 173 | *.mo 174 | *.pot 175 | 176 | # Flask stuff: 177 | instance/ 178 | .webassets-cache 179 | 180 | # Scrapy stuff: 181 | .scrapy 182 | 183 | # Sphinx documentation 184 | docs/_build/ 185 | 186 | # PyBuilder 187 | target/ 188 | 189 | # Jupyter Notebook 190 | .ipynb_checkpoints 191 | 192 | # pyenv 193 | .python-version 194 | 195 | # celery beat schedule file 196 | celerybeat-schedule.* 197 | 198 | # SageMath parsed files 199 | *.sage.py 200 | 201 | # Environments 202 | .env 203 | .venv 204 | env/ 205 | venv/ 206 | ENV/ 207 | env.bak/ 208 | venv.bak/ 209 | 210 | # Spyder project settings 211 | .spyderproject 212 | .spyproject 213 | 214 | # Rope project settings 215 | .ropeproject 216 | 217 | # mkdocs documentation 218 | /site 219 | 220 | # mypy 221 | .mypy_cache/ 222 | 223 | 224 | # End of https://www.gitignore.io/api/c,osx,c++,linux,python 225 | 226 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include maxflow/*.py 2 | 3 | include maxflow/src/CMakeLists.txt 4 | include maxflow/src/_maxflow.pyx 5 | include maxflow/src/pyarraymodule.h 6 | include maxflow/src/pyarray_symbol.h 7 | include maxflow/src/grid.h 8 | include maxflow/src/fastmin.h 9 | include maxflow/src/fastmin.cpp 10 | exclude maxflow/src/_maxflow.cpp 11 | 12 | include maxflow/src/core/*.h 13 | include maxflow/src/core/*.inc 14 | include maxflow/src/core/*.cpp 15 | include maxflow/src/core/README.TXT 16 | 17 | include examples/*.py 18 | include examples/*.png 19 | 20 | include doc/Makefile 21 | include doc/make.bat 22 | include doc/source/conf.py 23 | include doc/source/*.rst 24 | include doc/source/_static/* 25 | include doc/source/_templates/* 26 | 27 | include setup.py 28 | include README.rst 29 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | PyMaxflow 2 | --------- 3 | PyMaxflow is a Python library for graph construction and maxflow computation 4 | (commonly known as `graph cuts`). 5 | 6 | .. image:: doc/source/_static/small_layout_07.png 7 | :scale: 10 % 8 | 9 | The core of this library is the C++ implementation by Vladimir Kolmogorov, 10 | which can be downloaded from his `homepage `_. 11 | Besides the wrapper to the C++ library, PyMaxflow offers 12 | 13 | * NumPy integration, 14 | * methods for fast construction of common graph 15 | layouts in computer vision and graphics, 16 | * implementation of algorithms for fast energy 17 | minimization which use the ``maxflow`` method: the αβ-swap 18 | and the α-expansion. 19 | 20 | Take a look at the `PyMaxflow documentation `_. 21 | 22 | Example layouts 23 | --------------- 24 | 25 | PyMaxflow offers methods to easily build advanced network layouts with a few API 26 | calls. These are examples from `layout_examples.py `_. 27 | 28 | .. image:: doc/source/_static/montage.png 29 | 30 | 31 | Installation 32 | ------------ 33 | 34 | Open a terminal and write:: 35 | 36 | $ pip install PyMaxflow 37 | 38 | 39 | Manual installation 40 | ------------------- 41 | 42 | Download the source code or clone the Github repository. Open a terminal and 43 | write:: 44 | 45 | $ cd path/to/PyMaxflow 46 | $ python setup.py build 47 | ... lots of text ... 48 | 49 | If everything went fine, you should be able to install the package with:: 50 | 51 | $ python setup.py install 52 | -------------------------------------------------------------------------------- /doc/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = build 9 | 10 | # Internal variables. 11 | PAPEROPT_a4 = -D latex_paper_size=a4 12 | PAPEROPT_letter = -D latex_paper_size=letter 13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source 14 | 15 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest 16 | 17 | help: 18 | @echo "Please use \`make ' where is one of" 19 | @echo " html to make standalone HTML files" 20 | @echo " dirhtml to make HTML files named index.html in directories" 21 | @echo " singlehtml to make a single large HTML file" 22 | @echo " pickle to make pickle files" 23 | @echo " json to make JSON files" 24 | @echo " htmlhelp to make HTML files and a HTML help project" 25 | @echo " qthelp to make HTML files and a qthelp project" 26 | @echo " devhelp to make HTML files and a Devhelp project" 27 | @echo " epub to make an epub" 28 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 29 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 30 | @echo " text to make text files" 31 | @echo " man to make manual pages" 32 | @echo " changes to make an overview of all changed/added/deprecated items" 33 | @echo " linkcheck to check all external links for integrity" 34 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 35 | 36 | clean: 37 | -rm -rf $(BUILDDIR)/* 38 | 39 | html: 40 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 41 | @echo 42 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 43 | 44 | dirhtml: 45 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 46 | @echo 47 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 48 | 49 | singlehtml: 50 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 51 | @echo 52 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 53 | 54 | pickle: 55 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 56 | @echo 57 | @echo "Build finished; now you can process the pickle files." 58 | 59 | json: 60 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 61 | @echo 62 | @echo "Build finished; now you can process the JSON files." 63 | 64 | htmlhelp: 65 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 66 | @echo 67 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 68 | ".hhp project file in $(BUILDDIR)/htmlhelp." 69 | 70 | qthelp: 71 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 72 | @echo 73 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 74 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 75 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/PyMaxflow.qhcp" 76 | @echo "To view the help file:" 77 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/PyMaxflow.qhc" 78 | 79 | devhelp: 80 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 81 | @echo 82 | @echo "Build finished." 83 | @echo "To view the help file:" 84 | @echo "# mkdir -p $$HOME/.local/share/devhelp/PyMaxflow" 85 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/PyMaxflow" 86 | @echo "# devhelp" 87 | 88 | epub: 89 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 90 | @echo 91 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 92 | 93 | latex: 94 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 95 | @echo 96 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 97 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 98 | "(use \`make latexpdf' here to do that automatically)." 99 | 100 | latexpdf: 101 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 102 | @echo "Running LaTeX files through pdflatex..." 103 | make -C $(BUILDDIR)/latex all-pdf 104 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 105 | 106 | text: 107 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 108 | @echo 109 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 110 | 111 | man: 112 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 113 | @echo 114 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 115 | 116 | changes: 117 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 118 | @echo 119 | @echo "The overview file is in $(BUILDDIR)/changes." 120 | 121 | linkcheck: 122 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 123 | @echo 124 | @echo "Link check complete; look for any errors in the above output " \ 125 | "or in $(BUILDDIR)/linkcheck/output.txt." 126 | 127 | doctest: 128 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 129 | @echo "Testing of doctests in the sources finished, look at the " \ 130 | "results in $(BUILDDIR)/doctest/output.txt." 131 | -------------------------------------------------------------------------------- /doc/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% source 10 | if NOT "%PAPER%" == "" ( 11 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 12 | ) 13 | 14 | if "%1" == "" goto help 15 | 16 | if "%1" == "help" ( 17 | :help 18 | echo.Please use `make ^` where ^ is one of 19 | echo. html to make standalone HTML files 20 | echo. dirhtml to make HTML files named index.html in directories 21 | echo. singlehtml to make a single large HTML file 22 | echo. pickle to make pickle files 23 | echo. json to make JSON files 24 | echo. htmlhelp to make HTML files and a HTML help project 25 | echo. qthelp to make HTML files and a qthelp project 26 | echo. devhelp to make HTML files and a Devhelp project 27 | echo. epub to make an epub 28 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 29 | echo. text to make text files 30 | echo. man to make manual pages 31 | echo. changes to make an overview over all changed/added/deprecated items 32 | echo. linkcheck to check all external links for integrity 33 | echo. doctest to run all doctests embedded in the documentation if enabled 34 | goto end 35 | ) 36 | 37 | if "%1" == "clean" ( 38 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 39 | del /q /s %BUILDDIR%\* 40 | goto end 41 | ) 42 | 43 | if "%1" == "html" ( 44 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 45 | echo. 46 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 47 | goto end 48 | ) 49 | 50 | if "%1" == "dirhtml" ( 51 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 52 | echo. 53 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 54 | goto end 55 | ) 56 | 57 | if "%1" == "singlehtml" ( 58 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 59 | echo. 60 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 61 | goto end 62 | ) 63 | 64 | if "%1" == "pickle" ( 65 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 66 | echo. 67 | echo.Build finished; now you can process the pickle files. 68 | goto end 69 | ) 70 | 71 | if "%1" == "json" ( 72 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 73 | echo. 74 | echo.Build finished; now you can process the JSON files. 75 | goto end 76 | ) 77 | 78 | if "%1" == "htmlhelp" ( 79 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 80 | echo. 81 | echo.Build finished; now you can run HTML Help Workshop with the ^ 82 | .hhp project file in %BUILDDIR%/htmlhelp. 83 | goto end 84 | ) 85 | 86 | if "%1" == "qthelp" ( 87 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 88 | echo. 89 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 90 | .qhcp project file in %BUILDDIR%/qthelp, like this: 91 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\PyMaxflow.qhcp 92 | echo.To view the help file: 93 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\PyMaxflow.ghc 94 | goto end 95 | ) 96 | 97 | if "%1" == "devhelp" ( 98 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 99 | echo. 100 | echo.Build finished. 101 | goto end 102 | ) 103 | 104 | if "%1" == "epub" ( 105 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 106 | echo. 107 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 108 | goto end 109 | ) 110 | 111 | if "%1" == "latex" ( 112 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 113 | echo. 114 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 115 | goto end 116 | ) 117 | 118 | if "%1" == "text" ( 119 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 120 | echo. 121 | echo.Build finished. The text files are in %BUILDDIR%/text. 122 | goto end 123 | ) 124 | 125 | if "%1" == "man" ( 126 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 127 | echo. 128 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 129 | goto end 130 | ) 131 | 132 | if "%1" == "changes" ( 133 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 134 | echo. 135 | echo.The overview file is in %BUILDDIR%/changes. 136 | goto end 137 | ) 138 | 139 | if "%1" == "linkcheck" ( 140 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 141 | echo. 142 | echo.Link check complete; look for any errors in the above output ^ 143 | or in %BUILDDIR%/linkcheck/output.txt. 144 | goto end 145 | ) 146 | 147 | if "%1" == "doctest" ( 148 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 149 | echo. 150 | echo.Testing of doctests in the sources finished, look at the ^ 151 | results in %BUILDDIR%/doctest/output.txt. 152 | goto end 153 | ) 154 | 155 | :end 156 | -------------------------------------------------------------------------------- /doc/source/_static/a.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pmneila/PyMaxflow/ce18d01171fe3a8f5b9ec808beb87cfcc1610081/doc/source/_static/a.png -------------------------------------------------------------------------------- /doc/source/_static/a2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pmneila/PyMaxflow/ce18d01171fe3a8f5b9ec808beb87cfcc1610081/doc/source/_static/a2.png -------------------------------------------------------------------------------- /doc/source/_static/binary.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pmneila/PyMaxflow/ce18d01171fe3a8f5b9ec808beb87cfcc1610081/doc/source/_static/binary.png -------------------------------------------------------------------------------- /doc/source/_static/comparison.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pmneila/PyMaxflow/ce18d01171fe3a8f5b9ec808beb87cfcc1610081/doc/source/_static/comparison.png -------------------------------------------------------------------------------- /doc/source/_static/graph.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pmneila/PyMaxflow/ce18d01171fe3a8f5b9ec808beb87cfcc1610081/doc/source/_static/graph.png -------------------------------------------------------------------------------- /doc/source/_static/graph2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pmneila/PyMaxflow/ce18d01171fe3a8f5b9ec808beb87cfcc1610081/doc/source/_static/graph2.png -------------------------------------------------------------------------------- /doc/source/_static/layout_01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pmneila/PyMaxflow/ce18d01171fe3a8f5b9ec808beb87cfcc1610081/doc/source/_static/layout_01.png -------------------------------------------------------------------------------- /doc/source/_static/layout_02.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pmneila/PyMaxflow/ce18d01171fe3a8f5b9ec808beb87cfcc1610081/doc/source/_static/layout_02.png -------------------------------------------------------------------------------- /doc/source/_static/layout_03.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pmneila/PyMaxflow/ce18d01171fe3a8f5b9ec808beb87cfcc1610081/doc/source/_static/layout_03.png -------------------------------------------------------------------------------- /doc/source/_static/layout_04.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pmneila/PyMaxflow/ce18d01171fe3a8f5b9ec808beb87cfcc1610081/doc/source/_static/layout_04.png -------------------------------------------------------------------------------- /doc/source/_static/layout_05.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pmneila/PyMaxflow/ce18d01171fe3a8f5b9ec808beb87cfcc1610081/doc/source/_static/layout_05.png -------------------------------------------------------------------------------- /doc/source/_static/layout_06.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pmneila/PyMaxflow/ce18d01171fe3a8f5b9ec808beb87cfcc1610081/doc/source/_static/layout_06.png -------------------------------------------------------------------------------- /doc/source/_static/layout_07.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pmneila/PyMaxflow/ce18d01171fe3a8f5b9ec808beb87cfcc1610081/doc/source/_static/layout_07.png -------------------------------------------------------------------------------- /doc/source/_static/montage.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pmneila/PyMaxflow/ce18d01171fe3a8f5b9ec808beb87cfcc1610081/doc/source/_static/montage.png -------------------------------------------------------------------------------- /doc/source/_static/small_layout_07.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pmneila/PyMaxflow/ce18d01171fe3a8f5b9ec808beb87cfcc1610081/doc/source/_static/small_layout_07.png -------------------------------------------------------------------------------- /doc/source/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # PyMaxflow documentation build configuration file, created by 4 | # sphinx-quickstart on Wed Apr 20 07:08:53 2011. 5 | # 6 | # This file is execfile()d with the current directory set to its containing dir. 7 | # 8 | # Note that not all possible configuration values are present in this 9 | # autogenerated file. 10 | # 11 | # All configuration values have a default; values that are commented out 12 | # serve to show the default. 13 | 14 | import sys, os 15 | import maxflow 16 | 17 | # If extensions (or modules to document with autodoc) are in another directory, 18 | # add these directories to sys.path here. If the directory is relative to the 19 | # documentation root, use os.path.abspath to make it absolute, like shown here. 20 | #sys.path.insert(0, os.path.abspath('.')) 21 | 22 | # -- General configuration ----------------------------------------------------- 23 | 24 | # If your documentation needs a minimal Sphinx version, state it here. 25 | #needs_sphinx = '1.0' 26 | 27 | # Add any Sphinx extension module names here, as strings. They can be extensions 28 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 29 | extensions = ['sphinx.ext.imgmath', 'sphinx.ext.autodoc'] 30 | 31 | # Add any paths that contain templates here, relative to this directory. 32 | templates_path = ['_templates'] 33 | 34 | # The suffix of source filenames. 35 | source_suffix = '.rst' 36 | 37 | # The encoding of source files. 38 | #source_encoding = 'utf-8-sig' 39 | 40 | # The master toctree document. 41 | master_doc = 'index' 42 | 43 | # General information about the project. 44 | project = u'PyMaxflow' 45 | copyright = u'2011-2021, @pmneila' 46 | 47 | # The version info for the project you're documenting, acts as replacement for 48 | # |version| and |release|, also used in various other places throughout the 49 | # built documents. 50 | # 51 | # The short X.Y version. 52 | version = maxflow.__version_str__ 53 | # The full version, including alpha/beta/rc tags. 54 | release = maxflow.__version_str__ 55 | 56 | # The language for content autogenerated by Sphinx. Refer to documentation 57 | # for a list of supported languages. 58 | #language = None 59 | 60 | # There are two options for replacing |today|: either, you set today to some 61 | # non-false value, then it is used: 62 | #today = '' 63 | # Else, today_fmt is used as the format for a strftime call. 64 | #today_fmt = '%B %d, %Y' 65 | 66 | # List of patterns, relative to source directory, that match files and 67 | # directories to ignore when looking for source files. 68 | exclude_patterns = [] 69 | 70 | # The reST default role (used for this markup: `text`) to use for all documents. 71 | #default_role = None 72 | 73 | # If true, '()' will be appended to :func: etc. cross-reference text. 74 | #add_function_parentheses = True 75 | 76 | # If true, the current module name will be prepended to all description 77 | # unit titles (such as .. function::). 78 | #add_module_names = True 79 | 80 | # If true, sectionauthor and moduleauthor directives will be shown in the 81 | # output. They are ignored by default. 82 | #show_authors = False 83 | 84 | # The name of the Pygments (syntax highlighting) style to use. 85 | pygments_style = 'sphinx' 86 | 87 | # A list of ignored prefixes for module index sorting. 88 | #modindex_common_prefix = [] 89 | 90 | 91 | # -- Options for HTML output --------------------------------------------------- 92 | 93 | # The theme to use for HTML and HTML Help pages. See the documentation for 94 | # a list of builtin themes. 95 | html_theme = 'nature' 96 | 97 | # Theme options are theme-specific and customize the look and feel of a theme 98 | # further. For a list of options available for each theme, see the 99 | # documentation. 100 | #html_theme_options = {} 101 | 102 | # Add any paths that contain custom themes here, relative to this directory. 103 | #html_theme_path = [] 104 | 105 | # The name for this set of Sphinx documents. If None, it defaults to 106 | # " v documentation". 107 | #html_title = None 108 | 109 | # A shorter title for the navigation bar. Default is the same as html_title. 110 | #html_short_title = None 111 | 112 | # The name of an image file (relative to this directory) to place at the top 113 | # of the sidebar. 114 | #html_logo = None 115 | 116 | # The name of an image file (within the static path) to use as favicon of the 117 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 118 | # pixels large. 119 | #html_favicon = None 120 | 121 | # Add any paths that contain custom static files (such as style sheets) here, 122 | # relative to this directory. They are copied after the builtin static files, 123 | # so a file named "default.css" will overwrite the builtin "default.css". 124 | html_static_path = ['_static'] 125 | 126 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 127 | # using the given strftime format. 128 | #html_last_updated_fmt = '%b %d, %Y' 129 | 130 | # If true, SmartyPants will be used to convert quotes and dashes to 131 | # typographically correct entities. 132 | #html_use_smartypants = True 133 | 134 | # Custom sidebar templates, maps document names to template names. 135 | #html_sidebars = {} 136 | 137 | # Additional templates that should be rendered to pages, maps page names to 138 | # template names. 139 | #html_additional_pages = {} 140 | 141 | # If false, no module index is generated. 142 | #html_domain_indices = True 143 | 144 | # If false, no index is generated. 145 | #html_use_index = True 146 | 147 | # If true, the index is split into individual pages for each letter. 148 | #html_split_index = False 149 | 150 | # If true, links to the reST sources are added to the pages. 151 | #html_show_sourcelink = True 152 | 153 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 154 | #html_show_sphinx = True 155 | 156 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 157 | #html_show_copyright = True 158 | 159 | # If true, an OpenSearch description file will be output, and all pages will 160 | # contain a tag referring to it. The value of this option must be the 161 | # base URL from which the finished HTML is served. 162 | #html_use_opensearch = '' 163 | 164 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 165 | #html_file_suffix = None 166 | 167 | # Output file base name for HTML help builder. 168 | htmlhelp_basename = 'PyMaxflowdoc' 169 | 170 | 171 | # -- Options for LaTeX output -------------------------------------------------- 172 | 173 | # The paper size ('letter' or 'a4'). 174 | #latex_paper_size = 'letter' 175 | 176 | # The font size ('10pt', '11pt' or '12pt'). 177 | #latex_font_size = '10pt' 178 | 179 | # Grouping the document tree into LaTeX files. List of tuples 180 | # (source start file, target name, title, author, documentclass [howto/manual]). 181 | latex_documents = [ 182 | ('index', 'PyMaxflow.tex', u'PyMaxflow Documentation', 183 | u'Pablo Márquez Neila', 'manual'), 184 | ] 185 | 186 | # The name of an image file (relative to this directory) to place at the top of 187 | # the title page. 188 | #latex_logo = None 189 | 190 | # For "manual" documents, if this is true, then toplevel headings are parts, 191 | # not chapters. 192 | #latex_use_parts = False 193 | 194 | # If true, show page references after internal links. 195 | #latex_show_pagerefs = False 196 | 197 | # If true, show URL addresses after external links. 198 | #latex_show_urls = False 199 | 200 | # Additional stuff for the LaTeX preamble. 201 | #latex_preamble = "\usepackage{tkz-bergeasdfas aw2#" 202 | 203 | #latex_elements = {"preamble":"\usepackage{tkz-bergsdfe}"} 204 | 205 | # Documents to append as an appendix to all manuals. 206 | #latex_appendices = [] 207 | 208 | # If false, no module index is generated. 209 | #latex_domain_indices = True 210 | 211 | 212 | # -- Options for manual page output -------------------------------------------- 213 | 214 | # One entry per manual page. List of tuples 215 | # (source start file, name, description, authors, manual section). 216 | man_pages = [ 217 | ('index', 'pymaxflow', u'PyMaxflow Documentation', 218 | [u'Pablo Márquez Neila'], 1) 219 | ] 220 | -------------------------------------------------------------------------------- /doc/source/index.rst: -------------------------------------------------------------------------------- 1 | .. PyMaxflow documentation master file, created by 2 | sphinx-quickstart on Wed Apr 20 07:08:53 2011. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to PyMaxflow's documentation! 7 | ===================================== 8 | 9 | *PyMaxflow* is a Python library to build flow networks and compute their maximum 10 | flow/minimum cut (commonly known as `graph cuts`) as described in [BOYKOV04]_. 11 | This is a common technique used in different problems of image processing, 12 | computer vision and computer graphics. The core of this library is the C++ 13 | maxflow implementation by Vladimir Kolmogorov, which can be downloaded from his 14 | `homepage `_. Besides being a wrapper 15 | to the C++ library, PyMaxflow also offers 16 | 17 | * NumPy integration, 18 | * methods for fast declaration of complex network layouts with a single API 19 | call, which avoids the much slower one-call-per-edge alternative offered by 20 | the wrapped functions of the core C++ library, and 21 | * implementation of algorithms for fast energy minimization with more than two 22 | labels: the αβ-swap and the α-expansion. 23 | 24 | Take a look at the :ref:`tutorial`. 25 | 26 | Contents 27 | ======== 28 | 29 | .. toctree:: 30 | :maxdepth: 2 31 | 32 | tutorial 33 | maxflow 34 | 35 | License 36 | ======= 37 | 38 | This software is licensed under the GPL. 39 | 40 | .. important:: 41 | The core of the library is the C++ implementation by Vladimir Kolmogorov. It 42 | is also licensed under the GPL, but it **REQUIRES** that you cite [BOYKOV04]_ 43 | in any resulting publication if you use this code for research purposes. This 44 | requirement extends to *PyMaxflow*. 45 | 46 | Indices and tables 47 | ================== 48 | 49 | * :ref:`genindex` 50 | * :ref:`modindex` 51 | * :ref:`search` 52 | 53 | .. [BOYKOV04] *An Experimental Comparison of Min-Cut/Max-Flow Algorithms for 54 | Energy Minimization in Vision.* Yuri Boykov and Vladimir Kolmogorov. In 55 | IEEE Transactions on Pattern Analysis and Machine Intelligence (PAMI), September 2004 56 | -------------------------------------------------------------------------------- /doc/source/maxflow.rst: -------------------------------------------------------------------------------- 1 | 2 | Maxflow package 3 | =============== 4 | 5 | .. automodule:: maxflow 6 | 7 | The module :py:mod:`maxflow` has the classes :py:class:`maxflow.GraphInt` and 8 | :py:class:`maxflow.GraphFloat`. Both have the same methods and behavior. They 9 | only differ in the data type of the flow network. For conciseness, this page 10 | includes the documentation of just one of these classes. 11 | 12 | Note that these classes can be accessed with a template-like syntax using the 13 | dictionary ``maxflow.Graph``: ``maxflow.Graph[int]`` and 14 | ``maxflow.Graph[float]``. 15 | 16 | .. autoclass:: GraphInt 17 | :members: __init__, add_nodes, add_grid_nodes, add_edge, add_tedge, add_grid_edges, add_grid_tedges, get_node_count, get_edge_count, maxflow, get_segment, get_grid_segments, get_nx_graph 18 | 19 | .. automodule:: maxflow.fastmin 20 | :members: 21 | -------------------------------------------------------------------------------- /doc/source/tutorial.rst: -------------------------------------------------------------------------------- 1 | 2 | .. _tutorial: 3 | 4 | Tutorial 5 | ======== 6 | 7 | .. The *maximum flow* (maxflow) problem is a common technique 8 | in optimization and graph theory. Given a directed graph where each edge has 9 | a capacity, i.e., a flow network, the maximum flow problem consists on 10 | finding a feasible flow between a single source node and a single sink node 11 | that is maximum. 12 | 13 | This tutorial shows some basic examples on how to import and use *PyMaxflow*. It 14 | is aimed to people who are already familiar with the maxflow problem and its 15 | applications in computer vision and image processing, and want to learn the 16 | basic usage of *PyMaxflow*. This is not, in any case, a tutorial on graph-cuts. 17 | 18 | Getting started 19 | --------------- 20 | 21 | Install *PyMaxflow* using pip:: 22 | 23 | pip install PyMaxflow 24 | 25 | Once installed, import it as usual:: 26 | 27 | import maxflow 28 | 29 | # Print the version 30 | print(maxflow.__version__) 31 | 32 | A flow network with two nodes 33 | ----------------------------- 34 | 35 | This example builds a simple flow network and finds its maximum flow. 36 | 37 | .. image:: _static/graph.png 38 | :scale: 50 % 39 | 40 | This network has two *terminal* nodes, the source :math:`s` and the sink 41 | :math:`t`, and two *non-terminal* nodes, labeled 0 and 1. In *PyMaxflow*, 42 | terminal nodes :math:`s` and :math:`t` are always implicitly present in the 43 | network, and it is not necessary (or even possible) to declare them explicitly. 44 | In addition, terminal edges (connecting non-terminal nodes with terminal nodes), 45 | and non-terminal edges (connecting non-terminal nodes), are treated differently. 46 | 47 | The following code uses the standard `single-edge` methods of PyMaxflow to build 48 | this simple network. Note that these methods might be slow in practice for 49 | networks with many nodes and edges:: 50 | 51 | import maxflow 52 | 53 | # Create a graph with integer capacities, with 2 non-terminal nodes and 2 non-terminal edges. 54 | # Note that these numbers are just indicative (read below) 55 | g = maxflow.Graph[int](2, 2) 56 | # Add two (non-terminal) nodes. Get the index to the first one. 57 | nodes = g.add_nodes(2) 58 | # Create the non-terminal edges (forwards and backwards) with the given capacities between nodes 0 and 1. 59 | g.add_edge(nodes[0], nodes[1], 1, 2) 60 | # Set the capacities of the terminal edges... 61 | # ...for the first node 62 | g.add_tedge(nodes[0], 2, 5) 63 | # ...for the second node 64 | g.add_tedge(nodes[1], 9, 4) 65 | 66 | The non-terminal edges are created with ``add_edge``. The terminal edges are 67 | created with ``add_tedge``. 68 | 69 | The type of the capacities can be *int*, as in the example, or *float*. In that 70 | case, the graph declaration would be:: 71 | 72 | g = maxflow.Graph[float](2, 2) 73 | 74 | The constructor parameters ``(2, 2)`` are initial estimations of the number of 75 | nodes and the number of non-terminal edges. These estimations do not need to be 76 | correct or even approximate (it is possible to set them to ``0``), but a good 77 | estimation allows for more efficient memory management. Consult the 78 | documentation of the constructor for more details. In this specific example, the 79 | number of nodes and non-terminal edges was known in advance. 80 | 81 | Now we can find the maximum flow in the graph:: 82 | 83 | flow = g.maxflow() 84 | print(f"Maximum flow: {flow}") 85 | 86 | Finally, we want to know the the partition given by the minimum cut:: 87 | 88 | print(f"Segment of the node 0: {g.get_segment(nodes[0])}") 89 | print(f"Segment of the node 1: {g.get_segment(nodes[1])}") 90 | 91 | The method ``get_segment`` returns ``0`` when the given node belongs to the 92 | source partition and ``1`` when the node belongs to the sink partition. 93 | 94 | This example is available in :file:`examples/simple.py`. Running the code will 95 | print:: 96 | 97 | Maximum flow: 8 98 | Segment of the node 0: 1 99 | Segment of the node 1: 0 100 | 101 | This means that the minimum cut cuts the graph in this way: 102 | 103 | .. image:: _static/graph2.png 104 | :scale: 50 % 105 | 106 | The severed edges are marked with dashed lines. Indeed, the sum of the 107 | capacities of these edges is equal to the maximum flow 8. 108 | 109 | Binary image restoration 110 | ------------------------ 111 | 112 | This example shows how to build a 4-connected grid layout of non-terminal nodes 113 | using the advanced multi-edge functions of PyMaxflow. While this example focuses 114 | on a relatively simple 4-connected grid, these multi-edge functions are flexible 115 | to create very complex networks involving many nodes and edges with a few calls. 116 | More details are given in the following section. 117 | 118 | We will use the 4-connected grid network to remove Gaussian noise from a binary 119 | image. The original, noise-free image is 120 | 121 | .. image:: _static/a.png 122 | 123 | The noisy version was obtained adding strong Gaussian noise to the original 124 | image: 125 | 126 | .. image:: _static/a2.png 127 | 128 | We will restore the image minimizing the energy 129 | 130 | .. math:: 131 | E(\mathbf{x}) = \sum_i D_i(x_i) + \sum_{(i,j)\in\mathcal{C}} K|x_i - x_j|. 132 | 133 | :math:`\mathbf{x} \in \{0,1\}^N` are the values of the restored image, :math:`N` 134 | is the number of pixels. The unary term :math:`D_i(0)` (resp. :math:`D_i(1)`) 135 | is the penalty for assigning the value 0 (resp. 1) to the i-th pixel. Each 136 | :math:`D_i` depends on the values of the noisy image, which are denoted as 137 | :math:`p_i`: 138 | 139 | .. math:: 140 | D_i(x_i) = \begin{cases} p_i & \textrm{if } x_i=0\\ 255-p_i & \textrm{if } x_i=1 \end{cases}. 141 | 142 | Thus, :math:`D_i` is low when assigning the label 0 to dark pixels or the label 143 | 1 to bright pixels, and high otherwise. The value :math:`K` is the 144 | regularization strength. The larger :math:`K` the smoother the restoration. We 145 | arbitrarily fix it to 50. 146 | 147 | The maximum flow algorithm is widely used to minimize energy functions of this 148 | type. We build a network to represent the above energy. This network has a 149 | non-terminal node per image pixel, and the nodes are connected in a 4-connected 150 | grid arrangement. The capacities of all non-terminal edges is :math:`K`. The 151 | capacities of the edges from the source node are set to :math:`D_i(0)`, and the 152 | capacities of the edges to the sink node are :math:`D_i(1)`. 153 | 154 | .. note:: It could be possible to build this network as we did in the first 155 | example. First, add all the nodes with ``add_nodes``. Then, iterate over the 156 | nodes adding the non-terminal edges with ``add_edge``, and finally add the 157 | capacities of the terminal edges calling ``add_tedge`` once per pixel. While 158 | this approach is feasible, it is very slow in Python, especially when 159 | dealing with large images or stacks of images. 160 | 161 | *PyMaxflow* provides methods for building complex networks with a few calls. The 162 | method ``add_grid_nodes`` adds multiple nodes and returns their indices in a 163 | convenient n-dimensional array with the given shape; ``add_grid_edges`` adds 164 | edges to the grid with a given neighborhood structure (4-connected by default); 165 | and ``add_grid_tedges`` sets the capacities of the terminal edges for multiple 166 | nodes:: 167 | 168 | # Create the graph. 169 | g = maxflow.Graph[int]() 170 | # Add the nodes. nodeids has the identifiers of the nodes in the grid. 171 | # Note that nodeids.shape == img.shape 172 | nodeids = g.add_grid_nodes(img.shape) 173 | # Add non-terminal edges with the same capacity. 174 | g.add_grid_edges(nodeids, 50) 175 | # Add the terminal edges. The image pixels are the capacities 176 | # of the edges from the source node. The inverted image pixels 177 | # are the capacities of the edges to the sink node. 178 | g.add_grid_tedges(nodeids, img, 255-img) 179 | 180 | Perform the maxflow computation and get the results:: 181 | 182 | # Find the maximum flow. 183 | g.maxflow() 184 | # Get the segments of the nodes in the grid. 185 | # sgm.shape == nodeids.shape 186 | sgm = g.get_grid_segments(nodeids) 187 | 188 | The method ``get_grid_segments`` returns an array with the same shape than 189 | ``nodeids``. It is almost equivalent to calling ``get_segment`` once for each 190 | node in ``nodeids``, but much faster, and preserving the shape of the input. For 191 | the i-th cell, the array stores ``False`` if the i-th node belongs to the source 192 | segment (i.e., the corresponding pixel has the label 1) and ``True`` if the node 193 | belongs to the sink segment (i.e., the corresponding pixel has the label 0). We 194 | now get the labels for each pixel:: 195 | 196 | # The labels should be 1 where sgm is False and 0 otherwise. 197 | img2 = np.int64(np.logical_not(sgm)) 198 | # Show the result. 199 | from matplotlib import pyplot as ppl 200 | ppl.imshow(img2) 201 | ppl.show() 202 | 203 | The result is: 204 | 205 | .. image:: _static/binary.png 206 | :scale: 75 % 207 | 208 | This is a comparison between the original image (left), the noisy one (center) 209 | and the restoration of this example (right): 210 | 211 | .. image:: _static/comparison.png 212 | :scale: 50 % 213 | 214 | Complex grids with ``add_grid_edges`` 215 | ------------------------------------- 216 | 217 | The method ``add_grid_edges`` is a powerful tool to create complex network 218 | layouts: 219 | 220 | .. image:: _static/layout_01.png 221 | :scale: 25 % 222 | 223 | .. image:: _static/layout_02.png 224 | :scale: 25 % 225 | 226 | .. image:: _static/layout_03.png 227 | :scale: 25 % 228 | 229 | .. image:: _static/layout_04.png 230 | :scale: 25 % 231 | 232 | .. image:: _static/layout_05.png 233 | :scale: 25 % 234 | 235 | .. image:: _static/layout_06.png 236 | :scale: 25 % 237 | 238 | .. image:: _static/layout_07.png 239 | :scale: 25 % 240 | 241 | The best way to understand the potential applications of ``add_grid_edges`` is 242 | to look at the examples of the `PyMaxflow repository 243 | `_. 244 | 245 | * The file :file:`examples/layout_examples.py` shows a variety of network 246 | layouts created with ``add_grid_edges``. 247 | * A more advanced example in :file:`examples/layout_example2.py` builds a 248 | complex layout with several calls to ``add_grid_edges`` and 249 | ``add_grid_tedges``. 250 | * The file :file:`examples/layout_example3D.py` contains the definition a 3D 251 | grid layout. 252 | 253 | The documentation 254 | of :py:meth:`maxflow.GraphInt.add_grid_edges` also contains a few useful use 255 | cases. 256 | 257 | .. 258 | comment:: The first argument of ``add_grid_edges`` is ``nodeids``. It contains an array of 259 | node identifiers with the shape of the grid of nodes where the edges will be 260 | added. 261 | 262 | .. note:: The ``nodeids`` argument of ``add_grid_edges`` can be reshaped, 263 | modified, or reorganized to suit the desired layout of the edges to add. It 264 | can even contain repeated node IDs (for example, to connect a single node to 265 | an arbitrary set of nodes). It is not necessary in any case that ``nodeids`` 266 | is the output of ``add_grid_nodes``, as happened in the previous section. 267 | 268 | ``add_grid_edges`` determines the edges to add and their capacities using the 269 | arguments ``weights`` and ``structure``. 270 | 271 | ``weights`` is an array and its shape must be broadcastable to the shape of 272 | ``nodeids``. Thus, every node will have a associated weight. ``structure`` is an 273 | array with the same number of dimensions as ``nodeids`` and with an odd shape 274 | (typically ``structure.shape == (3, 3, ...)``, but this is not necessary). 275 | ``structure`` defines the local neighborhood of each node. 276 | 277 | Given a node in ``nodeids``, the ``structure`` array is centered on it. Edges 278 | are created from that node to the nodes of its neighborhood corresponding to 279 | nonzero entries of ``structure``. The capacity of the new edge will be the 280 | product of the ``weight`` of the initial node and the corresponding value in 281 | ``structure``. Additionally, a reverse edge with the same capacity will be added 282 | if the argument ``symmetric`` is ``True`` (by default). 283 | 284 | Therefore, the ``weights`` argument allows to define an inhomogeneous graph, 285 | with different capacities in different areas of the grid. ``structure`` defines 286 | the local neighborhood of the layout and enables anisotropic edges, with 287 | different capacities depending on their orientation. 288 | -------------------------------------------------------------------------------- /examples/a2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pmneila/PyMaxflow/ce18d01171fe3a8f5b9ec808beb87cfcc1610081/examples/a2.png -------------------------------------------------------------------------------- /examples/binary_restoration.py: -------------------------------------------------------------------------------- 1 | 2 | import numpy as np 3 | from imageio.v3 import imread 4 | from matplotlib import pyplot as ppl 5 | 6 | import maxflow 7 | 8 | img = imread("a2.png") 9 | 10 | # Create the graph. 11 | g = maxflow.Graph[int](0, 0) 12 | # Add the nodes. 13 | nodeids = g.add_grid_nodes(img.shape) 14 | # Add edges with the same capacities. 15 | g.add_grid_edges(nodeids, 50) 16 | # Add the terminal edges. 17 | g.add_grid_tedges(nodeids, img, 255-img) 18 | 19 | # Find the maximum flow. 20 | g.maxflow() 21 | # Get the segments. 22 | sgm = g.get_grid_segments(nodeids) 23 | 24 | # The labels should be 1 where sgm is False and 0 otherwise. 25 | img2 = np.int64(np.logical_not(sgm)) 26 | # Show the result. 27 | ppl.imshow(img2, cmap=ppl.cm.gray, interpolation='nearest') 28 | ppl.show() 29 | -------------------------------------------------------------------------------- /examples/examples_utils.py: -------------------------------------------------------------------------------- 1 | 2 | import numpy as np 3 | import networkx as nx 4 | 5 | import matplotlib.pyplot as plt 6 | 7 | 8 | def plot_graph_2d(graph, nodes_shape, plot_weights=True, plot_terminals=True, font_size=7): 9 | 10 | X, Y = np.mgrid[:nodes_shape[0], :nodes_shape[1]] 11 | aux = np.array([Y.ravel(), X[::-1].ravel()]).T 12 | positions = {i: v for i, v in enumerate(aux)} 13 | positions['s'] = (-1, nodes_shape[0] / 2.0 - 0.5) 14 | positions['t'] = (nodes_shape[1], nodes_shape[0] / 2.0 - 0.5) 15 | 16 | nxgraph = graph.get_nx_graph() 17 | if not plot_terminals: 18 | nxgraph.remove_nodes_from(['s', 't']) 19 | 20 | plt.clf() 21 | nx.draw(nxgraph, pos=positions) 22 | 23 | if plot_weights: 24 | edge_labels = {} 25 | for u, v, d in nxgraph.edges(data=True): 26 | edge_labels[(u, v)] = d['weight'] 27 | nx.draw_networkx_edge_labels(nxgraph, 28 | pos=positions, 29 | edge_labels=edge_labels, 30 | label_pos=0.3, 31 | font_size=font_size) 32 | 33 | plt.axis('equal') 34 | plt.show() 35 | 36 | 37 | def plot_graph_3d(graph, nodes_shape, plot_terminal=True, plot_weights=True, font_size=7): 38 | 39 | w_h = nodes_shape[1] * nodes_shape[2] 40 | X, Y = np.mgrid[:nodes_shape[1], :nodes_shape[2]] 41 | aux = np.array([Y.ravel(), X[::-1].ravel()]).T 42 | positions = {i: v for i, v in enumerate(aux)} 43 | 44 | for i in range(1, nodes_shape[0]): 45 | for j in range(w_h): 46 | positions[w_h * i + j] = [positions[j][0] + 0.3 * i, positions[j][1] + 0.2 * i] 47 | 48 | positions['s'] = np.array([-1, nodes_shape[1] / 2.0 - 0.5]) 49 | positions['t'] = np.array([nodes_shape[2] + 0.2 * nodes_shape[0], nodes_shape[1] / 2.0 - 0.5]) 50 | 51 | nxg = graph.get_nx_graph() 52 | if not plot_terminal: 53 | nxg.remove_nodes_from(['s', 't']) 54 | 55 | nx.draw(nxg, pos=positions) 56 | nx.draw_networkx_labels(nxg, pos=positions) 57 | if plot_weights: 58 | edge_labels = dict([((u, v), d['weight']) for u, v, d in nxg.edges(data=True)]) 59 | nx.draw_networkx_edge_labels(nxg, 60 | pos=positions, 61 | edge_labels=edge_labels, 62 | label_pos=0.3, 63 | font_size=font_size) 64 | plt.axis('equal') 65 | plt.show() 66 | -------------------------------------------------------------------------------- /examples/layout_example2.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | How to use several calls to ``add_grid_edges`` and ``add_grid_tedges`` to create 4 | a flow network. 5 | """ 6 | 7 | import numpy as np 8 | import maxflow 9 | 10 | from examples_utils import plot_graph_2d 11 | 12 | 13 | def create_graph(): 14 | g = maxflow.Graph[float]() 15 | nodeids = g.add_grid_nodes((5, 5)) 16 | 17 | # Edges pointing backwards (left, left up and left down) with infinite 18 | # capacity 19 | structure = np.array( 20 | [[np.inf, 0, 0], 21 | [np.inf, 0, 0], 22 | [np.inf, 0, 0]] 23 | ) 24 | g.add_grid_edges(nodeids, structure=structure, symmetric=False) 25 | 26 | # Set a few arbitrary weights 27 | weights = np.array([[100, 110, 120, 130, 140]]).T + np.array([0, 2, 4, 6, 8]) 28 | 29 | # Edges pointing right 30 | structure = np.zeros((3, 3)) 31 | structure[1, 2] = 1 32 | g.add_grid_edges(nodeids, structure=structure, weights=weights, symmetric=False) 33 | 34 | # Edges pointing up 35 | structure = np.zeros((3, 3)) 36 | structure[0, 1] = 1 37 | g.add_grid_edges(nodeids, structure=structure, weights=weights+100, symmetric=False) 38 | 39 | # Edges pointing down 40 | structure = np.zeros((3, 3)) 41 | structure[2, 1] = 1 42 | g.add_grid_edges(nodeids, structure=structure, weights=weights+200, symmetric=False) 43 | 44 | # Source node connected to leftmost non-terminal nodes. 45 | left = nodeids[:, 0] 46 | g.add_grid_tedges(left, np.inf, 0) 47 | # Sink node connected to rightmost non-terminal nodes. 48 | right = nodeids[:, -1] 49 | g.add_grid_tedges(right, 0, np.inf) 50 | 51 | return nodeids, g 52 | 53 | 54 | if __name__ == '__main__': 55 | nodeids, g = create_graph() 56 | 57 | plot_graph_2d(g, nodeids.shape) 58 | 59 | g.maxflow() 60 | print(g.get_grid_segments(nodeids)) 61 | -------------------------------------------------------------------------------- /examples/layout_example3D.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | How to create a tridimensional grid network 4 | """ 5 | 6 | import numpy as np 7 | import maxflow 8 | 9 | from examples_utils import plot_graph_3d 10 | 11 | 12 | def create_graph(width=6, height=5, depth=2): 13 | 14 | g = maxflow.Graph[float]() 15 | nodeids = g.add_grid_nodes((depth, height, width)) 16 | structure = np.array( 17 | [[[0, 1, 0], 18 | [1, 1, 1], 19 | [0, 1, 0]], 20 | [[0, 1, 0], 21 | [1, 0, 1], 22 | [0, 1, 0]], 23 | [[0, 1, 0], 24 | [1, 1, 1], 25 | [0, 1, 0]]] 26 | ) 27 | g.add_grid_edges(nodeids, structure=structure) 28 | 29 | # Source node connected to leftmost non-terminal nodes. 30 | g.add_grid_tedges(nodeids[:, :, 0], np.inf, 0) 31 | # Sink node connected to rightmost non-terminal nodes. 32 | g.add_grid_tedges(nodeids[:, :, -1], 0, np.inf) 33 | return nodeids, g 34 | 35 | 36 | if __name__ == '__main__': 37 | nodeids, g = create_graph() 38 | plot_graph_3d(g, nodeids.shape) 39 | g.maxflow() 40 | print(g.get_grid_segments(nodeids)) 41 | -------------------------------------------------------------------------------- /examples/layout_examples.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | This file contains a list of examples with different layouts that can be 4 | obtained using the ``add_grid_edges`` method. 5 | """ 6 | 7 | import numpy as np 8 | import maxflow 9 | 10 | from examples_utils import plot_graph_2d 11 | 12 | # Standard 4-connected grid 13 | g = maxflow.Graph[int]() 14 | nodeids = g.add_grid_nodes((5, 5)) 15 | g.add_grid_edges(nodeids, 1) 16 | # Equivalent to 17 | # structure = maxflow.vonNeumann_structure(ndim=2, directed=False) 18 | # g.add_grid_edges(nodeids, 1, 19 | # structure=structure, 20 | # symmetric=False) 21 | plot_graph_2d(g, nodeids.shape, plot_terminals=False) 22 | 23 | # 8-connected grid, ignore two nodes 24 | g = maxflow.Graph[int]() 25 | nodeids = g.add_grid_nodes((5, 5)) 26 | structure = np.array([[0, 0, 0], 27 | [0, 0, 1], 28 | [1, 1, 1]]) 29 | # Also structure = maxflow.moore_structure(ndim=2, directed=True) 30 | # Nodeid -1 is ignored when adding edges 31 | nodeids[1, 1] = -1 32 | nodeids[3, 2] = -1 33 | g.add_grid_edges(nodeids, 1, structure=structure, symmetric=True) 34 | plot_graph_2d(g, nodeids.shape, plot_terminals=False) 35 | 36 | # 24-connected 5x5 neighborhood 37 | g = maxflow.Graph[int]() 38 | nodeids = g.add_grid_nodes((5, 5)) 39 | structure = np.array([[1, 1, 1, 1, 1], 40 | [1, 1, 1, 1, 1], 41 | [1, 1, 0, 1, 1], 42 | [1, 1, 1, 1, 1], 43 | [1, 1, 1, 1, 1]]) 44 | g.add_grid_edges(nodeids, 1, structure=structure, symmetric=False) 45 | plot_graph_2d(g, nodeids.shape, plot_terminals=False, plot_weights=False) 46 | 47 | # Diagonal, not symmetric 48 | g = maxflow.Graph[int]() 49 | nodeids = g.add_grid_nodes((5, 5)) 50 | structure = np.array([[0, 0, 0], 51 | [0, 0, 0], 52 | [0, 0, 1]]) 53 | g.add_grid_edges(nodeids, 1, structure=structure, symmetric=False) 54 | plot_graph_2d(g, nodeids.shape, plot_terminals=False) 55 | 56 | # Central node connected to every other node 57 | g = maxflow.Graph[int]() 58 | nodeids = g.add_grid_nodes((5, 5)).ravel() 59 | 60 | central_node = nodeids[12] 61 | rest_of_nodes = np.hstack([nodeids[:12], nodeids[13:]]) 62 | 63 | nodeids = np.empty((2, 24), dtype=np.int64) 64 | nodeids[0] = central_node 65 | nodeids[1] = rest_of_nodes 66 | 67 | structure = np.array([[0, 0, 0], 68 | [0, 0, 0], 69 | [0, 1, 0]]) 70 | g.add_grid_edges(nodeids, 1, structure=structure, symmetric=False) 71 | plot_graph_2d(g, (5, 5), plot_terminals=False) 72 | -------------------------------------------------------------------------------- /examples/simple.py: -------------------------------------------------------------------------------- 1 | import maxflow 2 | 3 | # Create a graph with integer capacities. 4 | g = maxflow.Graph[int](2, 2) 5 | # Add two (non-terminal) nodes. Get the index to the first one. 6 | nodes = g.add_nodes(2) 7 | # Create two edges (forwards and backwards) with the given capacities. 8 | # The indices of the nodes are always consecutive. 9 | g.add_edge(nodes[0], nodes[1], 1, 2) 10 | # Set the capacities of the terminal edges... 11 | # ...for the first node. 12 | g.add_tedge(nodes[0], 2, 5) 13 | # ...for the second node. 14 | g.add_tedge(nodes[1], 9, 4) 15 | 16 | # Find the maxflow. 17 | flow = g.maxflow() 18 | print("Maximum flow: {}".format(flow)) 19 | 20 | # Print the segment of each node. 21 | print("Segment of the node 0: {}".format(g.get_segment(nodes[0]))) 22 | print("Segment of the node 1: {}".format(g.get_segment(nodes[1]))) 23 | -------------------------------------------------------------------------------- /maxflow/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- encoding:utf-8 -*- 2 | 3 | """ 4 | maxflow 5 | ======= 6 | 7 | ``maxflow`` is a Python module for max-flow/min-cut computations. It wraps 8 | the C++ maxflow library by Vladimir Kolmogorov, which implements the 9 | algorithm described in 10 | 11 | An Experimental Comparison of Min-Cut/Max-Flow Algorithms for Energy 12 | Minimization in Vision. Yuri Boykov and Vladimir Kolmogorov. TPAMI. 13 | 14 | This module aims to simplify the construction of graphs with complex 15 | layouts. It provides two Graph classes, ``Graph[int]`` and ``Graph[float]``, 16 | for integer and real data types. 17 | 18 | Example: 19 | 20 | >>> import maxflow 21 | >>> g = maxflow.Graph[int](2, 2) 22 | >>> nodes = g.add_nodes(2) 23 | >>> g.add_edge(nodes[0], nodes[1], 1, 2) 24 | >>> g.add_tedge(nodes[0], 2, 5) 25 | >>> g.add_tedge(nodes[1], 9, 4) 26 | >>> g.maxflow() 27 | 8 28 | >>> g.get_grid_segments(nodes) 29 | array([ True, False]) 30 | 31 | If you use this library for research purposes, you must cite the aforementioned 32 | paper in any resulting publication. 33 | """ 34 | 35 | import numpy as np 36 | from . import _maxflow 37 | from ._maxflow import GraphInt, GraphFloat, moore_structure, vonNeumann_structure 38 | from .version import __version__, __version_core__ 39 | from .fastmin import aexpansion_grid, abswap_grid 40 | 41 | Graph = {int: GraphInt, float: GraphFloat} 42 | 43 | __all__ = ['Graph', "GraphInt", "GraphFloat", "np", "_maxflow", 44 | "moore_structure", "vonNeumann_structure", 45 | "aexpansion_grid", "abswap_grid"] 46 | -------------------------------------------------------------------------------- /maxflow/fastmin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | maxflow.fastmin 5 | =============== 6 | 7 | ``fastmin`` provides implementations of the algorithms for 8 | fast energy minimization described in [BOYKOV01]_: the alpha-expansion 9 | and the alpha-beta-swap. 10 | 11 | .. [BOYKOV01] *Fast approximate energy minimization via graph cuts.* 12 | Yuri Boykov, Olga Veksler and Ramin Zabih. TPAMI 2001. 13 | 14 | Currently, the functions in this module are restricted to 15 | grids with von Neumann neighborhood. 16 | """ 17 | 18 | import logging 19 | from itertools import count, combinations 20 | import numpy as np 21 | from ._maxflow import aexpansion_grid_step, abswap_grid_step 22 | 23 | logger = logging.getLogger(__name__) 24 | 25 | 26 | def energy_of_grid_labeling(unary, binary, labels): 27 | """ 28 | Returns the energy of the labeling of a grid. 29 | 30 | For details about ``unary``, ``binary`` and ``labels``, see the 31 | documentation of ``aexpansion_grid``. 32 | 33 | Returns the energy of the labeling. 34 | """ 35 | 36 | num_labels = unary.shape[-1] 37 | ndim = labels.ndim 38 | 39 | # Sum of the unary terms. 40 | unary_energy = np.sum([unary[labels == i, i].sum() for i in range(num_labels)]) 41 | 42 | slice0 = [slice(None)]*ndim 43 | slice1 = [slice(None)]*ndim 44 | # Binary terms. 45 | binary_energy = 0 46 | for i in range(ndim): 47 | slice0[i] = slice(1, None) 48 | slice1[i] = slice(None, -1) 49 | 50 | binary_energy += binary[labels[tuple(slice0)], labels[tuple(slice1)]].sum() 51 | 52 | slice0[i] = slice(None) 53 | slice1[i] = slice(None) 54 | 55 | return unary_energy + binary_energy 56 | 57 | 58 | def abswap_grid(unary, binary, max_cycles=None, labels=None): 59 | """ 60 | Minimize an energy function iterating the alpha-beta-swap until convergence 61 | or until a maximum number of cycles, given by ``max_cycles``, is reached. 62 | 63 | ``unary`` must be a N+1-dimensional array with shape (S1, ..., SN, L), where 64 | L is the number of labels. *unary[p1, ..., pn, lbl]* is the unary cost of 65 | assigning the label *lbl* to the variable *(p1, ..., pn)*. 66 | 67 | ``binary`` is a two-dimensional array. *binary[lbl1, lbl2]* is the binary 68 | cost of assigning the labels *lbl1* and *lbl2* to a pair of neighbor 69 | variables. Note that the abswap algorithm, unlike the aexpansion, does not 70 | require ``binary`` to define a metric. 71 | 72 | The optional N-dimensional array ``labels`` gives the initial labeling for 73 | the algorithm. If omitted, the function will initialize the labels using the 74 | minimum unary costs given by ``unary``. 75 | 76 | The function return the labeling reached at the end of the algorithm. If the 77 | parameter ``labels`` is given, the function will modify this array in-place. 78 | """ 79 | if unary.ndim == 0: 80 | raise ValueError("The unary term cannot be a scalar") 81 | 82 | num_labels = unary.shape[-1] 83 | 84 | if num_labels == 0: 85 | raise ValueError("The number of labels cannot be 0") 86 | 87 | if binary.shape != (num_labels, num_labels): 88 | raise ValueError( 89 | "The binary term must be a square matrix of shape (num_labels, num_labels). " 90 | f"The shape of the binary term was {binary.shape} but, according to the unary term, num_labels={num_labels}" 91 | ) 92 | 93 | if labels is None: 94 | # Avoid using too much memory. 95 | if num_labels <= 127: 96 | labels = np.int8(unary.argmin(axis=-1)) 97 | else: 98 | labels = np.int64(unary.argmin(axis=-1)) 99 | else: 100 | if labels.min() < 0: 101 | raise ValueError("Values of labels must be non-negative") 102 | if labels.max() >= num_labels: 103 | raise ValueError(f"Values of labels must be smaller than num_labels={num_labels}") 104 | 105 | if max_cycles is None: 106 | rng = count() 107 | else: 108 | rng = range(max_cycles) 109 | 110 | prev_labels = np.copy(labels) 111 | best_energy = np.inf 112 | # Cycles. 113 | for i in rng: 114 | logger.info("Cycle {}...".format(i)) 115 | improved = False 116 | 117 | # Iterate through the labels. 118 | for alpha, beta in combinations(range(num_labels), 2): 119 | energy, _ = abswap_grid_step(alpha, beta, unary, binary, labels) 120 | logger.info("Energy of the last cut (α={}, β={}): {:.6g}".format(alpha, beta, energy)) 121 | 122 | # Compute the energy of the labeling. 123 | strimproved = "" 124 | energy = energy_of_grid_labeling(unary, binary, labels) 125 | 126 | # Check if the best energy has been improved. 127 | if energy < best_energy: 128 | prev_labels = np.copy(labels) 129 | best_energy = energy 130 | improved = True 131 | strimproved = "(Improved!)" 132 | else: 133 | # If the energy has not been improved, discard the changes. 134 | labels = prev_labels 135 | 136 | logger.info("Energy of the labeling: {:.6g} {}".format(energy, strimproved)) 137 | 138 | # Finish the minimization when convergence is reached. 139 | if not improved: 140 | break 141 | 142 | return labels 143 | 144 | 145 | def aexpansion_grid(unary, binary, max_cycles=None, labels=None): 146 | """ 147 | Minimize an energy function iterating the alpha-expansion until convergence 148 | or until a maximum number of cycles, given by ``max_cycles``, is reached. 149 | 150 | ``unary`` must be an N+1-dimensional array with shape (S1, ..., SN, L), 151 | where L is the number of labels. *unary[p1, ... ,pn ,lbl]* is the unary cost 152 | of assigning the label *lbl* to the variable *(p1, ..., pn)*. 153 | 154 | ``binary`` is a two-dimensional array. *binary[lbl1, lbl2]* is the binary 155 | cost of assigning the labels *lbl1* and *lbl2* to a pair of neighbor 156 | variables. Note that the distance defined by ``binary`` must be a metric or 157 | else the aexpansion might converge to invalid results. 158 | 159 | The optional N-dimensional array ``labels`` gives the initial labeling of 160 | the algorithm. If omitted, the function will initialize the labels using the 161 | minimum unary costs given by ``unary``. 162 | 163 | The function return the labeling reached at the end of the algorithm. If the 164 | parameter ``labels`` is given, the function will modify this array in-place. 165 | """ 166 | if unary.ndim == 0: 167 | raise ValueError("The unary term cannot be a scalar") 168 | 169 | num_labels = unary.shape[-1] 170 | 171 | if num_labels == 0: 172 | raise ValueError("The number of labels cannot be 0") 173 | 174 | if binary.shape != (num_labels, num_labels): 175 | raise ValueError( 176 | "The binary term must be a square matrix of shape (num_labels, num_labels). " 177 | f"The shape of the binary term was {binary.shape} but, according to the unary term, num_labels={num_labels}" 178 | ) 179 | 180 | if labels is None: 181 | # Avoid using too much memory. 182 | if num_labels <= 127: 183 | labels = np.int8(unary.argmin(axis=-1)) 184 | else: 185 | labels = np.int64(unary.argmin(axis=-1)) 186 | else: 187 | if labels.min() < 0: 188 | raise ValueError("Values of labels must be non-negative") 189 | if labels.max() >= num_labels: 190 | raise ValueError(f"Values of labels must be smaller than num_labels={num_labels}") 191 | 192 | if max_cycles is None: 193 | rng = count() 194 | else: 195 | rng = range(max_cycles) 196 | 197 | best_energy = np.inf 198 | # Cycles. 199 | for i in rng: 200 | logger.info("Cycle {}...".format(i)) 201 | improved = False 202 | # Iterate through the labels. 203 | for alpha in range(num_labels): 204 | energy, _ = aexpansion_grid_step(alpha, unary, binary, labels) 205 | strimproved = "" 206 | # Check if the best energy has been improved. 207 | if energy < best_energy: 208 | best_energy = energy 209 | improved = True 210 | strimproved = "(Improved!)" 211 | logger.info("Energy of the last cut (α={}): {:.6g} {}".format(alpha, energy, strimproved)) 212 | 213 | # Finish the minimization when convergence is reached. 214 | if not improved: 215 | break 216 | 217 | return labels 218 | -------------------------------------------------------------------------------- /maxflow/src/core/CHANGES.TXT: -------------------------------------------------------------------------------- 1 | List of changes from version 3.03: 2 | 3 | - changed types of node::TS and TIME from int to long (to prevent overflows for very large graphs). Thanks to Alexander Bersenev for the suggestion. 4 | 5 | List of changes from version 3.02: 6 | 7 | - put under GPL license 8 | 9 | List of changes from version 3.01: 10 | 11 | - fixed a bug: using add_node() or add_edge() after the first maxflow() with the reuse_trees option 12 | could have caused segmentation fault (if nodes or arcs are reallocated). Thanks to Jan Lellmann for pointing out this bug. 13 | - updated block.h to suppress compilation warnings 14 | 15 | List of changes from version 3.0: 16 | - Moved line 17 | #include "instances.inc" 18 | to the end of cpp files to make it compile under GNU c++ compilers 4.2(?) and above 19 | 20 | List of changes from version 2.2: 21 | 22 | - Added functions for accessing graph structure, residual capacities, etc. 23 | (They are needed for implementing maxflow-based algorithms such as primal-dual algorithm for convex MRFs.) 24 | - Added option of reusing trees. 25 | - node_id's are now integers starting from 0. Thus, it is not necessary to store node_id's in a separate array. 26 | - Capacity types are now templated. 27 | - Fixed bug in block.h. (After Block::Reset, ScanFirst() and ScanNext() did not work properly). 28 | - Implementation with a forward star representation of the graph is no longer supported. (It needs less memory, but slightly slower than adjacency list representation.) If you still wish to use it, download version 2.2. 29 | - Note: version 3.0 is released under a different license than version 2.2. 30 | 31 | List of changes from version 2.1: 32 | 33 | - Put the code under GPL license 34 | 35 | List of changes from version 2.02: 36 | 37 | - Fixed a bug in the implementation that uses forward star representation 38 | 39 | List of changes from version 2.01: 40 | 41 | - Added new interface function - Graph::add_tweights(Node_id, captype, captype) 42 | (necessary for the "ENERGY" software package) 43 | 44 | -------------------------------------------------------------------------------- /maxflow/src/core/GPL.TXT: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /maxflow/src/core/README.TXT: -------------------------------------------------------------------------------- 1 | ################################################################### 2 | # # 3 | # MAXFLOW - software for computing mincut/maxflow in a graph # 4 | # Version 3.03 # 5 | # http://http://pub.ist.ac.at/~vnk/software.html # 6 | # # 7 | # Yuri Boykov (yuri@csd.uwo.ca) # 8 | # Vladimir Kolmogorov (vnk@ist.ac.at) # 9 | # 2001-2006 # 10 | # # 11 | ################################################################### 12 | 13 | 1. Introduction. 14 | 15 | This software library implements the maxflow algorithm described in 16 | 17 | "An Experimental Comparison of Min-Cut/Max-Flow Algorithms for Energy Minimization in Vision." 18 | Yuri Boykov and Vladimir Kolmogorov. 19 | In IEEE Transactions on Pattern Analysis and Machine Intelligence (PAMI), 20 | September 2004 21 | 22 | This algorithm was developed by Yuri Boykov and Vladimir Kolmogorov 23 | at Siemens Corporate Research. To make it available for public use, 24 | it was later reimplemented by Vladimir Kolmogorov based on open publications. 25 | 26 | If you use this software for research purposes, you should cite 27 | the aforementioned paper in any resulting publication. 28 | 29 | ---------------------------------------------------------------------- 30 | 31 | REUSING TREES: 32 | 33 | Starting with version 3.0, there is a also an option of reusing search 34 | trees from one maxflow computation to the next, as described in 35 | 36 | "Efficiently Solving Dynamic Markov Random Fields Using Graph Cuts." 37 | Pushmeet Kohli and Philip H.S. Torr 38 | International Conference on Computer Vision (ICCV), 2005 39 | 40 | If you use this option, you should cite 41 | the aforementioned paper in any resulting publication. 42 | 43 | Tested under windows, Visual C++ 6.0 compiler and unix (SunOS 5.8 44 | and RedHat Linux 7.0, GNU c++ compiler). 45 | 46 | ################################################################## 47 | 48 | 2. License & disclaimer. 49 | 50 | Copyright 2001-2006 Vladimir Kolmogorov (vnk@ist.ac.at), Yuri Boykov (yuri@csd.uwo.ca). 51 | 52 | This software is under the GPL license. 53 | If you require another license, you may consider using version 2.21 54 | (which implements exactly the same algorithm, but does not have the option of reusing search trees). 55 | 56 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 57 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 58 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 59 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 60 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 61 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 62 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 63 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 64 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 65 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 66 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 67 | 68 | ################################################################## 69 | 70 | 3. Example usage. 71 | 72 | This section shows how to use the library to compute 73 | a minimum cut on the following graph: 74 | 75 | SOURCE 76 | / \ 77 | 1/ \2 78 | / 3 \ 79 | node0 -----> node1 80 | | <----- | 81 | | 4 | 82 | \ / 83 | 5\ /6 84 | \ / 85 | SINK 86 | 87 | /////////////////////////////////////////////////// 88 | 89 | #include 90 | #include "graph.h" 91 | 92 | int main() 93 | { 94 | typedef Graph GraphType; 95 | GraphType *g = new GraphType(/*estimated # of nodes*/ 2, /*estimated # of edges*/ 1); 96 | 97 | g -> add_node(); 98 | g -> add_node(); 99 | 100 | g -> add_tweights( 0, /* capacities */ 1, 5 ); 101 | g -> add_tweights( 1, /* capacities */ 2, 6 ); 102 | g -> add_edge( 0, 1, /* capacities */ 3, 4 ); 103 | 104 | int flow = g -> maxflow(); 105 | 106 | printf("Flow = %d\n", flow); 107 | printf("Minimum cut:\n"); 108 | if (g->what_segment(0) == GraphType::SOURCE) 109 | printf("node0 is in the SOURCE set\n"); 110 | else 111 | printf("node0 is in the SINK set\n"); 112 | if (g->what_segment(1) == GraphType::SOURCE) 113 | printf("node1 is in the SOURCE set\n"); 114 | else 115 | printf("node1 is in the SINK set\n"); 116 | 117 | delete g; 118 | 119 | return 0; 120 | } 121 | 122 | 123 | /////////////////////////////////////////////////// 124 | -------------------------------------------------------------------------------- /maxflow/src/core/block.h: -------------------------------------------------------------------------------- 1 | /* block.h */ 2 | /* Vladimir Kolmogorov vnk@ist.ac.at */ 3 | /* Last modified 08/05/2012 */ 4 | /* 5 | Template classes Block and DBlock 6 | Implement adding and deleting items of the same type in blocks. 7 | 8 | If there there are many items then using Block or DBlock 9 | is more efficient than using 'new' and 'delete' both in terms 10 | of memory and time since 11 | (1) On some systems there is some minimum amount of memory 12 | that 'new' can allocate (e.g., 64), so if items are 13 | small that a lot of memory is wasted. 14 | (2) 'new' and 'delete' are designed for items of varying size. 15 | If all items has the same size, then an algorithm for 16 | adding and deleting can be made more efficient. 17 | (3) All Block and DBlock functions are inline, so there are 18 | no extra function calls. 19 | 20 | Differences between Block and DBlock: 21 | (1) DBlock allows both adding and deleting items, 22 | whereas Block allows only adding items. 23 | (2) Block has an additional operation of scanning 24 | items added so far (in the order in which they were added). 25 | (3) Block allows to allocate several consecutive 26 | items at a time, whereas DBlock can add only a single item. 27 | 28 | Note that no constructors or destructors are called for items. 29 | 30 | Example usage for items of type 'MyType': 31 | 32 | /////////////////////////////////////////////////// 33 | #include "block.h" 34 | #define BLOCK_SIZE 1024 35 | typedef struct { int a, b; } MyType; 36 | MyType *ptr, *array[10000]; 37 | 38 | ... 39 | 40 | Block *block = new Block(BLOCK_SIZE); 41 | 42 | // adding items 43 | for (int i=0; i New(); 46 | ptr -> a = ptr -> b = rand(); 47 | } 48 | 49 | // reading items 50 | for (ptr=block->ScanFirst(); ptr; ptr=block->ScanNext()) 51 | { 52 | printf("%d %d\n", ptr->a, ptr->b); 53 | } 54 | 55 | delete block; 56 | 57 | ... 58 | 59 | DBlock *dblock = new DBlock(BLOCK_SIZE); 60 | 61 | // adding items 62 | for (int i=0; i New(); 65 | } 66 | 67 | // deleting items 68 | for (int i=0; i Delete(array[i]); 71 | } 72 | 73 | // adding items 74 | for (int i=0; i New(); 77 | } 78 | 79 | delete dblock; 80 | 81 | /////////////////////////////////////////////////// 82 | 83 | Note that DBlock deletes items by marking them as 84 | empty (i.e., by adding them to the list of free items), 85 | so that this memory could be used for subsequently 86 | added items. Thus, at each moment the memory allocated 87 | is determined by the maximum number of items allocated 88 | simultaneously at earlier moments. All memory is 89 | deallocated only when the destructor is called. 90 | */ 91 | 92 | #ifndef __BLOCK_H__ 93 | #define __BLOCK_H__ 94 | 95 | #include 96 | 97 | /***********************************************************************/ 98 | /***********************************************************************/ 99 | /***********************************************************************/ 100 | 101 | template class Block 102 | { 103 | public: 104 | /* Constructor. Arguments are the block size and 105 | (optionally) the pointer to the function which 106 | will be called if allocation failed; the message 107 | passed to this function is "Not enough memory!" */ 108 | Block(int size, void (*err_function)(const char *) = NULL) { first = last = NULL; block_size = size; error_function = err_function; } 109 | 110 | /* Destructor. Deallocates all items added so far */ 111 | ~Block() { while (first) { block *next = first -> next; delete[] ((char*)first); first = next; } } 112 | 113 | /* Allocates 'num' consecutive items; returns pointer 114 | to the first item. 'num' cannot be greater than the 115 | block size since items must fit in one block */ 116 | Type *New(int num = 1) 117 | { 118 | Type *t; 119 | 120 | if (!last || last->current + num > last->last) 121 | { 122 | if (last && last->next) last = last -> next; 123 | else 124 | { 125 | block *next = (block *) new char [sizeof(block) + (block_size-1)*sizeof(Type)]; 126 | if (!next) { if (error_function) (*error_function)("Not enough memory!"); exit(1); } 127 | if (last) last -> next = next; 128 | else first = next; 129 | last = next; 130 | last -> current = & ( last -> data[0] ); 131 | last -> last = last -> current + block_size; 132 | last -> next = NULL; 133 | } 134 | } 135 | 136 | t = last -> current; 137 | last -> current += num; 138 | return t; 139 | } 140 | 141 | /* Returns the first item (or NULL, if no items were added) */ 142 | Type *ScanFirst() 143 | { 144 | for (scan_current_block=first; scan_current_block; scan_current_block = scan_current_block->next) 145 | { 146 | scan_current_data = & ( scan_current_block -> data[0] ); 147 | if (scan_current_data < scan_current_block -> current) return scan_current_data ++; 148 | } 149 | return NULL; 150 | } 151 | 152 | /* Returns the next item (or NULL, if all items have been read) 153 | Can be called only if previous ScanFirst() or ScanNext() 154 | call returned not NULL. */ 155 | Type *ScanNext() 156 | { 157 | while (scan_current_data >= scan_current_block -> current) 158 | { 159 | scan_current_block = scan_current_block -> next; 160 | if (!scan_current_block) return NULL; 161 | scan_current_data = & ( scan_current_block -> data[0] ); 162 | } 163 | return scan_current_data ++; 164 | } 165 | 166 | struct iterator; // for overlapping scans 167 | Type *ScanFirst(iterator& i) 168 | { 169 | for (i.scan_current_block=first; i.scan_current_block; i.scan_current_block = i.scan_current_block->next) 170 | { 171 | i.scan_current_data = & ( i.scan_current_block -> data[0] ); 172 | if (i.scan_current_data < i.scan_current_block -> current) return i.scan_current_data ++; 173 | } 174 | return NULL; 175 | } 176 | Type *ScanNext(iterator& i) 177 | { 178 | while (i.scan_current_data >= i.scan_current_block -> current) 179 | { 180 | i.scan_current_block = i.scan_current_block -> next; 181 | if (!i.scan_current_block) return NULL; 182 | i.scan_current_data = & ( i.scan_current_block -> data[0] ); 183 | } 184 | return i.scan_current_data ++; 185 | } 186 | 187 | /* Marks all elements as empty */ 188 | void Reset() 189 | { 190 | block *b; 191 | if (!first) return; 192 | for (b=first; ; b=b->next) 193 | { 194 | b -> current = & ( b -> data[0] ); 195 | if (b == last) break; 196 | } 197 | last = first; 198 | } 199 | 200 | /***********************************************************************/ 201 | 202 | private: 203 | 204 | typedef struct block_st 205 | { 206 | Type *current, *last; 207 | struct block_st *next; 208 | Type data[1]; 209 | } block; 210 | 211 | int block_size; 212 | block *first; 213 | block *last; 214 | public: 215 | struct iterator 216 | { 217 | block *scan_current_block; 218 | Type *scan_current_data; 219 | }; 220 | private: 221 | block *scan_current_block; 222 | Type *scan_current_data; 223 | 224 | void (*error_function)(const char *); 225 | }; 226 | 227 | /***********************************************************************/ 228 | /***********************************************************************/ 229 | /***********************************************************************/ 230 | 231 | template class DBlock 232 | { 233 | public: 234 | /* Constructor. Arguments are the block size and 235 | (optionally) the pointer to the function which 236 | will be called if allocation failed; the message 237 | passed to this function is "Not enough memory!" */ 238 | DBlock(int size, void (*err_function)(const char *) = NULL) { first = NULL; first_free = NULL; block_size = size; error_function = err_function; } 239 | 240 | /* Destructor. Deallocates all items added so far */ 241 | ~DBlock() { while (first) { block *next = first -> next; delete[] ((char*)first); first = next; } } 242 | 243 | /* Allocates one item */ 244 | Type *New() 245 | { 246 | block_item *item; 247 | 248 | if (!first_free) 249 | { 250 | block *next = first; 251 | first = (block *) new char [sizeof(block) + (block_size-1)*sizeof(block_item)]; 252 | if (!first) { if (error_function) (*error_function)("Not enough memory!"); exit(1); } 253 | first_free = & (first -> data[0] ); 254 | for (item=first_free; item next_free = item + 1; 256 | item -> next_free = NULL; 257 | first -> next = next; 258 | } 259 | 260 | item = first_free; 261 | first_free = item -> next_free; 262 | return (Type *) item; 263 | } 264 | 265 | /* Deletes an item allocated previously */ 266 | void Delete(Type *t) 267 | { 268 | ((block_item *) t) -> next_free = first_free; 269 | first_free = (block_item *) t; 270 | } 271 | 272 | /***********************************************************************/ 273 | 274 | private: 275 | 276 | typedef union block_item_st 277 | { 278 | Type t; 279 | block_item_st *next_free; 280 | } block_item; 281 | 282 | typedef struct block_st 283 | { 284 | struct block_st *next; 285 | block_item data[1]; 286 | } block; 287 | 288 | int block_size; 289 | block *first; 290 | block_item *first_free; 291 | 292 | void (*error_function)(const char *); 293 | }; 294 | 295 | 296 | #endif 297 | 298 | -------------------------------------------------------------------------------- /maxflow/src/core/graph.h: -------------------------------------------------------------------------------- 1 | /* graph.h */ 2 | /* 3 | Copyright Vladimir Kolmogorov (vnk@ist.ac.at), Yuri Boykov (yuri@csd.uwo.ca) 4 | 5 | This file is part of MAXFLOW. 6 | 7 | MAXFLOW is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | MAXFLOW is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with MAXFLOW. If not, see . 19 | 20 | ======================== 21 | 22 | version 3.04 23 | 24 | This software library implements the maxflow algorithm 25 | described in 26 | 27 | "An Experimental Comparison of Min-Cut/Max-Flow Algorithms for Energy Minimization in Vision." 28 | Yuri Boykov and Vladimir Kolmogorov. 29 | In IEEE Transactions on Pattern Analysis and Machine Intelligence (PAMI), 30 | September 2004 31 | 32 | This algorithm was developed by Yuri Boykov and Vladimir Kolmogorov 33 | at Siemens Corporate Research. To make it available for public use, 34 | it was later reimplemented by Vladimir Kolmogorov based on open publications. 35 | 36 | If you use this software for research purposes, you should cite 37 | the aforementioned paper in any resulting publication. 38 | 39 | ---------------------------------------------------------------------- 40 | 41 | REUSING TREES: 42 | 43 | Starting with version 3.0, there is a also an option of reusing search 44 | trees from one maxflow computation to the next, as described in 45 | 46 | "Efficiently Solving Dynamic Markov Random Fields Using Graph Cuts." 47 | Pushmeet Kohli and Philip H.S. Torr 48 | International Conference on Computer Vision (ICCV), 2005 49 | 50 | If you use this option, you should cite 51 | the aforementioned paper in any resulting publication. 52 | */ 53 | 54 | 55 | 56 | /* 57 | For description, license, example usage see README.TXT. 58 | */ 59 | 60 | #ifndef __GRAPH_H__ 61 | #define __GRAPH_H__ 62 | 63 | #include 64 | #include "block.h" 65 | 66 | #include 67 | // NOTE: in UNIX you need to use -DNDEBUG preprocessor option to supress assert's!!! 68 | 69 | #include "../pyarraymodule.h" 70 | 71 | typedef enum 72 | { 73 | SOURCE = 0, 74 | SINK = 1 75 | } termtype; // terminals 76 | 77 | // captype: type of edge capacities (excluding t-links) 78 | // tcaptype: type of t-links (edges between nodes and terminals) 79 | // flowtype: type of total flow 80 | // 81 | // Current instantiations are in instances.inc 82 | template class Graph 83 | { 84 | public: 85 | typedef int node_id; 86 | 87 | ///////////////////////////////////////////////////////////////////////// 88 | // BASIC INTERFACE FUNCTIONS // 89 | // (should be enough for most applications) // 90 | ///////////////////////////////////////////////////////////////////////// 91 | 92 | // Constructor. 93 | // The first argument gives an estimate of the maximum number of nodes that can be added 94 | // to the graph, and the second argument is an estimate of the maximum number of edges. 95 | // The last (optional) argument is the pointer to the function which will be called 96 | // if an error occurs; an error message is passed to this function. 97 | // If this argument is omitted, exit(1) will be called. 98 | // 99 | // IMPORTANT: It is possible to add more nodes to the graph than node_num_max 100 | // (and node_num_max can be zero). However, if the count is exceeded, then 101 | // the internal memory is reallocated (increased by 50%) which is expensive. 102 | // Also, temporarily the amount of allocated memory would be more than twice than needed. 103 | // Similarly for edges. 104 | // If you wish to avoid this overhead, you can download version 2.2, where nodes and edges are stored in blocks. 105 | Graph(int node_num_max, int edge_num_max, void (*err_function)(const char *) = NULL); 106 | 107 | // Copy constructor 108 | Graph(const Graph& rhs); 109 | 110 | // Destructor 111 | ~Graph(); 112 | 113 | // Adds node(s) to the graph. By default, one node is added (num=1); then first call returns 0, second call returns 1, and so on. 114 | // If num>1, then several nodes are added, and node_id of the first one is returned. 115 | // IMPORTANT: see note about the constructor 116 | node_id add_node(int num = 1); 117 | 118 | // Adds a bidirectional edge between 'i' and 'j' with the weights 'cap' and 'rev_cap'. 119 | // IMPORTANT: see note about the constructor 120 | void add_edge(node_id i, node_id j, captype cap, captype rev_cap); 121 | 122 | // Adds new edges 'SOURCE->i' and 'i->SINK' with corresponding weights. 123 | // Can be called multiple times for each node. 124 | // Weights can be negative. 125 | // NOTE: the number of such edges is not counted in edge_num_max. 126 | // No internal memory is allocated by this call. 127 | void add_tweights(node_id i, tcaptype cap_source, tcaptype cap_sink); 128 | 129 | 130 | // Computes the maxflow. Can be called several times. 131 | // FOR DESCRIPTION OF reuse_trees, SEE mark_node(). 132 | // FOR DESCRIPTION OF changed_list, SEE remove_from_changed_list(). 133 | flowtype maxflow(bool reuse_trees = false, Block* changed_list = NULL); 134 | 135 | // After the maxflow is computed, this function returns to which 136 | // segment the node 'i' belongs (Graph::SOURCE or Graph::SINK). 137 | // 138 | // Occasionally there may be several minimum cuts. If a node can be assigned 139 | // to both the source and the sink, then default_segm is returned. 140 | termtype what_segment(node_id i, termtype default_segm = SOURCE); 141 | 142 | 143 | 144 | ////////////////////////////////////////////// 145 | // ADVANCED INTERFACE FUNCTIONS // 146 | // (provide access to the graph) // 147 | ////////////////////////////////////////////// 148 | 149 | private: 150 | struct node; 151 | struct arc; 152 | 153 | public: 154 | 155 | //////////////////////////// 156 | // 1. Reallocating graph. // 157 | //////////////////////////// 158 | 159 | // Removes all nodes and edges. 160 | // After that functions add_node() and add_edge() must be called again. 161 | // 162 | // Advantage compared to deleting Graph and allocating it again: 163 | // no calls to delete/new (which could be quite slow). 164 | // 165 | // If the graph structure stays the same, then an alternative 166 | // is to go through all nodes/edges and set new residual capacities 167 | // (see functions below). 168 | void reset(); 169 | 170 | //////////////////////////////////////////////////////////////////////////////// 171 | // 2. Functions for getting pointers to arcs and for reading graph structure. // 172 | // NOTE: adding new arcs may invalidate these pointers (if reallocation // 173 | // happens). So it's best not to add arcs while reading graph structure. // 174 | //////////////////////////////////////////////////////////////////////////////// 175 | 176 | // The following two functions return arcs in the same order that they 177 | // were added to the graph. NOTE: for each call add_edge(i,j,cap,cap_rev) 178 | // the first arc returned will be i->j, and the second j->i. 179 | // If there are no more arcs, then the function can still be called, but 180 | // the returned arc_id is undetermined. 181 | typedef uintptr_t arc_id; 182 | arc_id get_first_arc(); 183 | arc_id get_next_arc(arc_id a); 184 | 185 | // other functions for reading graph structure 186 | int get_node_num() { return node_num; } 187 | int get_arc_num() { return (int)(arc_last - arcs); } 188 | void get_arc_ends(arc_id a, node_id& i, node_id& j); // returns i,j to that a = i->j 189 | node_id get_arc_from(arc_id a); 190 | node_id get_arc_to(arc_id a); 191 | 192 | /////////////////////////////////////////////////// 193 | // 3. Functions for reading residual capacities. // 194 | /////////////////////////////////////////////////// 195 | 196 | // returns residual capacity of SOURCE->i minus residual capacity of i->SINK 197 | tcaptype get_trcap(node_id i); 198 | // returns residual capacity of arc a 199 | captype get_rcap(arc_id a); 200 | 201 | ///////////////////////////////////////////////////////////////// 202 | // 4. Functions for setting residual capacities. // 203 | // NOTE: If these functions are used, the value of the flow // 204 | // returned by maxflow() will not be valid! // 205 | ///////////////////////////////////////////////////////////////// 206 | 207 | void set_trcap(node_id i, tcaptype trcap); 208 | void set_rcap(arc* a, captype rcap); 209 | 210 | //////////////////////////////////////////////////////////////////// 211 | // 5. Functions related to reusing trees & list of changed nodes. // 212 | //////////////////////////////////////////////////////////////////// 213 | 214 | // If flag reuse_trees is true while calling maxflow(), then search trees 215 | // are reused from previous maxflow computation. 216 | // In this case before calling maxflow() the user must 217 | // specify which parts of the graph have changed by calling mark_node(): 218 | // add_tweights(i),set_trcap(i) => call mark_node(i) 219 | // add_edge(i,j),set_rcap(a) => call mark_node(i); mark_node(j) 220 | // 221 | // This option makes sense only if a small part of the graph is changed. 222 | // The initialization procedure goes only through marked nodes then. 223 | // 224 | // mark_node(i) can either be called before or after graph modification. 225 | // Can be called more than once per node, but calls after the first one 226 | // do not have any effect. 227 | // 228 | // NOTE: 229 | // - This option cannot be used in the first call to maxflow(). 230 | // - It is not necessary to call mark_node() if the change is ``not essential'', 231 | // i.e. sign(trcap) is preserved for a node and zero/nonzero status is preserved for an arc. 232 | // - To check that you marked all necessary nodes, you can call maxflow(false) after calling maxflow(true). 233 | // If everything is correct, the two calls must return the same value of flow. (Useful for debugging). 234 | void mark_node(node_id i); 235 | 236 | // If changed_list is not NULL while calling maxflow(), then the algorithm 237 | // keeps a list of nodes which could potentially have changed their segmentation label. 238 | // Nodes which are not in the list are guaranteed to keep their old segmentation label (SOURCE or SINK). 239 | // Example usage: 240 | // 241 | // typedef Graph G; 242 | // G* g = new Graph(nodeNum, edgeNum); 243 | // Block* changed_list = new Block(128); 244 | // 245 | // ... // add nodes and edges 246 | // 247 | // g->maxflow(); // first call should be without arguments 248 | // for (int iter=0; iter<10; iter++) 249 | // { 250 | // ... // change graph, call mark_node() accordingly 251 | // 252 | // g->maxflow(true, changed_list); 253 | // G::node_id* ptr; 254 | // for (ptr=changed_list->ScanFirst(); ptr; ptr=changed_list->ScanNext()) 255 | // { 256 | // G::node_id i = *ptr; assert(i>=0 && iremove_from_changed_list(i); 258 | // // do something with node i... 259 | // if (g->what_segment(i) == G::SOURCE) { ... } 260 | // } 261 | // changed_list->Reset(); 262 | // } 263 | // delete changed_list; 264 | // 265 | // NOTE: 266 | // - If changed_list option is used, then reuse_trees must be used as well. 267 | // - In the example above, the user may omit calls g->remove_from_changed_list(i) and changed_list->Reset() in a given iteration. 268 | // Then during the next call to maxflow(true, &changed_list) new nodes will be added to changed_list. 269 | // - If the next call to maxflow() does not use option reuse_trees, then calling remove_from_changed_list() 270 | // is not necessary. ("changed_list->Reset()" or "delete changed_list" should still be called, though). 271 | void remove_from_changed_list(node_id i) 272 | { 273 | assert(i>=0 && i 0 then tr_cap is residual capacity of the arc SOURCE->node 307 | // otherwise -tr_cap is residual capacity of the arc node->SINK 308 | 309 | }; 310 | 311 | struct arc 312 | { 313 | node *head; // node the arc points to 314 | arc *next; // next arc with the same originating node 315 | arc *sister; // reverse arc 316 | 317 | captype r_cap; // residual capacity 318 | }; 319 | 320 | struct nodeptr 321 | { 322 | node *ptr; 323 | nodeptr *next; 324 | }; 325 | static const int NODEPTR_BLOCK_SIZE = 128; 326 | 327 | node *nodes, *node_last, *node_max; // node_last = nodes+node_num, node_max = nodes+node_num_max; 328 | arc *arcs, *arc_last, *arc_max; // arc_last = arcs+2*edge_num, arc_max = arcs+2*edge_num_max; 329 | 330 | int node_num; 331 | 332 | DBlock *nodeptr_block; 333 | 334 | void (*error_function)(const char *); // this function is called if a error occurs, 335 | // with a corresponding error message 336 | // (or exit(1) is called if it's NULL) 337 | 338 | flowtype flow; // total flow 339 | 340 | // reusing trees & list of changed pixels 341 | int maxflow_iteration; // counter 342 | Block *changed_list; 343 | 344 | ///////////////////////////////////////////////////////////////////////// 345 | 346 | node *queue_first[2], *queue_last[2]; // list of active nodes 347 | nodeptr *orphan_first, *orphan_last; // list of pointers to orphans 348 | long long TIME; // monotonically increasing global counter 349 | 350 | ///////////////////////////////////////////////////////////////////////// 351 | 352 | void reallocate_nodes(int num); // num is the number of new nodes 353 | void reallocate_arcs(); 354 | 355 | // functions for processing active list 356 | void set_active(node *i); 357 | node *next_active(); 358 | 359 | // functions for processing orphans list 360 | void set_orphan_front(node* i); // add to the beginning of the list 361 | void set_orphan_rear(node* i); // add to the end of the list 362 | 363 | void add_to_changed_list(node* i); 364 | 365 | void maxflow_init(); // called if reuse_trees == false 366 | void maxflow_reuse_trees_init(); // called if reuse_trees == true 367 | void augment(arc *middle_arc); 368 | void process_source_orphan(node *i); 369 | void process_sink_orphan(node *i); 370 | 371 | void test_consistency(node* current_node=NULL); // debug function 372 | }; 373 | 374 | /////////////////////////////////////// 375 | // Implementation - inline functions // 376 | /////////////////////////////////////// 377 | 378 | template 379 | inline typename Graph::node_id Graph::add_node(int num) 380 | { 381 | assert(num > 0); 382 | 383 | if (node_last + num > node_max) reallocate_nodes(num); 384 | 385 | memset(node_last, 0, num*sizeof(node)); 386 | 387 | node_id i = node_num; 388 | node_num += num; 389 | node_last += num; 390 | return i; 391 | } 392 | 393 | template 394 | inline void Graph::add_tweights(node_id i, tcaptype cap_source, tcaptype cap_sink) 395 | { 396 | assert(i >= -1 && i < node_num); 397 | 398 | if(i == -1) 399 | return; 400 | 401 | if(node_num == 0) 402 | throw std::runtime_error("cannot add terminal edges; no nodes in the graph"); 403 | if(i >= node_num || i < 0) 404 | throw std::runtime_error("cannot add terminal edges; the node is not in the graph"); 405 | 406 | tcaptype delta = nodes[i].tr_cap; 407 | if (delta > 0) cap_source += delta; 408 | else cap_sink -= delta; 409 | flow += (cap_source < cap_sink) ? cap_source : cap_sink; 410 | nodes[i].tr_cap = cap_source - cap_sink; 411 | } 412 | 413 | template 414 | inline void Graph::add_edge(node_id _i, node_id _j, captype cap, captype rev_cap) 415 | { 416 | assert(_i >= -1 && _i < node_num); 417 | assert(_j >= -1 && _j < node_num); 418 | assert(cap >= 0); 419 | assert(rev_cap >= 0); 420 | 421 | if(_i == -1 || _j == -1 || _i == _j) 422 | return; 423 | 424 | if(node_num == 0) 425 | throw std::runtime_error("cannot add an edge; no nodes in the graph"); 426 | if(_i >= node_num || _i < 0) 427 | throw std::runtime_error("cannot add an edge; the first node is not in the graph"); 428 | if(_j >= node_num || _j < 0) 429 | throw std::runtime_error("cannot add an edge; the second node is not in the graph"); 430 | 431 | if (arc_last == arc_max) reallocate_arcs(); 432 | 433 | arc *a = arc_last ++; 434 | arc *a_rev = arc_last ++; 435 | 436 | node* i = nodes + _i; 437 | node* j = nodes + _j; 438 | 439 | a -> sister = a_rev; 440 | a_rev -> sister = a; 441 | a -> next = i -> first; 442 | i -> first = a; 443 | a_rev -> next = j -> first; 444 | j -> first = a_rev; 445 | a -> head = j; 446 | a_rev -> head = i; 447 | a -> r_cap = cap; 448 | a_rev -> r_cap = rev_cap; 449 | } 450 | 451 | template 452 | inline uintptr_t Graph::get_first_arc() 453 | { 454 | return reinterpret_cast(arcs); 455 | } 456 | 457 | template 458 | inline uintptr_t Graph::get_next_arc(uintptr_t _a) 459 | { 460 | arc* a = reinterpret_cast(_a); 461 | return reinterpret_cast(a + 1); 462 | } 463 | 464 | template 465 | inline void Graph::get_arc_ends(arc_id _a, node_id& i, node_id& j) 466 | { 467 | arc* a = reinterpret_cast(_a); 468 | assert(a >= arcs && a < arc_last); 469 | i = (node_id) (a->sister->head - nodes); 470 | j = (node_id) (a->head - nodes); 471 | } 472 | 473 | template 474 | inline tcaptype Graph::get_trcap(node_id i) 475 | { 476 | assert(i>=0 && i 481 | inline captype Graph::get_rcap(arc_id _a) 482 | { 483 | arc* a = reinterpret_cast(_a); 484 | assert(a >= arcs && a < arc_last); 485 | return a->r_cap; 486 | } 487 | 488 | template 489 | inline void Graph::set_trcap(node_id i, tcaptype trcap) 490 | { 491 | assert(i>=0 && i 496 | inline void Graph::set_rcap(arc* a, captype rcap) 497 | { 498 | assert(a >= arcs && a < arc_last); 499 | a->r_cap = rcap; 500 | } 501 | 502 | 503 | template 504 | inline termtype Graph::what_segment(node_id i, termtype default_segm) 505 | { 506 | if(i >= node_num || i < 0) 507 | throw std::runtime_error("cannot get the segment of the node; the node is not in the graph"); 508 | if (nodes[i].parent) 509 | { 510 | return (nodes[i].is_sink) ? SINK : SOURCE; 511 | } 512 | else 513 | { 514 | return default_segm; 515 | } 516 | } 517 | 518 | template 519 | inline void Graph::mark_node(node_id _i) 520 | { 521 | node* i = nodes + _i; 522 | if (!i->next) 523 | { 524 | /* it's not in the list yet */ 525 | if (queue_last[1]) queue_last[1] -> next = i; 526 | else queue_first[1] = i; 527 | queue_last[1] = i; 528 | i -> next = i; 529 | } 530 | i->is_marked = 1; 531 | } 532 | 533 | /* 534 | special constants for node->parent. Duplicated in maxflow.cpp, both should match! 535 | */ 536 | #define TERMINAL ( (arc *) 1 ) /* to terminal */ 537 | #define ORPHAN ( (arc *) 2 ) /* orphan */ 538 | 539 | template 540 | Graph::Graph(int node_num_max, int edge_num_max, void (*err_function)(const char *)) 541 | : node_num(0), 542 | nodeptr_block(NULL), 543 | error_function(err_function) 544 | { 545 | if (node_num_max < 16) node_num_max = 16; 546 | if (edge_num_max < 16) edge_num_max = 16; 547 | 548 | nodes = (node*) malloc(node_num_max*sizeof(node)); 549 | arcs = (arc*) malloc(2*edge_num_max*sizeof(arc)); 550 | if (!nodes || !arcs) { if (error_function) (*error_function)("Not enough memory!"); exit(1); } 551 | 552 | node_last = nodes; 553 | node_max = nodes + node_num_max; 554 | arc_last = arcs; 555 | arc_max = arcs + 2*edge_num_max; 556 | 557 | maxflow_iteration = 0; 558 | flow = 0; 559 | } 560 | 561 | template 562 | Graph::Graph(const Graph& rhs) 563 | : node_num(rhs.node_num), 564 | nodeptr_block(NULL), 565 | error_function(rhs.error_function), 566 | flow(rhs.flow), 567 | maxflow_iteration(0), 568 | changed_list(NULL) 569 | { 570 | size_t node_num_max = rhs.node_max - rhs.nodes; 571 | size_t arc_num_max = rhs.arc_max - rhs.arcs; 572 | size_t arc_num = rhs.arc_last - rhs.arcs; 573 | 574 | nodes = (node*) malloc(node_num_max * sizeof(node)); 575 | node_last = nodes + node_num; 576 | node_max = nodes + node_num_max; 577 | memcpy(nodes, rhs.nodes, node_num_max * sizeof(node)); 578 | 579 | arcs = (arc*) malloc(arc_num_max * sizeof(arc)); 580 | arc_last = arcs + arc_num; 581 | arc_max = arcs + arc_num_max; 582 | memcpy(arcs, rhs.arcs, arc_num_max * sizeof(arc)); 583 | 584 | // Copy the old content to the new graph. 585 | size_t node_offset = (char*)nodes - (char*)rhs.nodes; 586 | size_t arc_offset = (char*)arcs - (char*)rhs.arcs; 587 | for(node* node_i = nodes; node_i < node_last; ++node_i) 588 | { 589 | if(node_i->next) 590 | node_i->next = (node*)((char*)node_i->next + node_offset); 591 | 592 | node_i->first = (arc*)((char*)node_i->first + arc_offset); 593 | node_i->parent = (arc*)((char*)node_i->parent + arc_offset); 594 | } 595 | 596 | for(arc* arc_i = arcs; arc_i < arc_last; ++arc_i) 597 | { 598 | if(arc_i->next) 599 | arc_i->next = (arc*)((char*)arc_i->next + arc_offset); 600 | if(arc_i->sister) 601 | arc_i->sister = (arc*)((char*)arc_i->sister + arc_offset); 602 | 603 | arc_i->head = (node*)((char*)arc_i->head + node_offset); 604 | } 605 | } 606 | 607 | template 608 | Graph::~Graph() 609 | { 610 | if (nodeptr_block) 611 | { 612 | delete nodeptr_block; 613 | nodeptr_block = NULL; 614 | } 615 | free(nodes); 616 | free(arcs); 617 | } 618 | 619 | template 620 | void Graph::reset() 621 | { 622 | node_last = nodes; 623 | arc_last = arcs; 624 | node_num = 0; 625 | 626 | if (nodeptr_block) 627 | { 628 | delete nodeptr_block; 629 | nodeptr_block = NULL; 630 | } 631 | 632 | maxflow_iteration = 0; 633 | flow = 0; 634 | } 635 | 636 | template 637 | void Graph::reallocate_nodes(int num) 638 | { 639 | int node_num_max = (int)(node_max - nodes); 640 | node* nodes_old = nodes; 641 | 642 | node_num_max += node_num_max / 2; 643 | if (node_num_max < node_num + num) node_num_max = node_num + num; 644 | nodes = (node*) realloc(nodes_old, node_num_max*sizeof(node)); 645 | if (!nodes) { if (error_function) (*error_function)("Not enough memory!"); exit(1); } 646 | 647 | node_last = nodes + node_num; 648 | node_max = nodes + node_num_max; 649 | 650 | if (nodes != nodes_old) 651 | { 652 | node* i; 653 | arc* a; 654 | for (i=nodes; inext) i->next = (node*) ((char*)i->next + (((char*) nodes) - ((char*) nodes_old))); 657 | } 658 | for (a=arcs; ahead = (node*) ((char*)a->head + (((char*) nodes) - ((char*) nodes_old))); 661 | } 662 | } 663 | } 664 | 665 | template 666 | void Graph::reallocate_arcs() 667 | { 668 | int arc_num_max = (int)(arc_max - arcs); 669 | int arc_num = (int)(arc_last - arcs); 670 | arc* arcs_old = arcs; 671 | 672 | arc_num_max += arc_num_max / 2; if (arc_num_max & 1) arc_num_max ++; 673 | arcs = (arc*) realloc(arcs_old, arc_num_max*sizeof(arc)); 674 | if (!arcs) { if (error_function) (*error_function)("Not enough memory!"); exit(1); } 675 | 676 | arc_last = arcs + arc_num; 677 | arc_max = arcs + arc_num_max; 678 | 679 | if (arcs != arcs_old) 680 | { 681 | node* i; 682 | arc* a; 683 | for (i=nodes; ifirst) i->first = (arc*) ((char*)i->first + (((char*) arcs) - ((char*) arcs_old))); 686 | if (i->parent && i->parent != ORPHAN && i->parent != TERMINAL) i->parent = (arc*) ((char*)i->parent + (((char*) arcs) - ((char*) arcs_old))); 687 | } 688 | for (a=arcs; anext) a->next = (arc*) ((char*)a->next + (((char*) arcs) - ((char*) arcs_old))); 691 | a->sister = (arc*) ((char*)a->sister + (((char*) arcs) - ((char*) arcs_old))); 692 | } 693 | } 694 | } 695 | 696 | #include "../grid.h" 697 | 698 | #endif 699 | -------------------------------------------------------------------------------- /maxflow/src/core/instances.inc: -------------------------------------------------------------------------------- 1 | #include "graph.h" 2 | 3 | #ifdef _MSC_VER 4 | #pragma warning(disable: 4661) 5 | #endif 6 | 7 | // Instantiations: 8 | // IMPORTANT: 9 | // flowtype should be 'larger' than tcaptype 10 | // tcaptype should be 'larger' than captype 11 | 12 | template class Graph; 13 | // template class Graph; 14 | // template class Graph; 15 | template class Graph; 16 | -------------------------------------------------------------------------------- /maxflow/src/core/maxflow.cpp: -------------------------------------------------------------------------------- 1 | /* maxflow.cpp */ 2 | 3 | 4 | #include 5 | #include "graph.h" 6 | 7 | #define INFINITE_D ((int)(((unsigned)-1)/2)) /* infinite distance to the terminal */ 8 | 9 | /***********************************************************************/ 10 | 11 | /* 12 | Functions for processing active list. 13 | i->next points to the next node in the list 14 | (or to i, if i is the last node in the list). 15 | If i->next is NULL iff i is not in the list. 16 | 17 | There are two queues. Active nodes are added 18 | to the end of the second queue and read from 19 | the front of the first queue. If the first queue 20 | is empty, it is replaced by the second queue 21 | (and the second queue becomes empty). 22 | */ 23 | 24 | 25 | template 26 | inline void Graph::set_active(node *i) 27 | { 28 | if (!i->next) 29 | { 30 | /* it's not in the list yet */ 31 | if (queue_last[1]) queue_last[1] -> next = i; 32 | else queue_first[1] = i; 33 | queue_last[1] = i; 34 | i -> next = i; 35 | } 36 | } 37 | 38 | /* 39 | Returns the next active node. 40 | If it is connected to the sink, it stays in the list, 41 | otherwise it is removed from the list 42 | */ 43 | template 44 | inline typename Graph::node* Graph::next_active() 45 | { 46 | node *i; 47 | 48 | while ( 1 ) 49 | { 50 | if (!(i=queue_first[0])) 51 | { 52 | queue_first[0] = i = queue_first[1]; 53 | queue_last[0] = queue_last[1]; 54 | queue_first[1] = NULL; 55 | queue_last[1] = NULL; 56 | if (!i) return NULL; 57 | } 58 | 59 | /* remove it from the active list */ 60 | if (i->next == i) queue_first[0] = queue_last[0] = NULL; 61 | else queue_first[0] = i -> next; 62 | i -> next = NULL; 63 | 64 | /* a node in the list is active iff it has a parent */ 65 | if (i->parent) return i; 66 | } 67 | } 68 | 69 | /***********************************************************************/ 70 | 71 | template 72 | inline void Graph::set_orphan_front(node *i) 73 | { 74 | nodeptr *np; 75 | i -> parent = ORPHAN; 76 | np = nodeptr_block -> New(); 77 | np -> ptr = i; 78 | np -> next = orphan_first; 79 | orphan_first = np; 80 | } 81 | 82 | template 83 | inline void Graph::set_orphan_rear(node *i) 84 | { 85 | nodeptr *np; 86 | i -> parent = ORPHAN; 87 | np = nodeptr_block -> New(); 88 | np -> ptr = i; 89 | if (orphan_last) orphan_last -> next = np; 90 | else orphan_first = np; 91 | orphan_last = np; 92 | np -> next = NULL; 93 | } 94 | 95 | /***********************************************************************/ 96 | 97 | template 98 | inline void Graph::add_to_changed_list(node *i) 99 | { 100 | if (changed_list && !i->is_in_changed_list) 101 | { 102 | node_id* ptr = changed_list->New(); 103 | *ptr = (node_id)(i - nodes); 104 | i->is_in_changed_list = true; 105 | } 106 | } 107 | 108 | /***********************************************************************/ 109 | 110 | template 111 | void Graph::maxflow_init() 112 | { 113 | node *i; 114 | 115 | queue_first[0] = queue_last[0] = NULL; 116 | queue_first[1] = queue_last[1] = NULL; 117 | orphan_first = NULL; 118 | 119 | TIME = 0; 120 | 121 | for (i=nodes; i next = NULL; 124 | i -> is_marked = 0; 125 | i -> is_in_changed_list = 0; 126 | i -> TS = TIME; 127 | if (i->tr_cap > 0) 128 | { 129 | /* i is connected to the source */ 130 | i -> is_sink = 0; 131 | i -> parent = TERMINAL; 132 | set_active(i); 133 | i -> DIST = 1; 134 | } 135 | else if (i->tr_cap < 0) 136 | { 137 | /* i is connected to the sink */ 138 | i -> is_sink = 1; 139 | i -> parent = TERMINAL; 140 | set_active(i); 141 | i -> DIST = 1; 142 | } 143 | else 144 | { 145 | i -> parent = NULL; 146 | } 147 | } 148 | } 149 | 150 | template 151 | void Graph::maxflow_reuse_trees_init() 152 | { 153 | node* i; 154 | node* j; 155 | node* queue = queue_first[1]; 156 | arc* a; 157 | nodeptr* np; 158 | 159 | queue_first[0] = queue_last[0] = NULL; 160 | queue_first[1] = queue_last[1] = NULL; 161 | orphan_first = orphan_last = NULL; 162 | 163 | TIME ++; 164 | 165 | while ((i=queue)) 166 | { 167 | queue = i->next; 168 | if (queue == i) queue = NULL; 169 | i->next = NULL; 170 | i->is_marked = 0; 171 | set_active(i); 172 | 173 | if (i->tr_cap == 0) 174 | { 175 | if (i->parent) set_orphan_rear(i); 176 | continue; 177 | } 178 | 179 | if (i->tr_cap > 0) 180 | { 181 | if (!i->parent || i->is_sink) 182 | { 183 | i->is_sink = 0; 184 | for (a=i->first; a; a=a->next) 185 | { 186 | j = a->head; 187 | if (!j->is_marked) 188 | { 189 | if (j->parent == a->sister) set_orphan_rear(j); 190 | if (j->parent && j->is_sink && a->r_cap > 0) set_active(j); 191 | } 192 | } 193 | add_to_changed_list(i); 194 | } 195 | } 196 | else 197 | { 198 | if (!i->parent || !i->is_sink) 199 | { 200 | i->is_sink = 1; 201 | for (a=i->first; a; a=a->next) 202 | { 203 | j = a->head; 204 | if (!j->is_marked) 205 | { 206 | if (j->parent == a->sister) set_orphan_rear(j); 207 | if (j->parent && !j->is_sink && a->sister->r_cap > 0) set_active(j); 208 | } 209 | } 210 | add_to_changed_list(i); 211 | } 212 | } 213 | i->parent = TERMINAL; 214 | i -> TS = TIME; 215 | i -> DIST = 1; 216 | } 217 | 218 | //test_consistency(); 219 | 220 | /* adoption */ 221 | while ((np=orphan_first)) 222 | { 223 | orphan_first = np -> next; 224 | i = np -> ptr; 225 | nodeptr_block -> Delete(np); 226 | if (!orphan_first) orphan_last = NULL; 227 | if (i->is_sink) process_sink_orphan(i); 228 | else process_source_orphan(i); 229 | } 230 | /* adoption end */ 231 | 232 | //test_consistency(); 233 | } 234 | 235 | template 236 | void Graph::augment(arc *middle_arc) 237 | { 238 | node *i; 239 | arc *a; 240 | tcaptype bottleneck; 241 | 242 | 243 | /* 1. Finding bottleneck capacity */ 244 | /* 1a - the source tree */ 245 | bottleneck = middle_arc -> r_cap; 246 | for (i=middle_arc->sister->head; ; i=a->head) 247 | { 248 | a = i -> parent; 249 | if (a == TERMINAL) break; 250 | if (bottleneck > a->sister->r_cap) bottleneck = a -> sister -> r_cap; 251 | } 252 | if (bottleneck > i->tr_cap) bottleneck = i -> tr_cap; 253 | /* 1b - the sink tree */ 254 | for (i=middle_arc->head; ; i=a->head) 255 | { 256 | a = i -> parent; 257 | if (a == TERMINAL) break; 258 | if (bottleneck > a->r_cap) bottleneck = a -> r_cap; 259 | } 260 | if (bottleneck > - i->tr_cap) bottleneck = - i -> tr_cap; 261 | 262 | 263 | /* 2. Augmenting */ 264 | /* 2a - the source tree */ 265 | middle_arc -> sister -> r_cap += bottleneck; 266 | middle_arc -> r_cap -= bottleneck; 267 | for (i=middle_arc->sister->head; ; i=a->head) 268 | { 269 | a = i -> parent; 270 | if (a == TERMINAL) break; 271 | a -> r_cap += bottleneck; 272 | a -> sister -> r_cap -= bottleneck; 273 | if (!a->sister->r_cap) 274 | { 275 | set_orphan_front(i); // add i to the beginning of the adoption list 276 | } 277 | } 278 | i -> tr_cap -= bottleneck; 279 | if (!i->tr_cap) 280 | { 281 | set_orphan_front(i); // add i to the beginning of the adoption list 282 | } 283 | /* 2b - the sink tree */ 284 | for (i=middle_arc->head; ; i=a->head) 285 | { 286 | a = i -> parent; 287 | if (a == TERMINAL) break; 288 | a -> sister -> r_cap += bottleneck; 289 | a -> r_cap -= bottleneck; 290 | if (!a->r_cap) 291 | { 292 | set_orphan_front(i); // add i to the beginning of the adoption list 293 | } 294 | } 295 | i -> tr_cap += bottleneck; 296 | if (!i->tr_cap) 297 | { 298 | set_orphan_front(i); // add i to the beginning of the adoption list 299 | } 300 | 301 | 302 | flow += bottleneck; 303 | } 304 | 305 | /***********************************************************************/ 306 | 307 | template 308 | void Graph::process_source_orphan(node *i) 309 | { 310 | node *j; 311 | arc *a0, *a0_min = NULL, *a; 312 | int d, d_min = INFINITE_D; 313 | 314 | /* trying to find a new parent */ 315 | for (a0=i->first; a0; a0=a0->next) 316 | if (a0->sister->r_cap) 317 | { 318 | j = a0 -> head; 319 | if (!j->is_sink && (a=j->parent)) 320 | { 321 | /* checking the origin of j */ 322 | d = 0; 323 | while ( 1 ) 324 | { 325 | if (j->TS == TIME) 326 | { 327 | d += j -> DIST; 328 | break; 329 | } 330 | a = j -> parent; 331 | d ++; 332 | if (a==TERMINAL) 333 | { 334 | j -> TS = TIME; 335 | j -> DIST = 1; 336 | break; 337 | } 338 | if (a==ORPHAN) { d = INFINITE_D; break; } 339 | j = a -> head; 340 | } 341 | if (dhead; j->TS!=TIME; j=j->parent->head) 350 | { 351 | j -> TS = TIME; 352 | j -> DIST = d --; 353 | } 354 | } 355 | } 356 | } 357 | 358 | if ((i->parent = a0_min)) 359 | { 360 | i -> TS = TIME; 361 | i -> DIST = d_min + 1; 362 | } 363 | else 364 | { 365 | /* no parent is found */ 366 | add_to_changed_list(i); 367 | 368 | /* process neighbors */ 369 | for (a0=i->first; a0; a0=a0->next) 370 | { 371 | j = a0 -> head; 372 | if (!j->is_sink && (a=j->parent)) 373 | { 374 | if (a0->sister->r_cap) set_active(j); 375 | if (a!=TERMINAL && a!=ORPHAN && a->head==i) 376 | { 377 | set_orphan_rear(j); // add j to the end of the adoption list 378 | } 379 | } 380 | } 381 | } 382 | } 383 | 384 | template 385 | void Graph::process_sink_orphan(node *i) 386 | { 387 | node *j; 388 | arc *a0, *a0_min = NULL, *a; 389 | int d, d_min = INFINITE_D; 390 | 391 | /* trying to find a new parent */ 392 | for (a0=i->first; a0; a0=a0->next) 393 | if (a0->r_cap) 394 | { 395 | j = a0 -> head; 396 | if (j->is_sink && (a=j->parent)) 397 | { 398 | /* checking the origin of j */ 399 | d = 0; 400 | while ( 1 ) 401 | { 402 | if (j->TS == TIME) 403 | { 404 | d += j -> DIST; 405 | break; 406 | } 407 | a = j -> parent; 408 | d ++; 409 | if (a==TERMINAL) 410 | { 411 | j -> TS = TIME; 412 | j -> DIST = 1; 413 | break; 414 | } 415 | if (a==ORPHAN) { d = INFINITE_D; break; } 416 | j = a -> head; 417 | } 418 | if (dhead; j->TS!=TIME; j=j->parent->head) 427 | { 428 | j -> TS = TIME; 429 | j -> DIST = d --; 430 | } 431 | } 432 | } 433 | } 434 | 435 | if ((i->parent = a0_min)) 436 | { 437 | i -> TS = TIME; 438 | i -> DIST = d_min + 1; 439 | } 440 | else 441 | { 442 | /* no parent is found */ 443 | add_to_changed_list(i); 444 | 445 | /* process neighbors */ 446 | for (a0=i->first; a0; a0=a0->next) 447 | { 448 | j = a0 -> head; 449 | if (j->is_sink && (a=j->parent)) 450 | { 451 | if (a0->r_cap) set_active(j); 452 | if (a!=TERMINAL && a!=ORPHAN && a->head==i) 453 | { 454 | set_orphan_rear(j); // add j to the end of the adoption list 455 | } 456 | } 457 | } 458 | } 459 | } 460 | 461 | /***********************************************************************/ 462 | 463 | template 464 | flowtype Graph::maxflow(bool reuse_trees, Block* _changed_list) 465 | { 466 | node *i, *j, *current_node = NULL; 467 | arc *a; 468 | nodeptr *np, *np_next; 469 | 470 | if (!nodeptr_block) 471 | { 472 | nodeptr_block = new DBlock(NODEPTR_BLOCK_SIZE, error_function); 473 | } 474 | 475 | changed_list = _changed_list; 476 | if (maxflow_iteration == 0 && reuse_trees) { if (error_function) (*error_function)("reuse_trees cannot be used in the first call to maxflow()!"); exit(1); } 477 | if (changed_list && !reuse_trees) { if (error_function) (*error_function)("changed_list cannot be used without reuse_trees!"); exit(1); } 478 | 479 | if (reuse_trees) maxflow_reuse_trees_init(); 480 | else maxflow_init(); 481 | 482 | // main loop 483 | while ( 1 ) 484 | { 485 | // test_consistency(current_node); 486 | 487 | if ((i=current_node)) 488 | { 489 | i -> next = NULL; /* remove active flag */ 490 | if (!i->parent) i = NULL; 491 | } 492 | if (!i) 493 | { 494 | if (!(i = next_active())) break; 495 | } 496 | 497 | /* growth */ 498 | if (!i->is_sink) 499 | { 500 | /* grow source tree */ 501 | for (a=i->first; a; a=a->next) 502 | if (a->r_cap) 503 | { 504 | j = a -> head; 505 | if (!j->parent) 506 | { 507 | j -> is_sink = 0; 508 | j -> parent = a -> sister; 509 | j -> TS = i -> TS; 510 | j -> DIST = i -> DIST + 1; 511 | set_active(j); 512 | add_to_changed_list(j); 513 | } 514 | else if (j->is_sink) break; 515 | else if (j->TS <= i->TS && 516 | j->DIST > i->DIST) 517 | { 518 | /* heuristic - trying to make the distance from j to the source shorter */ 519 | j -> parent = a -> sister; 520 | j -> TS = i -> TS; 521 | j -> DIST = i -> DIST + 1; 522 | } 523 | } 524 | } 525 | else 526 | { 527 | /* grow sink tree */ 528 | for (a=i->first; a; a=a->next) 529 | if (a->sister->r_cap) 530 | { 531 | j = a -> head; 532 | if (!j->parent) 533 | { 534 | j -> is_sink = 1; 535 | j -> parent = a -> sister; 536 | j -> TS = i -> TS; 537 | j -> DIST = i -> DIST + 1; 538 | set_active(j); 539 | add_to_changed_list(j); 540 | } 541 | else if (!j->is_sink) { a = a -> sister; break; } 542 | else if (j->TS <= i->TS && 543 | j->DIST > i->DIST) 544 | { 545 | /* heuristic - trying to make the distance from j to the sink shorter */ 546 | j -> parent = a -> sister; 547 | j -> TS = i -> TS; 548 | j -> DIST = i -> DIST + 1; 549 | } 550 | } 551 | } 552 | 553 | TIME ++; 554 | 555 | if (a) 556 | { 557 | i -> next = i; /* set active flag */ 558 | current_node = i; 559 | 560 | /* augmentation */ 561 | augment(a); 562 | /* augmentation end */ 563 | 564 | /* adoption */ 565 | while ((np=orphan_first)) 566 | { 567 | np_next = np -> next; 568 | np -> next = NULL; 569 | 570 | while ((np=orphan_first)) 571 | { 572 | orphan_first = np -> next; 573 | i = np -> ptr; 574 | nodeptr_block -> Delete(np); 575 | if (!orphan_first) orphan_last = NULL; 576 | if (i->is_sink) process_sink_orphan(i); 577 | else process_source_orphan(i); 578 | } 579 | 580 | orphan_first = np_next; 581 | } 582 | /* adoption end */ 583 | } 584 | else current_node = NULL; 585 | } 586 | // test_consistency(); 587 | 588 | if (!reuse_trees || (maxflow_iteration % 64) == 0) 589 | { 590 | delete nodeptr_block; 591 | nodeptr_block = NULL; 592 | } 593 | 594 | maxflow_iteration ++; 595 | return flow; 596 | } 597 | 598 | /***********************************************************************/ 599 | 600 | 601 | template 602 | void Graph::test_consistency(node* current_node) 603 | { 604 | node *i; 605 | arc *a; 606 | int r; 607 | int num1 = 0, num2 = 0; 608 | 609 | // test whether all nodes i with i->next!=NULL are indeed in the queue 610 | for (i=nodes; inext || i==current_node) num1 ++; 613 | } 614 | for (r=0; r<3; r++) 615 | { 616 | i = (r == 2) ? current_node : queue_first[r]; 617 | if (i) 618 | for ( ; ; i=i->next) 619 | { 620 | num2 ++; 621 | if (i->next == i) 622 | { 623 | if (r<2) assert(i == queue_last[r]); 624 | else assert(i == current_node); 625 | break; 626 | } 627 | } 628 | } 629 | assert(num1 == num2); 630 | 631 | for (i=nodes; iparent == NULL) {} 635 | else if (i->parent == ORPHAN) {} 636 | else if (i->parent == TERMINAL) 637 | { 638 | if (!i->is_sink) assert(i->tr_cap > 0); 639 | else assert(i->tr_cap < 0); 640 | } 641 | else 642 | { 643 | if (!i->is_sink) assert (i->parent->sister->r_cap > 0); 644 | else assert (i->parent->r_cap > 0); 645 | } 646 | // test whether passive nodes in search trees have neighbors in 647 | // a different tree through non-saturated edges 648 | if (i->parent && !i->next) 649 | { 650 | if (!i->is_sink) 651 | { 652 | assert(i->tr_cap >= 0); 653 | for (a=i->first; a; a=a->next) 654 | { 655 | if (a->r_cap > 0) assert(a->head->parent && !a->head->is_sink); 656 | } 657 | } 658 | else 659 | { 660 | assert(i->tr_cap <= 0); 661 | for (a=i->first; a; a=a->next) 662 | { 663 | if (a->sister->r_cap > 0) assert(a->head->parent && a->head->is_sink); 664 | } 665 | } 666 | } 667 | // test marking invariants 668 | if (i->parent && i->parent!=ORPHAN && i->parent!=TERMINAL) 669 | { 670 | assert(i->TS <= i->parent->head->TS); 671 | if (i->TS == i->parent->head->TS) assert(i->DIST > i->parent->head->DIST); 672 | } 673 | } 674 | } 675 | 676 | #include "instances.inc" 677 | -------------------------------------------------------------------------------- /maxflow/src/fastmin.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | #include "pyarraymodule.h" 10 | 11 | #include "fastmin.h" 12 | #include "core/graph.h" 13 | 14 | // This avoids linker errors on Windows 15 | #undef DL_IMPORT 16 | #define DL_IMPORT(t) t 17 | #include "_maxflow.h" 18 | 19 | void incr_indices(npy_intp* ind, int ndim, const npy_intp* shape) 20 | { 21 | // Update the index. 22 | for(int j = ndim-1; j >= 0; --j) 23 | { 24 | if(ind[j] + 1 < shape[j]) 25 | { 26 | ++ind[j]; 27 | break; 28 | } 29 | else 30 | ind[j] = 0; 31 | } 32 | } 33 | 34 | template 35 | PyObject* build_graph_energy_tuple(Graph* g, T energy); 36 | 37 | template <> 38 | PyObject* build_graph_energy_tuple(Graph* g, double energy) 39 | { 40 | PyObject_GraphFloat* graph = PyObject_New(PyObject_GraphFloat, &GraphFloat); 41 | graph->thisptr = g; 42 | PyObject* res = Py_BuildValue("(d,O)", energy, graph); 43 | Py_XDECREF(graph); 44 | return res; 45 | } 46 | 47 | template <> 48 | PyObject* build_graph_energy_tuple(Graph* g, long energy) 49 | { 50 | PyObject_GraphInt* graph = PyObject_New(PyObject_GraphInt, &GraphInt); 51 | graph->thisptr = g; 52 | PyObject* res = Py_BuildValue("(l,O)", energy, graph); 53 | Py_XDECREF(graph); 54 | return res; 55 | } 56 | 57 | /* 58 | * Alpha-expansion with a graph cut. 59 | */ 60 | template 61 | PyObject* aexpansion(int alpha, PyArrayObject* d, PyArrayObject* v, 62 | PyArrayObject* labels) 63 | { 64 | typedef Graph GraphT; 65 | 66 | // Size of the labels matrix. 67 | int ndim = PyArray_NDIM(labels); 68 | npy_intp* shape = PyArray_DIMS(labels); 69 | 70 | // Some shape checks. 71 | if(PyArray_NDIM(d) != ndim+1) 72 | throw std::runtime_error("the unary term matrix D must be SxL (S=shape of labels array, L=number of labels)"); 73 | if(PyArray_NDIM(v) != 2 || PyArray_DIM(v, 0) != PyArray_DIM(v, 1)) 74 | throw std::runtime_error("the binary term matrix V must be LxL (L=number of labels)"); 75 | if(PyArray_DIM(v,0) != PyArray_DIM(d, ndim)) 76 | throw std::runtime_error("the number of labels given by D differs from the number of labels given by V"); 77 | if(PyArray_TYPE(v) != numpy_typemap::type) 78 | throw std::runtime_error("the type for the binary term matrix V must match the type of the unary matrix D"); 79 | if(!std::equal(shape, shape+ndim, PyArray_DIMS(d))) 80 | throw std::runtime_error("the shape of the labels array (S1,...,SN) must match the shape of the first dimensions of D (S1,...,SN,L)"); 81 | 82 | // Create the graph. 83 | // The number of nodes and edges is unknown at this point, 84 | // so they are roughly estimated. 85 | int num_nodes = std::accumulate(shape, shape+ndim, 1, std::multiplies()); 86 | GraphT* g = new GraphT(num_nodes, 2*ndim*num_nodes); 87 | g->add_node(num_nodes); 88 | 89 | // Get the array v from v_f. 90 | // Esmooth v(v_f); 91 | 92 | // For each pixel in labels... 93 | npy_intp* head_ind = new npy_intp[ndim+1]; 94 | npy_intp* ind = head_ind; 95 | npy_intp* nind = new npy_intp[ndim]; 96 | std::fill(ind, ind+ndim, 0); 97 | for(int node_index = 0; node_index < num_nodes; ++node_index) 98 | { 99 | // Take the label of current pixel. 100 | S label = *reinterpret_cast(PyArray_GetPtr(labels, ind)); 101 | // Discard pixels not in the set P_{ab}. 102 | head_ind[ndim] = alpha; 103 | T t1 = *reinterpret_cast(PyArray_GetPtr(d, head_ind)); 104 | T t2 = std::numeric_limits::max(); 105 | if(label != alpha) 106 | { 107 | head_ind[ndim] = label; 108 | t2 = *reinterpret_cast(PyArray_GetPtr(d, head_ind)); 109 | } 110 | 111 | g->add_tweights(node_index, t1, t2); 112 | 113 | // Process the neighbors. 114 | for(int n = 0; n < ndim; ++n) 115 | { 116 | std::copy(ind, ind+ndim, nind); 117 | ++nind[n]; 118 | // Discard bad neighbors. 119 | if(nind[n] >= shape[n]) 120 | continue; 121 | 122 | // Neighbor index and label. 123 | int nnode_index = node_index + std::accumulate(shape+n+1, shape+ndim, 1, std::multiplies()); 124 | S nlabel = *reinterpret_cast(PyArray_GetPtr(labels, nind)); 125 | 126 | T dist_label_alpha = *reinterpret_cast(PyArray_GETPTR2(v, label, alpha)); 127 | if(label == nlabel) 128 | { 129 | g->add_edge(node_index, nnode_index, dist_label_alpha, dist_label_alpha); 130 | } 131 | else 132 | { 133 | // If labels are different, add an extra node. 134 | T dist_label_nlabel = *reinterpret_cast(PyArray_GETPTR2(v, label, nlabel)); 135 | T dist_nlabel_alpha = *reinterpret_cast(PyArray_GETPTR2(v, nlabel, alpha)); 136 | int extra_index = g->add_node(1); 137 | g->add_tweights(extra_index, 0, dist_label_nlabel); 138 | g->add_edge(node_index, extra_index, dist_label_alpha, dist_label_alpha); 139 | g->add_edge(nnode_index, extra_index, dist_nlabel_alpha, dist_nlabel_alpha); 140 | } 141 | } 142 | 143 | // Update the index. 144 | incr_indices(ind, ndim, shape); 145 | } 146 | 147 | // The graph cut. 148 | T energy = g->maxflow(); 149 | 150 | // Update the labels with the maxflow result. 151 | std::fill(ind, ind+ndim, 0); 152 | for(int node_index = 0; node_index < num_nodes; ++node_index) 153 | { 154 | if(g->what_segment(node_index) == SINK) 155 | *reinterpret_cast(PyArray_GetPtr(labels, ind)) = alpha; 156 | 157 | // Update the index. 158 | incr_indices(ind, ndim, shape); 159 | } 160 | 161 | delete [] head_ind; 162 | delete [] nind; 163 | 164 | // Return the graph and the energy of the mincut. 165 | return build_graph_energy_tuple(g, energy); 166 | } 167 | 168 | #define DISPATCH(name, ctype, parameters) \ 169 | case numpy_typemap::type: \ 170 | return nameparameters; 171 | 172 | template 173 | PyObject* aexpansion_(int alpha, PyArrayObject* d, PyArrayObject* v, PyArrayObject* labels) 174 | { 175 | switch(PyArray_TYPE(labels)) 176 | { 177 | DISPATCH(aexpansion, char, (alpha, d, v, labels)); 178 | DISPATCH(aexpansion, short, (alpha, d, v, labels)); 179 | DISPATCH(aexpansion, int, (alpha, d, v, labels)); 180 | DISPATCH(aexpansion, long, (alpha, d, v, labels)); 181 | DISPATCH(aexpansion, long long, (alpha, d, v, labels)); 182 | default: 183 | throw std::runtime_error("invalid type for labels (should be any integer type)"); 184 | } 185 | } 186 | 187 | // Access point for the aexpansion function. 188 | PyObject* aexpansion(int alpha, PyArrayObject* d, PyArrayObject* v, 189 | PyArrayObject* labels) 190 | { 191 | if(PyArray_TYPE(d) == NPY_DOUBLE) 192 | return aexpansion_(alpha, d, v, labels); 193 | else if(PyArray_TYPE(d) == NPY_LONG) 194 | return aexpansion_(alpha, d, v, labels); 195 | else 196 | throw std::runtime_error("the type of the unary term D is not valid (should be np.double or np.int)"); 197 | } 198 | 199 | /* 200 | * Alpha-beta swap with a graph cut. 201 | */ 202 | template 203 | PyObject* abswap(int alpha, int beta, PyArrayObject* d, PyArrayObject* v, 204 | PyArrayObject* labels) 205 | { 206 | typedef Graph GraphT; 207 | 208 | // Map graph node -> label index. 209 | std::vector lookup; 210 | // Map label index -> graph node. 211 | std::map reverse; 212 | 213 | // Size of the labels matrix. 214 | int ndim = PyArray_NDIM(labels); 215 | npy_intp* shape = PyArray_DIMS(labels); 216 | npy_intp* strides = PyArray_STRIDES(labels); 217 | 218 | // Some shape checks. 219 | if(PyArray_NDIM(d) != ndim+1) 220 | throw std::runtime_error("the unary term matrix D must be SxL (S=shape of labels array, L=number of labels)"); 221 | if(PyArray_NDIM(v) != 2 || PyArray_DIM(v, 0) != PyArray_DIM(v, 1)) 222 | throw std::runtime_error("the binary term matrix V must be LxL (L=number of labels)"); 223 | if(PyArray_DIM(v,0) != PyArray_DIM(d,ndim)) 224 | throw std::runtime_error("the number of labels given by D differs from the number of labels given by V"); 225 | if(PyArray_TYPE(v) != numpy_typemap::type) 226 | throw std::runtime_error("the type for the binary term matrix V must match the type of the unary matrix D"); 227 | if(!std::equal(shape, shape+ndim, PyArray_DIMS(d))) 228 | throw std::runtime_error("the shape of the labels array (S1,...,SN) must match the shape of the first dimensions of D (S1,...,SN,L)"); 229 | 230 | // Create the graph. 231 | // The number of nodes and edges is unknown at this point, 232 | // so they are roughly estimated. 233 | int num_nodes = std::accumulate(shape, shape+ndim, 1, std::multiplies()); 234 | GraphT* g = new GraphT(num_nodes, 2*ndim*num_nodes); 235 | 236 | // Get the distance V(a,b). 237 | T Vab = *reinterpret_cast(PyArray_GETPTR2(v, alpha, beta)); 238 | 239 | // For each pixel in labels... 240 | npy_intp* head_ind = new npy_intp[ndim+1]; 241 | npy_intp* ind = head_ind; 242 | npy_intp* nind = new npy_intp[ndim]; 243 | std::fill(ind, ind+ndim, 0); 244 | 245 | for(int i = 0; i < num_nodes; ++i, incr_indices(ind, ndim, shape)) 246 | { 247 | // Offset of the current pixel. 248 | //int labels_index = labels_indexbase + j * PyArray_STRIDE(labels, 1); 249 | int labels_index = std::inner_product(ind, ind+ndim, strides, 0); 250 | 251 | // Take the label of current pixel. 252 | S label = *reinterpret_cast(PyArray_BYTES(labels) + labels_index); 253 | 254 | // Discard pixels not in the set P_{ab}. 255 | if(label != alpha && label != beta) 256 | continue; 257 | 258 | int node_index = g->add_node(1); 259 | // Add to the lookup table. 260 | lookup.push_back(labels_index); 261 | // Add to the reverse map. 262 | reverse[labels_index] = node_index; 263 | 264 | // T-links weights initialization. 265 | head_ind[ndim] = alpha; 266 | T ta = *reinterpret_cast(PyArray_GetPtr(d, head_ind)); 267 | head_ind[ndim] = beta; 268 | T tb = *reinterpret_cast(PyArray_GetPtr(d, head_ind)); 269 | 270 | // Process the neighbors. 271 | for(int n = 0, dir = -1; n < ndim; n = dir == 1 ? n+1 : n, dir*=-1) 272 | { 273 | std::copy(ind, ind+ndim, nind); 274 | nind[n] += dir; 275 | 276 | // Discard bad neighbors. 277 | if(nind[n] < 0 || nind[n] >= shape[n]) 278 | continue; 279 | 280 | int labels_neighbor = std::inner_product(nind, nind+ndim, strides, 0); 281 | S label2 = *reinterpret_cast(PyArray_BYTES(labels) + labels_neighbor); 282 | if(label2 != alpha && label2 != beta) 283 | { 284 | // Add the weights to the t-links for the neighbors 285 | // not in P_{ab}. 286 | ta += *reinterpret_cast(PyArray_GETPTR2(v, alpha, label2)); 287 | tb += *reinterpret_cast(PyArray_GETPTR2(v, beta, label2)); 288 | } 289 | else if(dir == -1) 290 | // Add edges to the neighbors in P_{ab}. 291 | g->add_edge(node_index, reverse[labels_neighbor], Vab, Vab); 292 | } 293 | 294 | g->add_tweights(node_index, ta, tb); 295 | } 296 | 297 | // The graph cut. 298 | T energy = g->maxflow(); 299 | 300 | // Update the labels with the maxflow result. 301 | for(unsigned int i = 0; i < lookup.size(); ++i) 302 | { 303 | int labels_index = lookup[i]; 304 | S* label = reinterpret_cast(PyArray_BYTES(labels) + labels_index); 305 | *label = g->what_segment(i) == SINK ? alpha : beta; 306 | } 307 | 308 | delete [] head_ind; 309 | delete [] nind; 310 | 311 | // Return the graph and the energy of the mincut. 312 | return build_graph_energy_tuple(g, energy); 313 | } 314 | 315 | template 316 | PyObject* abswap_(int alpha, int beta, PyArrayObject* d, PyArrayObject* v, PyArrayObject* labels) 317 | { 318 | switch(PyArray_TYPE(labels)) 319 | { 320 | DISPATCH(abswap, char, (alpha, beta, d, v, labels)); 321 | DISPATCH(abswap, short, (alpha, beta, d, v, labels)); 322 | DISPATCH(abswap, int, (alpha, beta, d, v, labels)); 323 | DISPATCH(abswap, long, (alpha, beta, d, v, labels)); 324 | DISPATCH(abswap, long long, (alpha, beta, d, v, labels)); 325 | default: 326 | throw std::runtime_error("invalid type for labels (should be any integer type)"); 327 | } 328 | } 329 | 330 | // Access point for the abswap function. 331 | PyObject* abswap(int alpha, int beta, PyArrayObject* d, PyArrayObject* v, 332 | PyArrayObject* labels) 333 | { 334 | if(PyArray_TYPE(d) == NPY_DOUBLE) 335 | return abswap_(alpha, beta, d, v, labels); 336 | else if(PyArray_TYPE(d) == NPY_LONG) 337 | return abswap_(alpha, beta, d, v, labels); 338 | else 339 | throw std::runtime_error("the type of the unary term D is not v (should be np.double or np.int)"); 340 | } 341 | -------------------------------------------------------------------------------- /maxflow/src/fastmin.h: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Algorithms from "Fast approximate energy minimization via graph-cuts". 4 | */ 5 | 6 | #ifndef _FASTMIN_H 7 | #define _FASTMIN_H 8 | 9 | #include 10 | 11 | #include "core/graph.h" 12 | 13 | PyObject* abswap(int alpha, int beta, PyArrayObject* d, 14 | PyArrayObject* v, PyArrayObject* labels); 15 | PyObject* aexpansion(int alpha, PyArrayObject* d, 16 | PyArrayObject* v, PyArrayObject* labels); 17 | 18 | #endif 19 | -------------------------------------------------------------------------------- /maxflow/src/grid.h: -------------------------------------------------------------------------------- 1 | 2 | #ifndef _GRID_H 3 | #define _GRID_H 4 | 5 | #include 6 | #include 7 | #include 8 | 9 | // Some defines for backwards compatibility with previous APIs of NumPy 10 | #ifndef NPY_ARRAY_FORCECAST 11 | #define NPY_ARRAY_FORCECAST NPY_FORCECAST 12 | #endif 13 | 14 | template 15 | void getSparseStructure(PyArrayObject* structureArr, 16 | int ndim, 17 | std::vector, captype> >* structure) 18 | { 19 | typedef typename std::pair, captype> StructElem; 20 | 21 | // Check shape of the structure array. 22 | int structureNDIM = PyArray_NDIM(structureArr); 23 | npy_intp* structureShape = PyArray_DIMS(structureArr); 24 | int dimsdiff = ndim - structureNDIM; 25 | 26 | std::vector center(ndim, 0); 27 | for(int i = 0; i < structureNDIM; ++i) 28 | { 29 | int s = structureShape[i]; 30 | 31 | // Every dimension must be odd. 32 | if((s & 1) == 0) 33 | { 34 | throw std::runtime_error("the structure array must have an odd shape"); 35 | } 36 | 37 | center[i + dimsdiff] = s >> 1; 38 | } 39 | 40 | // Create the sparse representation of the structure 41 | NpyIter* iter = NpyIter_New(structureArr, 42 | NPY_ITER_READONLY | NPY_ITER_MULTI_INDEX, 43 | NPY_KEEPORDER, 44 | NPY_NO_CASTING, 45 | NULL); 46 | 47 | if(iter == NULL) 48 | throw std::runtime_error("unknown error creating a NpyIter"); 49 | 50 | NpyIter_IterNextFunc* iternext = NpyIter_GetIterNext(iter, NULL); 51 | NpyIter_GetMultiIndexFunc* getMI = NpyIter_GetGetMultiIndex(iter, NULL); 52 | char** dataptr = NpyIter_GetDataPtrArray(iter); 53 | 54 | npy_intp* mi = new npy_intp[ndim]; 55 | std::fill(mi, mi+ndim, 0); 56 | do 57 | { 58 | captype v = *reinterpret_cast(*dataptr); 59 | if(v == captype(0)) 60 | continue; 61 | 62 | getMI(iter, &mi[dimsdiff]); 63 | if(std::equal(mi, mi+ndim, center.begin())) 64 | continue; 65 | 66 | // Subtract the center coord 67 | std::transform(mi, mi+ndim, center.begin(), mi, std::minus()); 68 | 69 | structure->push_back(StructElem(std::vector(mi, mi+ndim), v)); 70 | }while(iternext(iter)); 71 | delete [] mi; 72 | 73 | NpyIter_Deallocate(iter); 74 | } 75 | 76 | template 77 | std::vector getVector(PyArrayObject* arr, int length) 78 | { 79 | int arr_ndim = PyArray_NDIM(arr); 80 | npy_intp* arr_shape = PyArray_DIMS(arr); 81 | 82 | if(arr_ndim > 1) 83 | throw std::runtime_error("`periodic` array must have at most 1 dimension"); 84 | 85 | if(arr_ndim == 0) 86 | { 87 | T value = *reinterpret_cast(PyArray_GetPtr(arr, NULL)); 88 | return std::vector(length, value); 89 | } 90 | 91 | // arr_ndim == 1 92 | if(arr_shape[0] < length) 93 | throw std::runtime_error("the length of `periodic` must be equal to the number of dimensions of `nodeids`"); 94 | 95 | std::vector result(length); 96 | for(npy_intp i = 0; i < length; ++i) 97 | result[i] = *reinterpret_cast(PyArray_GetPtr(arr, &i)); 98 | return result; 99 | } 100 | 101 | template 102 | void Graph::add_grid_edges(PyArrayObject* _nodeids, 103 | PyObject* _weights, 104 | PyObject* _structure, 105 | int symmetric, 106 | PyObject* _periodic) 107 | { 108 | typedef typename std::pair, captype> StructElem; 109 | typedef std::vector Structure; 110 | 111 | int ndim = PyArray_NDIM(_nodeids); 112 | PyArrayObject* nodeids = reinterpret_cast(PyArray_FROMANY((PyObject*)_nodeids, NPY_LONG, 0, 0, NPY_ITER_ALIGNED | NPY_ARRAY_FORCECAST)); 113 | if(nodeids == NULL) 114 | throw std::runtime_error("The horror"); 115 | 116 | PyArrayObject* weights = reinterpret_cast(PyArray_FROMANY(_weights, numpy_typemap::type, 0, ndim, NPY_ITER_ALIGNED | NPY_ARRAY_FORCECAST)); 117 | if(weights == NULL) 118 | { 119 | Py_DECREF(nodeids); 120 | throw std::runtime_error("invalid number of dimensions for `weights`"); 121 | } 122 | 123 | PyArrayObject* structureArr = reinterpret_cast(PyArray_FROMANY(_structure, numpy_typemap::type, 0, ndim, NPY_ITER_ALIGNED | NPY_ARRAY_FORCECAST)); 124 | if(structureArr == NULL) 125 | { 126 | Py_DECREF(weights); 127 | Py_DECREF(nodeids); 128 | throw std::runtime_error("invalid number of dimensions for `structure`"); 129 | } 130 | 131 | PyArrayObject* periodicArr = reinterpret_cast(PyArray_FROMANY(_periodic, numpy_typemap::type, 0, 1, NPY_ITER_ALIGNED | NPY_ARRAY_FORCECAST)); 132 | if(periodicArr == NULL) 133 | { 134 | Py_DECREF(structureArr); 135 | Py_DECREF(weights); 136 | Py_DECREF(nodeids); 137 | throw std::runtime_error("invalid value for `periodic`"); 138 | } 139 | 140 | npy_intp* shape = PyArray_DIMS(nodeids); 141 | 142 | // Extract the structure in a sparse format. 143 | Structure structure; 144 | std::vector periodic; 145 | try 146 | { 147 | getSparseStructure(structureArr, ndim, &structure); 148 | periodic = getVector(periodicArr, ndim); 149 | } 150 | catch(std::exception& e) 151 | { 152 | Py_DECREF(periodicArr); 153 | Py_DECREF(structureArr); 154 | Py_DECREF(weights); 155 | Py_DECREF(nodeids); 156 | throw e; 157 | } 158 | 159 | // Create the edges 160 | PyArrayObject* op[2] = {nodeids, weights}; 161 | npy_uint32 op_flags[2] = {NPY_ITER_READONLY, NPY_ITER_READONLY}; 162 | NpyIter* iter = NpyIter_MultiNew(2, op, 163 | NPY_ITER_MULTI_INDEX, 164 | NPY_KEEPORDER, 165 | NPY_NO_CASTING, 166 | op_flags, 167 | NULL); 168 | 169 | if(iter == NULL) 170 | { 171 | Py_DECREF(periodicArr); 172 | Py_DECREF(structureArr); 173 | Py_DECREF(weights); 174 | Py_DECREF(nodeids); 175 | throw std::runtime_error("unknown error creating a NpyIter"); 176 | } 177 | 178 | NpyIter_IterNextFunc* iternext = NpyIter_GetIterNext(iter, NULL); 179 | NpyIter_GetMultiIndexFunc* getMI = NpyIter_GetGetMultiIndex(iter, NULL); 180 | char** dataptr = NpyIter_GetDataPtrArray(iter); 181 | 182 | npy_intp* mi = new npy_intp[ndim]; 183 | npy_intp* n_mi = new npy_intp[ndim]; 184 | 185 | // Iterate over the full array. 186 | do 187 | { 188 | getMI(iter, mi); 189 | 190 | long i = *reinterpret_cast(dataptr[0]); 191 | captype w = *reinterpret_cast(dataptr[1]); 192 | 193 | // Neighbors... 194 | for(typename Structure::const_iterator it = structure.begin(); it != structure.end(); ++it) 195 | { 196 | const std::vector& offset = it->first; 197 | std::transform(mi, mi+ndim, offset.begin(), n_mi, std::plus()); 198 | 199 | // Check if the neighbor is valid. 200 | bool valid_neigh = true; 201 | for(int d = 0; d < ndim && valid_neigh; ++d) 202 | { 203 | if(n_mi[d] < 0 || n_mi[d] >= shape[d]) 204 | { 205 | if(periodic[d]) 206 | { 207 | n_mi[d] = n_mi[d] % shape[d]; 208 | 209 | // C++ has an awkward modulo operator. 210 | // Compensate for negative values. 211 | if(n_mi[d] < 0) 212 | n_mi[d] = shape[d] + n_mi[d]; 213 | } 214 | else 215 | valid_neigh = false; 216 | } 217 | } 218 | if(!valid_neigh) 219 | continue; 220 | 221 | // Get the neighbor. 222 | long j = *reinterpret_cast(PyArray_GetPtr(nodeids, n_mi)); 223 | 224 | captype capacity = w * it->second; 225 | 226 | add_edge(i, j, capacity, symmetric ? capacity : captype(0)); 227 | } 228 | 229 | }while(iternext(iter)); 230 | delete [] mi; 231 | delete [] n_mi; 232 | 233 | NpyIter_Deallocate(iter); 234 | 235 | Py_DECREF(periodicArr); 236 | Py_DECREF(structureArr); 237 | Py_DECREF(weights); 238 | Py_DECREF(nodeids); 239 | } 240 | 241 | template 242 | inline int Graph::get_arc_from(arc_id _a) 243 | { 244 | arc* a = reinterpret_cast(_a); 245 | assert(a >= arcs && a < arc_last); 246 | return (node_id) (a->sister->head - nodes); 247 | } 248 | 249 | template 250 | inline int Graph::get_arc_to(arc_id _a) 251 | { 252 | arc* a = reinterpret_cast(_a); 253 | assert(a >= arcs && a < arc_last); 254 | return (node_id) (a->head - nodes); 255 | } 256 | 257 | template 258 | void Graph::mark_grid_nodes(PyArrayObject* nodeids) 259 | { 260 | NpyIter* iter = NpyIter_New(nodeids, NPY_ITER_READONLY, NPY_KEEPORDER, NPY_NO_CASTING, NULL); 261 | if (iter == NULL) { 262 | throw std::runtime_error("unknown error creating a NpyIter"); 263 | } 264 | 265 | NpyIter_IterNextFunc *iternext = NpyIter_GetIterNext(iter, NULL); 266 | char** dataptr = NpyIter_GetDataPtrArray(iter); 267 | 268 | do { 269 | long node = *reinterpret_cast(dataptr[0]); 270 | mark_node(node); 271 | } while(iternext(iter)); 272 | 273 | NpyIter_Deallocate(iter); 274 | } 275 | 276 | template 277 | void Graph::add_grid_tedges(PyArrayObject* _nodeids, 278 | PyObject* _sourcecaps, 279 | PyObject* _sinkcaps) 280 | { 281 | PyArrayObject* nodeids = reinterpret_cast(PyArray_FROMANY((PyObject*)_nodeids, NPY_LONG, 0, 0, NPY_ITER_ALIGNED | NPY_ARRAY_FORCECAST)); 282 | int ndim = PyArray_NDIM(nodeids); 283 | 284 | PyArrayObject* sourcecaps = reinterpret_cast(PyArray_FROMANY(_sourcecaps, numpy_typemap::type, 0, ndim, NPY_ITER_ALIGNED | NPY_ARRAY_FORCECAST)); 285 | if(sourcecaps == NULL) 286 | { 287 | Py_DECREF(nodeids); 288 | throw std::runtime_error("invalid number of dimensions for sourcecaps"); 289 | } 290 | PyArrayObject* sinkcaps = reinterpret_cast(PyArray_FROMANY(_sinkcaps, numpy_typemap::type, 0, ndim, NPY_ITER_ALIGNED | NPY_ARRAY_FORCECAST)); 291 | if(sinkcaps == NULL) 292 | { 293 | Py_DECREF(sourcecaps); 294 | Py_DECREF(nodeids); 295 | throw std::runtime_error("invalid number of dimensions for sinkcaps"); 296 | } 297 | 298 | // Create the multiiterator. 299 | PyArrayObject* op[3] = {nodeids, sourcecaps, sinkcaps}; 300 | npy_uint32 op_flags[3] = {NPY_ITER_READONLY, NPY_ITER_READONLY, NPY_ITER_READONLY}; 301 | NpyIter* iter = NpyIter_MultiNew(3, op, 302 | 0, 303 | NPY_KEEPORDER, 304 | NPY_NO_CASTING, 305 | op_flags, 306 | NULL); 307 | if(iter == NULL) 308 | { 309 | Py_DECREF(sinkcaps); 310 | Py_DECREF(sourcecaps); 311 | Py_DECREF(nodeids); 312 | throw std::runtime_error("unknown error creating a NpyIter"); 313 | } 314 | 315 | NpyIter_IterNextFunc* iternext = NpyIter_GetIterNext(iter, NULL); 316 | char** dataptr = NpyIter_GetDataPtrArray(iter); 317 | do 318 | { 319 | long node = *reinterpret_cast(dataptr[0]); 320 | tcaptype src = *reinterpret_cast(dataptr[1]); 321 | tcaptype snk = *reinterpret_cast(dataptr[2]); 322 | add_tweights(node, src, snk); 323 | }while(iternext(iter)); 324 | 325 | NpyIter_Deallocate(iter); 326 | Py_DECREF(sinkcaps); 327 | Py_DECREF(sourcecaps); 328 | Py_DECREF(nodeids); 329 | } 330 | 331 | template 332 | PyArrayObject* Graph::get_grid_segments(PyArrayObject* nodeids) 333 | { 334 | PyArrayObject* op[2] = {nodeids, NULL}; 335 | npy_uint32 op_flags[2] = {NPY_ITER_READONLY, NPY_ITER_WRITEONLY | NPY_ITER_ALLOCATE}; 336 | PyArray_Descr* op_dtypes[2] = {NULL, PyArray_DescrFromType(NPY_BOOL)}; 337 | NpyIter* iter = NpyIter_MultiNew(2, op, 0, NPY_KEEPORDER, NPY_NO_CASTING, op_flags, op_dtypes); 338 | if(iter == NULL) 339 | throw std::runtime_error("unknown error creating a NpyIter"); 340 | 341 | NpyIter_IterNextFunc* iternext = NpyIter_GetIterNext(iter, NULL); 342 | char** dataptr = NpyIter_GetDataPtrArray(iter); 343 | 344 | do 345 | { 346 | long node = *reinterpret_cast(dataptr[0]); 347 | *reinterpret_cast(dataptr[1]) = what_segment(node) == SINK; 348 | }while(iternext(iter)); 349 | 350 | PyArrayObject* res = NpyIter_GetOperandArray(iter)[1]; 351 | Py_INCREF(res); 352 | NpyIter_Deallocate(iter); 353 | return res; 354 | } 355 | 356 | #endif 357 | -------------------------------------------------------------------------------- /maxflow/src/pyarray_symbol.h: -------------------------------------------------------------------------------- 1 | 2 | // #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION 3 | #define PY_ARRAY_UNIQUE_SYMBOL maxflow_PyArray_API 4 | -------------------------------------------------------------------------------- /maxflow/src/pyarraymodule.h: -------------------------------------------------------------------------------- 1 | 2 | #ifndef _EXTMODULE_H 3 | #define _EXTMODULE_H 4 | 5 | #include 6 | #include 7 | 8 | // #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION 9 | #define PY_ARRAY_UNIQUE_SYMBOL maxflow_PyArray_API 10 | #define NO_IMPORT_ARRAY 11 | #include "numpy/arrayobject.h" 12 | 13 | #include 14 | 15 | template 16 | struct numpy_typemap; 17 | 18 | #define define_numpy_type(ctype, dtype) \ 19 | template<> \ 20 | struct numpy_typemap \ 21 | {static const int type = dtype;}; 22 | 23 | define_numpy_type(bool, NPY_BOOL); 24 | define_numpy_type(char, NPY_BYTE); 25 | define_numpy_type(short, NPY_SHORT); 26 | define_numpy_type(int, NPY_INT); 27 | define_numpy_type(long, NPY_LONG); 28 | define_numpy_type(long long, NPY_LONGLONG); 29 | define_numpy_type(unsigned char, NPY_UBYTE); 30 | define_numpy_type(unsigned short, NPY_USHORT); 31 | define_numpy_type(unsigned int, NPY_UINT); 32 | define_numpy_type(unsigned long, NPY_ULONG); 33 | define_numpy_type(unsigned long long, NPY_ULONGLONG); 34 | define_numpy_type(float, NPY_FLOAT); 35 | define_numpy_type(double, NPY_DOUBLE); 36 | define_numpy_type(long double, NPY_LONGDOUBLE); 37 | define_numpy_type(std::complex, NPY_CFLOAT); 38 | define_numpy_type(std::complex, NPY_CDOUBLE); 39 | define_numpy_type(std::complex, NPY_CLONGDOUBLE); 40 | 41 | template 42 | T PyArray_SafeGet(const PyArrayObject* aobj, const npy_intp* indaux) 43 | { 44 | // HORROR. 45 | npy_intp* ind = const_cast(indaux); 46 | void* ptr = PyArray_GetPtr(const_cast(aobj), ind); 47 | switch(PyArray_TYPE(aobj)) 48 | { 49 | case NPY_BOOL: 50 | return static_cast(*reinterpret_cast(ptr)); 51 | case NPY_BYTE: 52 | return static_cast(*reinterpret_cast(ptr)); 53 | case NPY_SHORT: 54 | return static_cast(*reinterpret_cast(ptr)); 55 | case NPY_INT: 56 | return static_cast(*reinterpret_cast(ptr)); 57 | case NPY_LONG: 58 | return static_cast(*reinterpret_cast(ptr)); 59 | case NPY_LONGLONG: 60 | return static_cast(*reinterpret_cast(ptr)); 61 | case NPY_UBYTE: 62 | return static_cast(*reinterpret_cast(ptr)); 63 | case NPY_USHORT: 64 | return static_cast(*reinterpret_cast(ptr)); 65 | case NPY_UINT: 66 | return static_cast(*reinterpret_cast(ptr)); 67 | case NPY_ULONG: 68 | return static_cast(*reinterpret_cast(ptr)); 69 | case NPY_ULONGLONG: 70 | return static_cast(*reinterpret_cast(ptr)); 71 | case NPY_FLOAT: 72 | return static_cast(*reinterpret_cast(ptr)); 73 | case NPY_DOUBLE: 74 | return static_cast(*reinterpret_cast(ptr)); 75 | case NPY_LONGDOUBLE: 76 | return static_cast(*reinterpret_cast(ptr)); 77 | default: 78 | throw std::runtime_error("data type not supported"); 79 | } 80 | } 81 | 82 | template 83 | T PyArray_SafeSet(PyArrayObject* aobj, const npy_intp* indaux, const T& value) 84 | { 85 | // HORROR. 86 | npy_intp* ind = const_cast(indaux); 87 | void* ptr = PyArray_GetPtr(aobj, ind); 88 | switch(PyArray_TYPE(aobj)) 89 | { 90 | case NPY_BOOL: 91 | *reinterpret_cast(ptr) = static_cast(value); 92 | break; 93 | case NPY_BYTE: 94 | *reinterpret_cast(ptr) = static_cast(value); 95 | break; 96 | case NPY_SHORT: 97 | *reinterpret_cast(ptr) = static_cast(value); 98 | break; 99 | case NPY_INT: 100 | *reinterpret_cast(ptr) = static_cast(value); 101 | break; 102 | case NPY_LONG: 103 | *reinterpret_cast(ptr) = static_cast(value); 104 | break; 105 | case NPY_LONGLONG: 106 | *reinterpret_cast(ptr) = static_cast(value); 107 | break; 108 | case NPY_UBYTE: 109 | *reinterpret_cast(ptr) = static_cast(value); 110 | break; 111 | case NPY_USHORT: 112 | *reinterpret_cast(ptr) = static_cast(value); 113 | break; 114 | case NPY_UINT: 115 | *reinterpret_cast(ptr) = static_cast(value); 116 | break; 117 | case NPY_ULONG: 118 | *reinterpret_cast(ptr) = static_cast(value); 119 | break; 120 | case NPY_ULONGLONG: 121 | *reinterpret_cast(ptr) = static_cast(value); 122 | break; 123 | case NPY_FLOAT: 124 | *reinterpret_cast(ptr) = static_cast(value); 125 | break; 126 | case NPY_DOUBLE: 127 | *reinterpret_cast(ptr) = static_cast(value); 128 | break; 129 | case NPY_LONGDOUBLE: 130 | *reinterpret_cast(ptr) = static_cast(value); 131 | break; 132 | default: 133 | throw std::runtime_error("data type not supported"); 134 | } 135 | } 136 | 137 | #endif 138 | -------------------------------------------------------------------------------- /maxflow/version.py: -------------------------------------------------------------------------------- 1 | # -*- encoding:utf-8 -*- 2 | 3 | __version__ = "1.3.2" 4 | __version_core__ = (3, 0, 4) 5 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools", "wheel", "Cython", "numpy~=2.0"] 3 | build-backend = "setuptools.build_meta" 4 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [flake8] 2 | max-line-length=120 3 | per-file-ignores = __init__.py:F401 4 | exclude = doc/,build/ 5 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # -*- encoding: utf-8 -*- 2 | 3 | from setuptools import setup 4 | 5 | import runpy 6 | from distutils.extension import Extension 7 | 8 | import numpy 9 | from Cython.Build import cythonize 10 | 11 | # Get the version number. 12 | __version__ = runpy.run_path("maxflow/version.py")["__version__"] 13 | 14 | 15 | def extensions(): 16 | numpy_include_dir = numpy.get_include() 17 | maxflow_module = Extension( 18 | "maxflow._maxflow", 19 | [ 20 | "maxflow/src/_maxflow.pyx", 21 | "maxflow/src/core/maxflow.cpp", 22 | "maxflow/src/fastmin.cpp" 23 | ], 24 | language="c++", 25 | extra_compile_args=['-std=c++11', '-Wall'], 26 | include_dirs=[numpy_include_dir], 27 | depends=[ 28 | "maxflow/src/fastmin.h", 29 | "maxflow/src/grid.h", 30 | "maxflow/src/pyarray_symbol.h", 31 | "maxflow/src/pyarraymodule.h", 32 | "maxflow/src/core/block.h", 33 | "maxflow/src/core/graph.h" 34 | ], 35 | # Cython 0.29 generates code using the deprecated pre 1.7 NumPy API 36 | # This line should be uncommented when Cython 3.0 is officially released 37 | # define_macros=[("NPY_NO_DEPRECATED_API", "NPY_1_7_API_VERSION")] 38 | ) 39 | return cythonize( 40 | [maxflow_module], 41 | language_level="3" 42 | ) 43 | 44 | 45 | setup( 46 | name="PyMaxflow", 47 | version=__version__, 48 | description="A mincut/maxflow package for Python", 49 | author="Pablo Márquez Neila", 50 | author_email="pablo.marquez@unibe.ch", 51 | url="https://github.com/pmneila/PyMaxflow", 52 | license="GPL", 53 | long_description=""" 54 | PyMaxflow is a Python library for graph construction and 55 | maxflow computation (commonly known as `graph cuts`). The 56 | core of this library is the C++ implementation by 57 | Vladimir Kolmogorov, which can be downloaded from his 58 | `homepage `_. 59 | Besides the wrapper to the C++ library, PyMaxflow offers 60 | 61 | * NumPy integration, 62 | * methods for the construction of common graph 63 | layouts in computer vision and graphics, 64 | * implementation of algorithms for fast energy 65 | minimization which use the `maxflow` method: 66 | the alpha-beta-swap and the alpha-expansion. 67 | 68 | """, 69 | classifiers=[ 70 | "Development Status :: 4 - Beta", 71 | "Environment :: Console", 72 | "Intended Audience :: Developers", 73 | "Intended Audience :: Science/Research", 74 | "License :: OSI Approved :: GNU General Public License (GPL)", 75 | "Natural Language :: English", 76 | "Operating System :: OS Independent", 77 | "Programming Language :: C++", 78 | "Programming Language :: Python", 79 | "Topic :: Scientific/Engineering :: Image Recognition", 80 | "Topic :: Scientific/Engineering :: Artificial Intelligence", 81 | "Topic :: Scientific/Engineering :: Mathematics" 82 | ], 83 | packages=["maxflow"], 84 | ext_modules=extensions(), 85 | install_requires=['numpy>=1.26'] 86 | ) 87 | -------------------------------------------------------------------------------- /test_maxflow.py: -------------------------------------------------------------------------------- 1 | 2 | import pytest 3 | 4 | import numpy as np 5 | from numpy.testing import assert_array_equal 6 | from networkx.utils import graphs_equal 7 | 8 | from imageio.v3 import imread 9 | 10 | import maxflow 11 | 12 | 13 | @pytest.mark.parametrize("type", [int, float]) 14 | def test_simple(type): 15 | g = maxflow.Graph[type](2, 2) 16 | nodes = g.add_nodes(2) 17 | g.add_edge(nodes[0], nodes[1], 1, 2) 18 | g.add_tedge(nodes[0], 2, 5) 19 | g.add_tedge(nodes[1], 9, 4) 20 | 21 | # Find the maxflow. 22 | flow = g.maxflow() 23 | 24 | assert flow == 8 25 | assert g.get_segment(nodes[0]) == 1 26 | assert g.get_segment(nodes[1]) == 0 27 | 28 | 29 | def test_restoration(): 30 | 31 | img = imread("examples/a2.png") 32 | g = maxflow.Graph[int](0, 0) 33 | nodeids = g.add_grid_nodes(img.shape) 34 | g.add_grid_edges(nodeids, 50) 35 | g.add_grid_tedges(nodeids, img, 255-img) 36 | 37 | g.get_nx_graph() 38 | 39 | g.maxflow() 40 | sgm = g.get_grid_segments(nodeids) 41 | 42 | assert sgm.sum() == 758 43 | 44 | 45 | @pytest.mark.parametrize("type", [int, float]) 46 | def test_copy_empty(type): 47 | g = maxflow.Graph[type]() 48 | g2 = g.copy() 49 | assert g.get_node_count() == g2.get_node_count() 50 | assert g.get_edge_count() == g2.get_edge_count() 51 | 52 | 53 | @pytest.mark.parametrize("type", [int, float]) 54 | def test_copy(type): 55 | g = maxflow.Graph[type]() 56 | nodeids = g.add_grid_nodes((5, 5)) 57 | structure = np.array([[2, 1, 1, 1, 2], 58 | [1, 1, 1, 1, 1], 59 | [1, 1, 0, 1, 1], 60 | [1, 1, 1, 1, 1], 61 | [2, 1, 1, 1, 2]]) 62 | g.add_grid_edges(nodeids, 1, structure=structure, symmetric=False) 63 | g.add_grid_tedges(nodeids, structure, 2-structure) 64 | g2 = g.copy() 65 | 66 | assert g.get_node_count() == g2.get_node_count() 67 | assert g.get_edge_count() == g2.get_edge_count() 68 | 69 | nx1 = g.get_nx_graph() 70 | nx2 = g2.get_nx_graph() 71 | 72 | assert graphs_equal(nx1, nx2) 73 | 74 | g.maxflow() 75 | 76 | nx1_after_mf = g.get_nx_graph() 77 | nx2_after_mf = g2.get_nx_graph() 78 | 79 | assert not graphs_equal(nx1, nx1_after_mf) 80 | assert graphs_equal(nx1, nx2_after_mf) 81 | 82 | 83 | @pytest.mark.parametrize("type", [int, float]) 84 | def test_periodic(type): 85 | g = maxflow.Graph[type]() 86 | nodeids = g.add_grid_nodes((5, 5)) 87 | g.add_grid_edges(nodeids, 1, periodic=False) 88 | nx = g.get_nx_graph() 89 | assert (nodeids[0, 0], nodeids[0, 4]) not in nx.edges 90 | assert (nodeids[0, 0], nodeids[4, 0]) not in nx.edges 91 | assert (nodeids[4, 0], nodeids[4, 4]) not in nx.edges 92 | assert (nodeids[0, 4], nodeids[4, 4]) not in nx.edges 93 | assert (nodeids[0, 0], nodeids[4, 4]) not in nx.edges 94 | assert (nodeids[4, 0], nodeids[0, 1]) not in nx.edges 95 | 96 | g = maxflow.Graph[type]() 97 | nodeids = g.add_grid_nodes((5, 5)) 98 | g.add_grid_edges(nodeids, 1, periodic=True) 99 | nx = g.get_nx_graph() 100 | assert (nodeids[0, 0], nodeids[0, 4]) in nx.edges 101 | assert (nodeids[0, 0], nodeids[4, 0]) in nx.edges 102 | assert (nodeids[4, 0], nodeids[4, 4]) in nx.edges 103 | assert (nodeids[0, 4], nodeids[4, 4]) in nx.edges 104 | assert (nodeids[0, 0], nodeids[4, 4]) not in nx.edges 105 | assert (nodeids[4, 0], nodeids[0, 1]) not in nx.edges 106 | 107 | g = maxflow.Graph[type]() 108 | nodeids = g.add_grid_nodes((5, 5)) 109 | g.add_grid_edges(nodeids, 1, periodic=[True, False]) 110 | nx = g.get_nx_graph() 111 | assert (nodeids[0, 0], nodeids[0, 4]) not in nx.edges 112 | assert (nodeids[0, 0], nodeids[4, 0]) in nx.edges 113 | assert (nodeids[4, 0], nodeids[4, 4]) not in nx.edges 114 | assert (nodeids[0, 4], nodeids[4, 4]) in nx.edges 115 | assert (nodeids[0, 0], nodeids[4, 4]) not in nx.edges 116 | assert (nodeids[4, 0], nodeids[0, 1]) not in nx.edges 117 | 118 | g = maxflow.Graph[type]() 119 | nodeids = g.add_grid_nodes((5, 5)) 120 | structure = np.array([[0, 0, 0], 121 | [0, 0, 1], 122 | [1, 1, 1]]) 123 | g.add_grid_edges(nodeids, 1, structure=structure, symmetric=True, periodic=True) 124 | nx = g.get_nx_graph() 125 | assert (nodeids[0, 0], nodeids[0, 4]) in nx.edges 126 | assert (nodeids[0, 0], nodeids[4, 0]) in nx.edges 127 | assert (nodeids[4, 0], nodeids[4, 4]) in nx.edges 128 | assert (nodeids[0, 4], nodeids[4, 4]) in nx.edges 129 | assert (nodeids[0, 0], nodeids[4, 4]) in nx.edges 130 | assert (nodeids[4, 0], nodeids[0, 1]) in nx.edges 131 | 132 | 133 | def test_aexpansion(): 134 | 135 | unary = np.array([ 136 | [ 137 | [5.0, 10.0, 10.0], 138 | [0.0, 5.0, 10.0], 139 | [0.0, 0.0, 5.0] 140 | ], 141 | [ 142 | [4.0, 5.0, 5.0], 143 | [5.0, 4.0, 5.0], 144 | [5.0, 5.0, 4.0] 145 | ], 146 | [ 147 | [5.0, 0.0, 0.0], 148 | [10.0, 5.0, 0.0], 149 | [10.0, 10.0, 5.0] 150 | ], 151 | ]).transpose((1, 2, 0)) 152 | 153 | binary = np.array([ 154 | [0.0, 1.0, 1.0], 155 | [1.0, 0.0, 1.0], 156 | [1.0, 1.0, 0.0] 157 | ]) 158 | 159 | labels = maxflow.aexpansion_grid(unary, 0.1 * binary) 160 | result = np.array([ 161 | [1, 2, 2], 162 | [0, 1, 2], 163 | [0, 0, 1] 164 | ]) 165 | assert_array_equal(labels, result) 166 | 167 | labels = maxflow.aexpansion_grid(unary, 2 * binary) 168 | assert not np.any(labels == 1) 169 | 170 | 171 | def test_fastmin_edge_cases(): 172 | 173 | # Array with 0 spatial dimensions 174 | unary = np.zeros((0, 0, 3)) 175 | binary = np.ones((3, 3), dtype=np.float64) - np.eye(3, dtype=np.float64) 176 | labels = maxflow.aexpansion_grid(unary, binary) 177 | assert labels.shape == (0, 0) 178 | 179 | # Unary term is a scalar 180 | unary = np.zeros(()) 181 | binary = np.ones(()) 182 | with pytest.raises(ValueError): 183 | maxflow.aexpansion_grid(unary, binary) 184 | with pytest.raises(ValueError): 185 | maxflow.abswap_grid(unary, binary) 186 | 187 | # num_labels is 0 188 | unary = np.zeros((3, 3, 0)) 189 | binary = np.zeros((0, 0)) 190 | with pytest.raises(ValueError): 191 | maxflow.aexpansion_grid(unary, binary) 192 | with pytest.raises(ValueError): 193 | maxflow.abswap_grid(unary, binary) 194 | 195 | # num_labels mismatch for the unary and the binary terms 196 | unary = np.zeros((3, 3, 3)) 197 | binary = np.zeros((2, 2)) 198 | with pytest.raises(ValueError): 199 | maxflow.aexpansion_grid(unary, binary) 200 | with pytest.raises(ValueError): 201 | maxflow.abswap_grid(unary, binary) 202 | 203 | # Shape of initial labels do not match the shape of the unary array 204 | unary = np.zeros((3, 3, 3)) 205 | binary = np.zeros((3, 3)) 206 | labels = np.ones((4, 4), dtype=np.int64) 207 | with pytest.raises(Exception): 208 | maxflow.aexpansion_grid(unary, binary, labels=labels) 209 | with pytest.raises(Exception): 210 | maxflow.abswap_grid(unary, binary, labels=labels) 211 | 212 | # Initial labels contain values larger than num_labels 213 | unary = np.zeros((3, 3, 3)) 214 | binary = np.zeros((3, 3)) 215 | labels = np.full((3, 3), 5, dtype=np.int64) 216 | with pytest.raises(ValueError): 217 | maxflow.aexpansion_grid(unary, binary, labels=labels) 218 | with pytest.raises(ValueError): 219 | maxflow.abswap_grid(unary, binary, labels=labels) 220 | 221 | # Initial labels contain negative values 222 | unary = np.zeros((3, 3, 3)) 223 | binary = np.zeros((3, 3)) 224 | labels = np.full((3, 3), -1, dtype=np.int64) 225 | with pytest.raises(ValueError): 226 | maxflow.aexpansion_grid(unary, binary, labels=labels) 227 | with pytest.raises(ValueError): 228 | maxflow.abswap_grid(unary, binary, labels=labels) 229 | 230 | 231 | def test_abswap(): 232 | 233 | unary = np.array([ 234 | [ 235 | [5.0, 10.0, 10.0], 236 | [0.0, 5.0, 10.0], 237 | [0.0, 0.0, 5.0] 238 | ], 239 | [ 240 | [10.0, 5.0, 5.0], 241 | [5.0, 10.0, 5.0], 242 | [5.0, 5.0, 10.0] 243 | ], 244 | [ 245 | [5.0, 0.0, 0.0], 246 | [10.0, 5.0, 0.0], 247 | [10.0, 10.0, 5.0] 248 | ], 249 | ]).transpose((1, 2, 0)) 250 | 251 | binary = np.array([ 252 | [0.0, 1.0, 50.0], 253 | [1.0, 0.0, 1.0], 254 | [50.0, 1.0, 0.0] 255 | ]) 256 | 257 | labels = maxflow.abswap_grid(unary, binary) 258 | 259 | result = np.array([ 260 | [1, 2, 2], 261 | [0, 1, 2], 262 | [0, 0, 1] 263 | ]) 264 | 265 | assert_array_equal(labels, result) 266 | --------------------------------------------------------------------------------