├── .gitattributes ├── .gitignore ├── LICENSE.md ├── docs ├── Makefile ├── conf.py ├── index.rst ├── modules.rst └── pyransac.rst ├── examples ├── circle-image.py ├── circle-video.py ├── exponential.py ├── media │ └── HRE-video.avi └── ransac.py └── pyransac ├── __init__.py ├── features.py └── ransac.py /.gitattributes: -------------------------------------------------------------------------------- 1 | *.avi filter=lfs diff=lfs merge=lfs -text 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | video/ 2 | docs/_build/ 3 | *.pdf 4 | *.jpg 5 | *.png 6 | *.npy 7 | *.eps 8 | 9 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015, Ruben Di Battista 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 5 | 6 | 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 7 | 8 | 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 9 | 10 | 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 11 | 12 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 13 | -------------------------------------------------------------------------------- /docs/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 | SPHINXAPIDIR = .. 8 | SPHINXAPIDOC = sphinx-apidoc 9 | PAPER = 10 | BUILDDIR = ../../python-ransac-library-docs 11 | 12 | # User-friendly check for sphinx-build 13 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 14 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 15 | endif 16 | 17 | # Internal variables. 18 | PAPEROPT_a4 = -D latex_paper_size=a4 19 | PAPEROPT_letter = -D latex_paper_size=letter 20 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | # the i18n builder cannot share the environment and doctrees with the others 22 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 23 | 24 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest coverage gettext 25 | 26 | help: 27 | @echo "Please use \`make ' where is one of" 28 | @echo " html to make standalone HTML files" 29 | @echo " dirhtml to make HTML files named index.html in directories" 30 | @echo " singlehtml to make a single large HTML file" 31 | @echo " pickle to make pickle files" 32 | @echo " json to make JSON files" 33 | @echo " htmlhelp to make HTML files and a HTML help project" 34 | @echo " qthelp to make HTML files and a qthelp project" 35 | @echo " applehelp to make an Apple Help Book" 36 | @echo " devhelp to make HTML files and a Devhelp project" 37 | @echo " epub to make an epub" 38 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 39 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 40 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 41 | @echo " text to make text files" 42 | @echo " man to make manual pages" 43 | @echo " texinfo to make Texinfo files" 44 | @echo " info to make Texinfo files and run them through makeinfo" 45 | @echo " gettext to make PO message catalogs" 46 | @echo " changes to make an overview of all changed/added/deprecated items" 47 | @echo " xml to make Docutils-native XML files" 48 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 49 | @echo " linkcheck to check all external links for integrity" 50 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 51 | @echo " coverage to run coverage check of the documentation (if enabled)" 52 | 53 | clean: 54 | rm -rf $(BUILDDIR)/* 55 | 56 | html: 57 | $(SPHINXAPIDOC) $(SPHINXAPIDIR) -o . 58 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 61 | 62 | dirhtml: 63 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 64 | @echo 65 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 66 | 67 | singlehtml: 68 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 69 | @echo 70 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 71 | 72 | pickle: 73 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 74 | @echo 75 | @echo "Build finished; now you can process the pickle files." 76 | 77 | json: 78 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 79 | @echo 80 | @echo "Build finished; now you can process the JSON files." 81 | 82 | htmlhelp: 83 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 84 | @echo 85 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 86 | ".hhp project file in $(BUILDDIR)/htmlhelp." 87 | 88 | qthelp: 89 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 90 | @echo 91 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 92 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 93 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/PythonRansacLibrary.qhcp" 94 | @echo "To view the help file:" 95 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/PythonRansacLibrary.qhc" 96 | 97 | applehelp: 98 | $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp 99 | @echo 100 | @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." 101 | @echo "N.B. You won't be able to view it unless you put it in" \ 102 | "~/Library/Documentation/Help or install it in your application" \ 103 | "bundle." 104 | 105 | devhelp: 106 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 107 | @echo 108 | @echo "Build finished." 109 | @echo "To view the help file:" 110 | @echo "# mkdir -p $$HOME/.local/share/devhelp/PythonRansacLibrary" 111 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/PythonRansacLibrary" 112 | @echo "# devhelp" 113 | 114 | epub: 115 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 116 | @echo 117 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 118 | 119 | latex: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo 122 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 123 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 124 | "(use \`make latexpdf' here to do that automatically)." 125 | 126 | latexpdf: 127 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 128 | @echo "Running LaTeX files through pdflatex..." 129 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 130 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 131 | 132 | latexpdfja: 133 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 134 | @echo "Running LaTeX files through platex and dvipdfmx..." 135 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 136 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 137 | 138 | text: 139 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 140 | @echo 141 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 142 | 143 | man: 144 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 145 | @echo 146 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 147 | 148 | texinfo: 149 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 150 | @echo 151 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 152 | @echo "Run \`make' in that directory to run these through makeinfo" \ 153 | "(use \`make info' here to do that automatically)." 154 | 155 | info: 156 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 157 | @echo "Running Texinfo files through makeinfo..." 158 | make -C $(BUILDDIR)/texinfo info 159 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 160 | 161 | gettext: 162 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 163 | @echo 164 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 165 | 166 | changes: 167 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 168 | @echo 169 | @echo "The overview file is in $(BUILDDIR)/changes." 170 | 171 | linkcheck: 172 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 173 | @echo 174 | @echo "Link check complete; look for any errors in the above output " \ 175 | "or in $(BUILDDIR)/linkcheck/output.txt." 176 | 177 | doctest: 178 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 179 | @echo "Testing of doctests in the sources finished, look at the " \ 180 | "results in $(BUILDDIR)/doctest/output.txt." 181 | 182 | coverage: 183 | $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage 184 | @echo "Testing of coverage in the sources finished, look at the " \ 185 | "results in $(BUILDDIR)/coverage/python.txt." 186 | 187 | xml: 188 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 189 | @echo 190 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 191 | 192 | pseudoxml: 193 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 194 | @echo 195 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 196 | htmlp: html 197 | cd $(BUILDDIR)/html; git add . ; git commit -m "rebuilt docs"; git push origin gh-pages 198 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Python Ransac Library documentation build configuration file, created by 4 | # sphinx-quickstart on Mon Nov 30 04:32:54 2015. 5 | # 6 | # This file is execfile()d with the current directory set to its 7 | # containing dir. 8 | # 9 | # Note that not all possible configuration values are present in this 10 | # autogenerated file. 11 | # 12 | # All configuration values have a default; values that are commented out 13 | # serve to show the default. 14 | 15 | import sys 16 | import os 17 | import shlex 18 | 19 | # If extensions (or modules to document with autodoc) are in another directory, 20 | # add these directories to sys.path here. If the directory is relative to the 21 | # documentation root, use os.path.abspath to make it absolute, like shown here. 22 | sys.path.insert(0, os.path.abspath('..')) 23 | 24 | # -- General configuration ------------------------------------------------ 25 | 26 | # If your documentation needs a minimal Sphinx version, state it here. 27 | #needs_sphinx = '1.0' 28 | 29 | # Add any Sphinx extension module names here, as strings. They can be 30 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 31 | # ones. 32 | extensions = [ 33 | 'sphinx.ext.autodoc', 34 | 'sphinx.ext.mathjax', 35 | 'sphinxcontrib.napoleon' 36 | ] 37 | 38 | # Add any paths that contain templates here, relative to this directory. 39 | templates_path = ['_templates'] 40 | 41 | # The suffix(es) of source filenames. 42 | # You can specify multiple suffix as a list of string: 43 | # source_suffix = ['.rst', '.md'] 44 | source_suffix = '.rst' 45 | 46 | # The encoding of source files. 47 | #source_encoding = 'utf-8-sig' 48 | 49 | # The master toctree document. 50 | master_doc = 'index' 51 | 52 | # General information about the project. 53 | project = u'Python Ransac Library' 54 | copyright = u'2015, Ruben Di Battista' 55 | author = u'Ruben Di Battista' 56 | 57 | # The version info for the project you're documenting, acts as replacement for 58 | # |version| and |release|, also used in various other places throughout the 59 | # built documents. 60 | # 61 | # The short X.Y version. 62 | version = '0.1a' 63 | # The full version, including alpha/beta/rc tags. 64 | release = '0.1a' 65 | 66 | # The language for content autogenerated by Sphinx. Refer to documentation 67 | # for a list of supported languages. 68 | # 69 | # This is also used if you do content translation via gettext catalogs. 70 | # Usually you set "language" from the command line for these cases. 71 | language = None 72 | 73 | # There are two options for replacing |today|: either, you set today to some 74 | # non-false value, then it is used: 75 | #today = '' 76 | # Else, today_fmt is used as the format for a strftime call. 77 | #today_fmt = '%B %d, %Y' 78 | 79 | # List of patterns, relative to source directory, that match files and 80 | # directories to ignore when looking for source files. 81 | exclude_patterns = ['_build'] 82 | 83 | # The reST default role (used for this markup: `text`) to use for all 84 | # documents. 85 | #default_role = None 86 | 87 | # If true, '()' will be appended to :func: etc. cross-reference text. 88 | #add_function_parentheses = True 89 | 90 | # If true, the current module name will be prepended to all description 91 | # unit titles (such as .. function::). 92 | #add_module_names = True 93 | 94 | # If true, sectionauthor and moduleauthor directives will be shown in the 95 | # output. They are ignored by default. 96 | #show_authors = False 97 | 98 | # The name of the Pygments (syntax highlighting) style to use. 99 | pygments_style = 'sphinx' 100 | 101 | # A list of ignored prefixes for module index sorting. 102 | #modindex_common_prefix = [] 103 | 104 | # If true, keep warnings as "system message" paragraphs in the built documents. 105 | #keep_warnings = False 106 | 107 | # If true, `todo` and `todoList` produce output, else they produce nothing. 108 | todo_include_todos = False 109 | 110 | 111 | # -- Options for HTML output ---------------------------------------------- 112 | 113 | # The theme to use for HTML and HTML Help pages. See the documentation for 114 | # a list of builtin themes. 115 | html_theme = 'sphinx_rtd_theme' 116 | 117 | # Theme options are theme-specific and customize the look and feel of a theme 118 | # further. For a list of options available for each theme, see the 119 | # documentation. 120 | #html_theme_options = {} 121 | 122 | # Add any paths that contain custom themes here, relative to this directory. 123 | #html_theme_path = [] 124 | 125 | # The name for this set of Sphinx documents. If None, it defaults to 126 | # " v documentation". 127 | #html_title = None 128 | 129 | # A shorter title for the navigation bar. Default is the same as html_title. 130 | #html_short_title = None 131 | 132 | # The name of an image file (relative to this directory) to place at the top 133 | # of the sidebar. 134 | #html_logo = None 135 | 136 | # The name of an image file (within the static path) to use as favicon of the 137 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 138 | # pixels large. 139 | #html_favicon = None 140 | 141 | # Add any paths that contain custom static files (such as style sheets) here, 142 | # relative to this directory. They are copied after the builtin static files, 143 | # so a file named "default.css" will overwrite the builtin "default.css". 144 | html_static_path = ['_static'] 145 | 146 | # Add any extra paths that contain custom files (such as robots.txt or 147 | # .htaccess) here, relative to this directory. These files are copied 148 | # directly to the root of the documentation. 149 | #html_extra_path = [] 150 | 151 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 152 | # using the given strftime format. 153 | #html_last_updated_fmt = '%b %d, %Y' 154 | 155 | # If true, SmartyPants will be used to convert quotes and dashes to 156 | # typographically correct entities. 157 | #html_use_smartypants = True 158 | 159 | # Custom sidebar templates, maps document names to template names. 160 | #html_sidebars = {} 161 | 162 | # Additional templates that should be rendered to pages, maps page names to 163 | # template names. 164 | #html_additional_pages = {} 165 | 166 | # If false, no module index is generated. 167 | #html_domain_indices = True 168 | 169 | # If false, no index is generated. 170 | #html_use_index = True 171 | 172 | # If true, the index is split into individual pages for each letter. 173 | #html_split_index = False 174 | 175 | # If true, links to the reST sources are added to the pages. 176 | #html_show_sourcelink = True 177 | 178 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 179 | #html_show_sphinx = True 180 | 181 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 182 | #html_show_copyright = True 183 | 184 | # If true, an OpenSearch description file will be output, and all pages will 185 | # contain a tag referring to it. The value of this option must be the 186 | # base URL from which the finished HTML is served. 187 | #html_use_opensearch = '' 188 | 189 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 190 | #html_file_suffix = None 191 | 192 | # Language to be used for generating the HTML full-text search index. 193 | # Sphinx supports the following languages: 194 | # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' 195 | # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' 196 | #html_search_language = 'en' 197 | 198 | # A dictionary with options for the search language support, empty by default. 199 | # Now only 'ja' uses this config value 200 | #html_search_options = {'type': 'default'} 201 | 202 | # The name of a javascript file (relative to the configuration directory) that 203 | # implements a search results scorer. If empty, the default will be used. 204 | #html_search_scorer = 'scorer.js' 205 | 206 | # Output file base name for HTML help builder. 207 | htmlhelp_basename = 'PythonRansacLibrarydoc' 208 | 209 | # -- Options for LaTeX output --------------------------------------------- 210 | 211 | latex_elements = { 212 | # The paper size ('letterpaper' or 'a4paper'). 213 | #'papersize': 'letterpaper', 214 | 215 | # The font size ('10pt', '11pt' or '12pt'). 216 | #'pointsize': '10pt', 217 | 218 | # Additional stuff for the LaTeX preamble. 219 | #'preamble': '', 220 | 221 | # Latex figure (float) alignment 222 | #'figure_align': 'htbp', 223 | } 224 | 225 | # Grouping the document tree into LaTeX files. List of tuples 226 | # (source start file, target name, title, 227 | # author, documentclass [howto, manual, or own class]). 228 | latex_documents = [ 229 | (master_doc, 'PythonRansacLibrary.tex', u'Python Ransac Library Documentation', 230 | u'Ruben Di Battista', 'manual'), 231 | ] 232 | 233 | # The name of an image file (relative to this directory) to place at the top of 234 | # the title page. 235 | #latex_logo = None 236 | 237 | # For "manual" documents, if this is true, then toplevel headings are parts, 238 | # not chapters. 239 | #latex_use_parts = False 240 | 241 | # If true, show page references after internal links. 242 | #latex_show_pagerefs = False 243 | 244 | # If true, show URL addresses after external links. 245 | #latex_show_urls = False 246 | 247 | # Documents to append as an appendix to all manuals. 248 | #latex_appendices = [] 249 | 250 | # If false, no module index is generated. 251 | #latex_domain_indices = True 252 | 253 | 254 | # -- Options for manual page output --------------------------------------- 255 | 256 | # One entry per manual page. List of tuples 257 | # (source start file, name, description, authors, manual section). 258 | man_pages = [ 259 | (master_doc, 'pythonransaclibrary', u'Python Ransac Library Documentation', 260 | [author], 1) 261 | ] 262 | 263 | # If true, show URL addresses after external links. 264 | #man_show_urls = False 265 | 266 | 267 | # -- Options for Texinfo output ------------------------------------------- 268 | 269 | # Grouping the document tree into Texinfo files. List of tuples 270 | # (source start file, target name, title, author, 271 | # dir menu entry, description, category) 272 | texinfo_documents = [ 273 | (master_doc, 'PythonRansacLibrary', u'Python Ransac Library Documentation', 274 | author, 'PythonRansacLibrary', 'One line description of project.', 275 | 'Miscellaneous'), 276 | ] 277 | 278 | # Documents to append as an appendix to all manuals. 279 | #texinfo_appendices = [] 280 | 281 | # If false, no module index is generated. 282 | #texinfo_domain_indices = True 283 | 284 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 285 | #texinfo_show_urls = 'footnote' 286 | 287 | # If true, do not generate a @detailmenu in the "Top" node's menu. 288 | #texinfo_no_detailmenu = False 289 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. Python Ransac Library documentation master file, created by 2 | sphinx-quickstart on Mon Nov 30 04:32:54 2015. 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 Python Ransac Library's documentation! 7 | ================================================= 8 | 9 | Contents: 10 | 11 | .. toctree:: 12 | :maxdepth: 2 13 | 14 | 15 | 16 | Indices and tables 17 | ================== 18 | 19 | * :ref:`genindex` 20 | * :ref:`modindex` 21 | * :ref:`search` 22 | 23 | -------------------------------------------------------------------------------- /docs/modules.rst: -------------------------------------------------------------------------------- 1 | .. 2 | == 3 | 4 | .. toctree:: 5 | :maxdepth: 4 6 | 7 | pyransac 8 | -------------------------------------------------------------------------------- /docs/pyransac.rst: -------------------------------------------------------------------------------- 1 | pyransac package 2 | ================ 3 | 4 | Submodules 5 | ---------- 6 | 7 | pyransac.features module 8 | ------------------------ 9 | 10 | .. automodule:: pyransac.features 11 | :members: 12 | :undoc-members: 13 | :show-inheritance: 14 | 15 | pyransac.ransac module 16 | ---------------------- 17 | 18 | .. automodule:: pyransac.ransac 19 | :members: 20 | :undoc-members: 21 | :show-inheritance: 22 | 23 | 24 | Module contents 25 | --------------- 26 | 27 | .. automodule:: pyransac 28 | :members: 29 | :undoc-members: 30 | :show-inheritance: 31 | -------------------------------------------------------------------------------- /examples/circle-image.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | import cv2 3 | from matplotlib import pyplot as plt 4 | import numpy as n 5 | from pyransac.ransac import RansacFeature 6 | from pyransac.features import Circle 7 | 8 | # Extract a frame from the provided video 9 | video = cv2.VideoCapture('media/HRE-video.avi') 10 | video.set(cv2.CAP_PROP_POS_FRAMES,70) 11 | succ, frame = video.read() 12 | 13 | # Set Gray Color 14 | frame = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) 15 | 16 | # Init RansacFeature class for circle detection 17 | ransac_process = RansacFeature(Circle,max_it = 100, inliers_percent=0.7,dst=2,threshold=100) 18 | 19 | # Process the frame to detect the circle 20 | dc,percent = ransac_process.image_search(frame) 21 | 22 | # Super impose the detected feature on the image 23 | 24 | theta = n.linspace(-n.pi,n.pi,100) 25 | plt.imshow(frame, cmap='gray') 26 | x,y = dc.print_feature(100) 27 | 28 | # Reverted x,y because 29 | # OpenCV uses numpy.ndarray 30 | # to store images and 31 | # image[:,0] is the vertical 32 | # axis of it. 33 | # See: http://stackoverflow.com/q/30681997/1334711 34 | 35 | plt.plot(y,x,'r-',linewidth=2) 36 | plt.axis('off') 37 | plt.show() -------------------------------------------------------------------------------- /examples/circle-video.py: -------------------------------------------------------------------------------- 1 | import tra.ransac as rns 2 | import tra.features as fts 3 | import numpy as n 4 | 5 | 6 | ransac = rns.RansacFeature(fts.Circle,max_it=100,threshold=100,dst=1) 7 | circles = ransac.video_processing('../../video/14_XVID.avi',save_frames=True) 8 | 9 | circles = [[c.radius,c.xc,c.yc] for c in circles if c] 10 | 11 | n.save('data.npy',circles) -------------------------------------------------------------------------------- /examples/exponential.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import numpy as np 3 | import scipy.optimize as opt 4 | import matplotlib.pyplot as plt 5 | from pyransac import features as ffs 6 | 7 | # Generating an exponential function 8 | start = 2 9 | end = 10 10 | num_points = 11 11 | 12 | a = 1 13 | b = 1 14 | n = 3 15 | x = np.linspace(a,10,11) 16 | y = a*np.power(x,n)+b 17 | 18 | # Select three points from the mathematical 19 | # function 20 | i = [0,3,5] 21 | points = np.array([ 22 | pps for pps in zip(x[i],y[i]) 23 | ]) 24 | 25 | 26 | # Generate Exponential feature from the 27 | # three points 28 | exp = ffs.Exponential(points) 29 | 30 | # Compare parameters 31 | print(""" 32 | Manual set parameters for exponential y=ax*n + b:\n 33 | a = {0} 34 | b = {1} 35 | k = {2} 36 | 37 | Detected feature parameters: 38 | 39 | a = {3} 40 | b = {4} 41 | k = {5} 42 | """.format(a,b,n,exp.a,exp.b,exp.k) 43 | ) 44 | 45 | # Print feature 46 | xe,ye = exp.print_feature(num_points,start,end) 47 | plt.plot(x,y) 48 | plt.plot(x[i],y[i],'*') 49 | plt.plot(xe,ye,'o-') 50 | plt.show() -------------------------------------------------------------------------------- /examples/media/HRE-video.avi: -------------------------------------------------------------------------------- 1 | version https://git-lfs.github.com/spec/v1 2 | oid sha256:cfc5fd06cfc2daa644977f5c1e092b888c73dcd1257cdafe09787a29472c89dd 3 | size 10926932 4 | -------------------------------------------------------------------------------- /examples/ransac.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | import cv2 3 | from matplotlib import pyplot as plt 4 | import numpy as n 5 | from pyransac.ransac import RansacFeature 6 | from pyransac.features import Circle 7 | 8 | video = cv2.VideoCapture('media/HRE-video.avi') 9 | print video.get(cv2.CAP_PROP_FPS) 10 | video.set(cv2.CAP_PROP_POS_FRAMES,250) 11 | succ, frame = video.read() 12 | frame = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) 13 | 14 | ransac_process = RansacFeature(Circle,max_it = 1E3, inliers_percent=0.7,dst=3,threshold=100) 15 | dc,percent = ransac_process.image_search(frame) 16 | 17 | theta = n.linspace(-n.pi,n.pi,100) 18 | plt.imshow(frame, cmap='gray') 19 | #plt.plot(dc.yc + dc.radius*n.cos(theta), dc.xc + dc.radius*n.sin(theta),'r-',linewidth=2) 20 | plt.ylim([0,512]) 21 | plt.xlim([0,512]) 22 | plt.axis('off') 23 | plt.show() 24 | video.release() -------------------------------------------------------------------------------- /pyransac/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rdbisme/python-ransac-library/955eeb3a5b69a59461dcce9c667c03a7bd84af4c/pyransac/__init__.py -------------------------------------------------------------------------------- /pyransac/features.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | import abc 3 | import numpy as n 4 | import scipy.linalg as linalg 5 | import scipy.optimize as opt 6 | import scipy.spatial.distance as dist 7 | 8 | class Feature(object): 9 | ''' 10 | Abstract class that represents a feature to be used 11 | with :py:class:`pyransac.ransac.RansacFeature` 12 | ''' 13 | __metaclass__ = abc.ABCMeta 14 | 15 | @abc.abstractmethod 16 | def __init__(self): 17 | pass 18 | 19 | @abc.abstractproperty 20 | def min_points(self): 21 | '''int: Minimum number of points needed to define the feature.''' 22 | 23 | pass 24 | 25 | @abc.abstractmethod 26 | def points_distance(self,points): 27 | ''' 28 | This function implements a method to compute the distance 29 | of points from the feature. 30 | 31 | Args: 32 | points (numpy.ndarray): a numpy array of points the distance must be 33 | computed of. 34 | 35 | Returns: 36 | distances (numpy.ndarray): the computed distances of the points from the feature. 37 | ''' 38 | 39 | pass 40 | 41 | @abc.abstractmethod 42 | def print_feature(self,num_points): 43 | ''' 44 | This method returns an array of x,y coordinates for 45 | points that are in the feature. 46 | 47 | Args: 48 | num_points (numpy.ndarray): the number of points to be returned 49 | 50 | Returns: 51 | coords (numpy.ndarray): a num_points x 2 numpy array that contains 52 | the points coordinates 53 | ''' 54 | 55 | class Circle(Feature): 56 | ''' 57 | Feature class for a Circle :math:`(x-x_c)^2 + (y-y_c)^2 - r = 0` 58 | ''' 59 | 60 | min_points = 3 61 | '''int: Minimum number of points needed to define the circle (3).''' 62 | 63 | def __init__(self,points): 64 | self.radius,self.xc,self.yc = self.__gen(points) 65 | 66 | 67 | def __gen(self,points): 68 | ''' 69 | Compute the radius and the center coordinates of a 70 | circumference given three points 71 | 72 | Args: 73 | points (numpy.ndarray): a (3,2) numpy array, each row is a 2D Point. 74 | 75 | Returns: 76 | (tuple): A 3 elements tuple that contains the circumference radius 77 | and center coordinates [radius,xc,yc] 78 | 79 | Raises: 80 | RuntimeError: If the circle computation does not succeed 81 | a RuntimeError is raised. 82 | ''' 83 | 84 | # Linear system for (D,E,F) in circle 85 | # equations: D*xi + E*yi + F = -(xi**2 + yi**2) 86 | # where xi, yi are the coordinate of the i-th point. 87 | 88 | # Generating A matrix 89 | A = n.array([(x,y,1) for x,y in points]) 90 | # Generating rhs 91 | rhs = n.array([-(x**2+y**2) for x,y in points]) 92 | 93 | try: 94 | #Solving linear system 95 | D,E,F = linalg.lstsq(A,rhs)[0] 96 | except linalg.LinAlgError: 97 | raise RuntimeError('Circle calculation not successful. Please\ 98 | check the input data, probable collinear points') 99 | 100 | xc = -D/2 101 | yc = -E/2 102 | r = n.sqrt(xc**2+yc**2-F) 103 | 104 | return (r,xc,yc) 105 | 106 | def points_distance(self,points): 107 | r''' 108 | Compute the distance of the points from the feature 109 | 110 | :math:`d = \left| \sqrt{(x_i - x_c)^2 + (y_i-y_c)^2} - r \right|` 111 | 112 | Args: 113 | points (numpy.ndarray): a (3,2) numpy array, each row is a 2D Point. 114 | 115 | Returns: 116 | d (numpy.ndarray): the computed distances of the points from the feature. 117 | 118 | ''' 119 | 120 | xa = n.array([self.xc,self.yc]).reshape((1,2)) 121 | d = n.abs(dist.cdist(points,xa) - self.radius) 122 | return d 123 | 124 | 125 | def print_feature(self, num_points): 126 | ''' 127 | This method returns an array of x,y coordinates for 128 | points that are in the feature. 129 | 130 | Args: 131 | num_points (numpy.ndarray): the number of points to be returned 132 | 133 | Returns: 134 | coords (numpy.ndarray): a num_points x 2 numpy array that contains 135 | the points coordinates 136 | ''' 137 | 138 | theta = n.linspace(0,2*n.pi,num_points) 139 | x = self.xc + self.radius*n.cos(theta) 140 | y = self.yc + self.radius*n.sin(theta) 141 | 142 | return n.vstack((x,y)) 143 | 144 | class Exponential (Feature): 145 | ''' 146 | Feature Class for an exponential curve :math:`y=ax^{k} + b` 147 | ''' 148 | 149 | min_points = 3 150 | 151 | def __init__(self,points): 152 | self.a,self.k,self.b = self.__gen(points) 153 | 154 | 155 | def __gen(self,points): 156 | ''' 157 | Compute the three parameters that univocally determine the 158 | exponential curve 159 | 160 | Args: 161 | points(numpy.ndarray): a (3,2) numpy array, each row is a 2D Point. 162 | 163 | Returns: 164 | exp(numpy.ndarray): A (3,) numpy array that contains the a,n,b parameters 165 | [a,k,b] 166 | 167 | Raises: 168 | RuntimeError: If the circle computation does not succeed 169 | a RuntimeError is raised. 170 | 171 | 172 | 173 | ''' 174 | def exponential(x,points): 175 | ''' Non linear system function to use 176 | with :py:func:`scypy.optimize.root` 177 | ''' 178 | aa = x[0] 179 | nn = x[1] 180 | bb = x[2] 181 | 182 | f = n.zeros((3,)) 183 | f[0] = n.abs(aa)*n.power(points[0,0],nn)+bb - points[0,1] 184 | f[1] = n.abs(aa)*n.power(points[1,0],nn)+bb - points[1,1] 185 | f[2] = n.abs(aa)*n.power(points[2,0],nn)+bb - points[2,1] 186 | 187 | return f 188 | 189 | 190 | exp = opt.root(exponential,[1,1,1],points,method='lm')['x'] 191 | return exp 192 | 193 | 194 | def points_distance(self,points): 195 | r''' 196 | Compute the distance of the points from the feature 197 | 198 | :math:`d = \sqrt{(x_i - x_c)^2 + (y_i-y_c)^2}` 199 | 200 | Args: 201 | points (numpy.ndarray): a (3,2) numpy array, each row is a 2D Point. 202 | 203 | Returns: 204 | d (numpy.ndarray): the computed distances of the points from the feature. 205 | 206 | ''' 207 | x = points[:,0] 208 | xa = n.array([x,self.a*n.power(x,self.k)+self.b]) 209 | xa = xa.T 210 | d = dist.cdist(points,xa) 211 | return n.diag(d) 212 | 213 | def print_feature(self, num_points, a,b): 214 | ''' 215 | This method returns an array of x,y coordinates for 216 | points that are in the feature in the interval [a,b]. 217 | 218 | Args: 219 | num_points (numpy.ndarray): the number of points to be returned 220 | a (float): left end of the interval 221 | b (float): right end of the interval 222 | 223 | Returns: 224 | coords (numpy.ndarray): a num_points x 2 numpy array that contains 225 | the points coordinates 226 | ''' 227 | 228 | 229 | x = n.linspace(a,b,num_points) 230 | y = self.a*x**self.k + self.b 231 | 232 | return n.vstack((x,y)) 233 | 234 | -------------------------------------------------------------------------------- /pyransac/ransac.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | import cv2 3 | from matplotlib import pyplot as plt 4 | import numpy as n 5 | import numpy.random as rnd 6 | 7 | 8 | class RansacFeature(object): 9 | ''' 10 | Class for feature detection inside images and videos with 11 | the :abbr:`RANSAC (Random Sample Consensus)` algorithm. 12 | 13 | Attributes: 14 | feature(:py:class:`pyransac.features.Feature`): the feature class. 15 | max_it(int): Max Number of iterations for the RANSAC loop. 16 | inliers_percent(float): percentage of inliers over total points.\ 17 | Used for stop criteria in the RANSAC loop. 18 | threshold(int): Value of threshold used after the image normalization \ 19 | (can be an integer from 1 to 254). 20 | dst(float): the distance of the inliers pixels from the feature (i.e.\ 21 | a pixel is considered an inlier if its distance is < dst). 22 | ''' 23 | 24 | def __init__(self,feature,max_it=100,inliers_percent=0.6, threshold = 100, dst = 10): 25 | self.feature = feature 26 | self.max_it = max_it 27 | self.inliers_percent = inliers_percent 28 | self.threshold = threshold 29 | self.dst = dst 30 | 31 | def detect_feature(self,pixels): 32 | ''' This method look for the feature inside a set of points. 33 | 34 | Args: 35 | points(numpy.ndarray): a (n,n)-shaped numpy array of points. 36 | 37 | Returns: 38 | (list): list containing: 39 | 40 | feature(:py:attr:`pyransac.ransac.RansacFeature.feature`): The detected feature object. 41 | 42 | percent(float): The percentage of "fitness" (i.e inliers/total_points) of the feature detected \ 43 | in the image. 44 | 45 | ''' 46 | 47 | # -- Starting Loop -- # 48 | 49 | # Pre-allocating guess points 50 | pts = n.zeros((self.feature.min_points,2)) 51 | 52 | # Starting iterations 53 | it = 0 54 | 55 | # Current percent of inliers over the total points 56 | percent = 0 57 | 58 | 59 | while not(percent>self.inliers_percent or it>self.max_it): 60 | 61 | # Guess three pixels from the non-zero ones 62 | pts = pixels[rnd.randint(n.size(pixels[:,0]),size=self.feature.min_points)] 63 | 64 | 65 | 66 | # Generating Circle from the three given points 67 | try: 68 | guess_feature = self.feature(pts) 69 | except RuntimeError: # If the three points are collinear the circle cannot be computed 70 | continue 71 | # Compute distance of all non-zero points from the circumference 72 | distances = guess_feature.points_distance(pixels) 73 | 74 | # Count how many points are inliers (i.e. near the circle) 75 | inliers = n.size(n.nonzero(distances <= self.dst)[0]) 76 | 77 | #Compute the percentage 78 | percent_new = inliers/n.size(pixels) 79 | 80 | it = it+1 81 | 82 | if percent_new > percent: 83 | # Update if better approximation 84 | percent = percent_new 85 | feature = guess_feature 86 | 87 | 88 | #======================================================================= 89 | # if it >self.max_it: 90 | # warnings.warn('''Max Iterations number reached. The current percentage of fitness is {0}'''\ 91 | # .format(percent),RuntimeWarning) 92 | #=======================================================================s 93 | return (feature,percent) 94 | 95 | def image_search(self,image): 96 | ''' This method look for the feature inside a grayscale image. 97 | 98 | Args: 99 | image(numpy.ndarray): the image where to detect the circle. 100 | 101 | Returns: 102 | (list): list containing: 103 | 104 | feature (:py:class:`pyransac.ransac.RansacFeature.feature`): The detected feature object 105 | 106 | percent (float): the percentage of 'fitness' (i.e.inliers/total_points) 107 | of the detected feature 108 | 109 | Raises: 110 | ValueError: If the thresholded image is completely empty (all pixels intensities 111 | == 0, a ValueError is raised). 112 | ''' 113 | 114 | #======================================================================= 115 | # TODO: Check if the image is gray 116 | #======================================================================= 117 | 118 | 119 | # Normalization 120 | image = cv2.normalize(image,image, alpha=0,norm_type=cv2.NORM_MINMAX, beta = 255) 121 | 122 | # Thresholding 123 | _ret,image = cv2.threshold(image,self.threshold,255,cv2.THRESH_BINARY) 124 | 125 | # Only the non-zero pixels 126 | pixels = n.where(image>0) 127 | 128 | #Thresholded image can be empty 129 | if not(pixels): 130 | raise ValueError('Thresholded image is completely empty.\ 131 | The threshold argument is too high or the image\ 132 | is totally black') 133 | 134 | # Orienting correctly the points in a (n,2) shape 135 | # needed because of arguments of Circle.points_distance() 136 | pixels = n.transpose(n.vstack([pixels[0],pixels[1]])) 137 | 138 | return self.detect_feature(pixels) 139 | 140 | 141 | def video_processing(self,videofile,save_frames=False): 142 | ''' This method look for the feature inside each frame of 143 | a video. 144 | 145 | Args: 146 | videofile (str): path string of the video file. 147 | 148 | Returns: 149 | fs (numpy.ndarray): the array of features detected 150 | 151 | 152 | Raises: 153 | ValueError: If the thresholded image is completely empty (all pixels intensities 154 | == 0, a ValueError is raised). 155 | ''' 156 | video = cv2.VideoCapture(videofile) 157 | nframes = int(video.get(cv2.CAP_PROP_FRAME_COUNT)) 158 | 159 | #Pre-allocating dataset for feature array 160 | fs = n.empty(nframes,dtype=self.feature) 161 | 162 | if save_frames: 163 | theta = n.linspace(-n.pi,n.pi,100) 164 | 165 | for i in xrange(nframes): 166 | succ, frame = video.read() 167 | frame = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) 168 | 169 | if succ: # If successfully got the video frame 170 | 171 | try: 172 | feature,_percent = self.image_search(frame) 173 | fs[i] = feature 174 | 175 | if save_frames: 176 | plt.imshow(frame, cmap='gray') 177 | plt.plot(feature.yc + feature.radius*n.cos(theta), feature.xc + feature.radius*n.sin(theta),'r-',linewidth=2) 178 | plt.axis('off') 179 | plt.savefig('Frame_'+str(i)) 180 | plt.close() 181 | 182 | except ValueError: 183 | fs[i] = None 184 | 185 | else: 186 | raise RuntimeError("Error in retrieving video frames.") 187 | 188 | return fs --------------------------------------------------------------------------------