{"id":21033585,"url":"https://github.com/gabyx/approxmvbb","last_synced_at":"2025-04-05T09:06:18.595Z","repository":{"id":24393550,"uuid":"27793651","full_name":"gabyx/ApproxMVBB","owner":"gabyx","description":"Fast algorithms to compute an approximation of the minimal volume oriented bounding box of a point cloud in 3D.","archived":false,"fork":false,"pushed_at":"2021-11-18T19:23:53.000Z","size":6520,"stargazers_count":456,"open_issues_count":7,"forks_count":93,"subscribers_count":20,"default_branch":"main","last_synced_at":"2025-03-29T08:05:57.158Z","etag":null,"topics":["bounding-boxes","kd-tree","oobb","outlier-removal","point-cloud","volume"],"latest_commit_sha":null,"homepage":null,"language":"C++","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mpl-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/gabyx.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"COPYING","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null},"funding":{"github":["gabyx"]}},"created_at":"2014-12-10T00:00:00.000Z","updated_at":"2025-03-21T02:59:34.000Z","dependencies_parsed_at":"2022-07-25T10:32:11.001Z","dependency_job_id":null,"html_url":"https://github.com/gabyx/ApproxMVBB","commit_stats":null,"previous_names":[],"tags_count":27,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gabyx%2FApproxMVBB","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gabyx%2FApproxMVBB/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gabyx%2FApproxMVBB/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gabyx%2FApproxMVBB/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/gabyx","download_url":"https://codeload.github.com/gabyx/ApproxMVBB/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247312077,"owners_count":20918344,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bounding-boxes","kd-tree","oobb","outlier-removal","point-cloud","volume"],"created_at":"2024-11-19T12:58:03.842Z","updated_at":"2025-04-05T09:06:18.555Z","avatar_url":"https://github.com/gabyx.png","language":"C++","funding_links":["https://github.com/sponsors/gabyx"],"categories":[],"sub_categories":[],"readme":"# ApproxMVBB\n\n![C++](https://img.shields.io/badge/c%2B%2B-11/14-green.svg)\n![Deps](https://img.shields.io/badge/dependencies-eigen3,meta,[pugixml,python3]-blue.svg)\n![System](https://img.shields.io/badge/system-linux,osx,{windows}-lightgrey.svg)\n\n**Status**\n\n| Build                                                                                                               | UnitTests                                                                                                              |\n| ------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |\n| [![Build Status](https://travis-ci.org/gabyx/ApproxMVBB.svg?branch=master)](https://travis-ci.org/gabyx/ApproxMVBB) | [![Build Status](https://travis-ci.org/gabyx/ApproxMVBB.svg?branch=unitTests)](https://travis-ci.org/gabyx/ApproxMVBB) |\n\n[Homepage](http://gabyx.github.io/ApproxMVBB/)\n\n---\n\n## Fast algorithms to compute an approximation of the minimal volume oriented bounding box of a point cloud in 3D.\n\nComputing the minimal volume oriented bounding box for a given point cloud in 3D is a hard problem in computer science.\nExact algorithms are known and of cubic order in the number of points in 3D. A faster exact algorithm is currently not know. However, for lots of applications an approximation of the minimum volume oriented bounding box is acceptable and already accurate enough. This project was developed for research in [Granular Rigidbody Dynamics](http://gabyx.github.io/GRSFramework/).\nThis small standard compliant C++11 library can either be built into a shared object library\nor directly be included in an existing C++ project.\n\nI am not especially proud of the underlying code as it was written years ago, nevertheless consider PR for refactoring and clean ups are very welcome!\n\nThis library includes code for :\n\n- computing an approximation of an oriented minimal volume box (multithreading support: OpenMP),\n- computing the convex hull of a point cloud in 2d,\n- computing the minimal area rectangle of a 2d point cloud,\n- 2d projections of point clouds,\n- fast building a kD-Tree (n-dimensional, templated) with sophisticated splitting techniques which optimizes a\n  quality criteria during the splitting process,\n- computing the k-nearest neighbors to a given point (kNN search) via kd-Tree.\n- fast statistical outlier filtering of point clouds via (nearest neighbor search, kD-Tree).\n\n\u003cp align=\"center\"\u003e\n\u003ca href=\"https://github.com/gabyx/ApproxMVBB/wiki/images/Bunny.png\" tag=\"Bunny\"  target=\"_blank\"\u003e \u003cimg src=\"https://github.com/gabyx/ApproxMVBB/wiki/images/Bunny.png\"   height=\"300px\" border=\"10px\"/\u003e\u003c/a\u003e\n\u003ca href=\"https://github.com/gabyx/ApproxMVBB/wiki/images/Cube.png\" tag=\"Cube\"  target=\"_blank\"\u003e\u003cimg src=\"https://github.com/gabyx/ApproxMVBB/wiki/images/Cube.png\"  height=\"300px\" border=\"10px\"/\u003e\u003c/a\u003e\n\u003c/p\u003e\n\n---\n\n## Installation \u0026 Dependencies\n\nTo build the library, the tests and the example you need the build tool [cmake](http://www.cmake.org).\nThis library has these light-weight required dependencies:\n\n- [Eigen](http://eigen.tuxfamily.org) at least version 3.\n  - With homebrew or linuxbrew: `brew install eigen3`\n- [meta](https://github.com/ericniebler/meta)\n  - Install optional: Gets downloaded and used during build.\n\nand theses optional dependecies:\n\n- [pugixml](https://github.com/zeux/pugixml)\n  - With homebrew or linuxbrew: `brew install pugixml`\n  - install with `#define PUGIXML_HAS_LONG_LONG` enabled in `pugiconfig.hpp`.\n  - only needed if cmake variable `ApproxMVBB_XML_SUPPORT=ON` (default=`OFF`).\n- [python3](https://www.python.org/downloads/) only needed for visualization purposes.\n\nDownload these and install it on your system.\n\nDownload the latest ApproxMVBB code:\n\n```bash\n    git clone https://github.com/gabyx/ApproxMVBB.git ApproxMVBB\n```\n\nMake a build directory and navigate to it:\n\n```bash\n    mkdir Build\n    cd Build\n```\n\nInvoke cmake in the Build directory:\n\n```bash\n    cmake ../ApproxMVBB\n```\n\nThe cmake script tries to find [Eigen](http://eigen.tuxfamily.org),[meta](https://github.com/ericniebler/meta) and [pugixml](https://github.com/zeux/pugixml)\nIf you installed these in a system wide folder (e.g `/usr/local/`) this should succeed without any problems.\nIn the `CMakeCache.txt` file (or over the console by `-D\u003cvariable\u003e=ON`) you can specify what you want to build, the following options are availabe:\n\n- `ApproxMVBB_BUILD_LIBRARY`,\n- `ApproxMVBB_BUILD_TESTS`\n- `ApproxMVBB_BUILD_EXAMPLE`\n- `ApproxMVBB_BUILD_BENCHMARKS`\n- etc. See the marked red options after configuring in cmake-gui.\n\nTo install the library and the header files at a specific location `/usr/local/` run cmake with:\n\n```bash\n    cmake -DCMAKE_INSTALL_PREFIX=\"/usr/local/\" ../ApproxMVBB\n```\n\nFinally, build and install the project:\n\n```bash\n    make all\n    make install\n```\n\nBy default the multithreading support is enabled if OpenMP is found! (see [Multithreading Support](#multithreading-support))\nTo build in parallel use the `-jN` flag in the `make` command, where `N`denotes the number of parallel threads to use, or use the Ninja Generator which already uses maximum threads your system offers.\n\n**CMake FindScripts**\nThe installation installs also scripts `approxmvbb-config.cmake` and `approxmvbb-config-version.cmake` into the `lib/cmake` folder. To include the library in another project the only thing you need to add in your cmake script is\n\n```cmake\n    find_package(ApproxMVBB [version] [COMPONENTS [SUPPORT_KDTREE] [SUPPORT_XML] ] [Required] )\n```\n\nwhich defines the following targets if ApproxMVBB has been found successfully:\n\n```cmake\n    ApproxMVBB::Core            # Main target to link with!\n    ApproxMVBB::KdTreeSupport   # Optional target for KdTree support to link with (only available if installed with this supported!)\n    ApproxMVBB::XMLSupport      # Optional target for XML support to link with (only available if installed with this supported!)\n```\n\nThe components `SUPPORT_KDTREE` additionally loads the dependency [meta](https://github.com/ericniebler/meta) for the `KdTree.hpp` header and `SUPPORT_XML` loads [pugixml](https://github.com/zeux/pugixml) for the `KdTreeXml.hpp` header.\n\nIf you installed the library into non-system generic location you can set the cmake variable `$ApproxMVBB_DIR` before invoking the `find_library` command:\n\n```cmake\n    set(ApproxMVBB_DIR \"path/to/installation/lib/cmake\")\n    find_package(ApproxMVBB [version] [Required] )\n```\n\nSee the example `example/libraryUsage` which should be configured as a separate build, and the example `example/kdTreeFiltering` for more information on how to\nset up the dependencies!\n\n---\n\n## Supported Platforms\n\nThe code has been tested on Linux and OS X with compilers `clang` and `gcc`.\nIt should work for Windows as well, but has not been tested properly. Under Visual Studio 15 it seems to build.\n\n---\n\n## Example Usage: Approximation MVBB\n\nPlease see the `example/approxMVBB/main.cpp` in the source directory.\nGiven a point cloud with `n=10000` points sampled in the unit cube in 3D\nwe compute an approximation of the minimum volume bounding volume by the following calls:\n\n```C++\n    #include \u003ciostream\u003e\n    #include \"ApproxMVBB/ComputeApproxMVBB.hpp\"\n\n    int  main(int argc, char** argv)\n    {\n          ApproxMVBB::Matrix3Dyn points(3,10000);\n          points.setRandom();\n          ApproxMVBB::OOBB oobb = ApproxMVBB::approximateMVBB(points,0.001,500,5,0,5);\n          oobb.expandToMinExtentRelative(0.1);\n          return 0;\n    }\n```\n\nThe returned object oriented bounding box `oobb` contains the lower `oobb.m_minPoint` and upper point `oobb.m_maxPoint` expressed in the coordinate frame K of the bounding box. The bounding box also stores the rotation matrix from the world frame to the object frame K as a quaternion `oobb.m_q_KI` . The rotation matrix `R_KI` from frame I to frame K can be obtained by `oobb.m_q_KI.matrix()` (see `Eigen::Quaternion`). This rotation matrix `R_KI` corresponds to a coordinate transformation A_IK which transforms coordinates from frame K to coordinates in frame I. Thereforce, to get the lower point expressed in the coordinate frame I this yields:\n\n```C++\n    ApproxMVBB::Vector3 p = oobb.m_q_KI * oobb.m_minPoint  // A_IK * oobb.m_minPoint\n```\n\n**Degenerate OOBB:**\nThe returned bounding box might have a degenerated extent in some axis directions depending on the input points (e.g. 3 points defines a plane which is the minimal oriented bounding box with zero volume). The function `oobb.expandToMinExtentRelative(0.1);` is a post processing function to enlarge the bounding box by a certain percentage of the largest extent (if existing, otherwise a default value is used).\n\n**Points Outside of the final OOBB:**\nBecause the algorithm works internally with a sample of the point cloud, the resulting OOBB might not contain all points of the original point cloud! To compensate for this an additional loop is required:\n\n```C++\n    ApproxMVBB::Matrix33 A_KI = oobb.m_q_KI.matrix().transpose();\n    auto size = points.cols();\n    for( unsigned int i=0;  i\u003csize; ++i ) {\n        oobb.unite(A_KI*points.col(i));\n    }\n```\n\n**Function Parameters \u0026 How It Works:**\nThe most important function:\n\n```C++\n    ApproxMVBB::approximateMVBB(pts,\n                                epsilon,\n                                pointSamples,\n                                gridSize,\n                                mvbbDiamOptLoops,\n                                mvbbGridSearchOptLoops)\n```\n\ncomputes an approximation of the minimal volume bounding box in the following steps:\n\n1. **An approximation of the diameter** (direction which realizes the diameter: `z` ) of the points `pts` is computed.\n   The value `epsilon` is the absolute tolerance for\n   the approximation of the diameter and has the same units as the points `pts` (in the example 0.001 meter)\n2. The points are projected into the plane perpendicular to the direction `z`\n3. An approximation of the diameter of the projected points in 2D is computed (direction `x` )\n4. **The initial approximate bounding box** `A` is computed in the orthogonal frame `[x,y,z]`\n5. **A first optional optimization loop** is performed (parameter `mvbbDiamOptLoops` specifies how many loops)\n   by computing the minimal volume bounding box over a direction `t` where the direction `t`\n   is choosen sequentially from the current optimal bounding box solution. The algorithm starts with the directions of the box `A`. _This optimization works with all points in `pts` and might use a lot of time_\n6. **The initial bounding box** `A` is used as a tight fit around the points `pts`\n   to compute a **representative sample** `RS` of the point cloud. The value `pointSamples`\n   defines how many points are used for the exhaustive grid search procedure in the next step\n7. **An exhaustive grid search** (value `gridSize` specifies the x,y,z dimension of the grid defined by the bounding box `A`) is performed.\n   This search is a simple loop over all grid directions (see Gill Barequet, and Sariel Har-Peled [1]) to find a even smaller bounding box.\n   For each grid direction `g` the minimal bounding box of the projected points in direction `g` is computed. This consists\n   of finding the minimal rectangle (axis `u` and `v` in world frame) of the projected point cloud in the plane perpendicular to direction `g`. The minimal bounding box `G` in direction `g` can be computed from the basis `(u,v,g)` and is a candidate for the overall minimization problem.\n   Each found bounding box candidate `G` and its directions `(u,v,g)` can be used as a starting point for a **second optional optimization loop** (parameter `mvbbGridSearchOptLoops`, same algorithm as in step 5 but with less points, namely `RS` ).\n8. The final approximation for the minimal volume bounding box (minimal volume over all computed candidates) is returned. :poop:\n\n---\n\n## Example Usage: Generating a KdTree and Outlier Filtering\n\nThe library includes a fast KdTree implementation (which is not claimed to be ultimativly fast and absolutely memory efficient,\nbut was written to fulfill this aspects to a certain level, real benchmarks still need to be done, the implementation\ncan really well compete with famous implementations such as PCL(FLANN),ANN, and CGAL )\nThe KdTree splitting heuristic implements an extendable sophisticated splitting optimization\nwhich in the most elaborate, performance worst case consists of\nsearching for the best split between the splitting heuristics `MIDPOINT` , `MEDIAN` and `GEOMETRIC_MEAN`\nby evaluating a user-provided quality evaluator. The simple standard quality evaluator is the `LinearQualityEvaluator` which computes the split quality by a weighted linear combination of the quantities `splitRatio` , `pointRatio`, `minMaxExtentRatio`.\n\nOutlier filtering is done with the k-nearest neighbor search algorithm (similar to the PCL library but faster, and with user defined precision) and works roughly as the following:\nThe algorithm finds for each point `p` in the point cloud `k` nearest neighbors and averages their distance (distance functor) to the point `p`\nto obtain a mean distance `distance` for this particular point.\nAll nearest mean distances for all points give a histogram with a sample mean `mean` and sample standard deviation `stdDev`.\nAll points which have a mean nearest neighbor distance greater or equal to `mean + stdDevMult * stdDev`\nare classified as outlier points.\n\nLook at the examples in `examples/kdTreeFiltering` which produced the following pictures with the provided visualization notebook\n`examples/kdTreeFiltering/python/VisualizeKdTree.ipynb`.\n\n\u003cp align=\"center\"\u003e\n\u003ca href=\"https://github.com/gabyx/ApproxMVBB/wiki/images/BunnyKdTree1.png\" tag=\"Bunny Kd-Tree Special Split Optimization\"  target=\"_blank\"\u003e \u003cimg src=\"https://github.com/gabyx/ApproxMVBB/wiki/images/BunnyKdTree1.png\"   width=\"300px\"/\u003e\u003c/a\u003e\n\u003ca href=\"https://github.com/gabyx/ApproxMVBB/wiki/images/BunnyKdTree2.png\" tag=\"Bunny Kd-Tree, simple midpoint split\"  target=\"_blank\"\u003e\u003cimg src=\"https://github.com/gabyx/ApproxMVBB/wiki/images/BunnyKdTree1.png\"  width=\"300px\"/\u003e\u003c/a\u003e\n\u003c/p\u003e\n\n**Function Parameters \u0026 How It Works**\nTo come\n\n---\n\n## Building and Visualizing the Tests\n\nBuilding and installing the basic tests is done by:\n\n```bash\n    cd ApproxMVBB\n    git submodule init\n    git submodule update\n    cd ../Build\n    make build_and_test\n```\n\n**Note that if the tests fail, submit a new issue and report which test failed.\nThe results can still be visualized and should be correct. **\n\n**Note:**\nTo run the test in high-performance mode (needs lots of ram), which tests also points clouds of\n140 million points and some polygonal statue `lucy.txt` successfully you need\nto set the cmake variable `ApproxMVBB_TESTS_HIGH_PERFORMANCE` to `ON`\nand additionally initialize the submodule `additional` and unzip the files:\n\n```bash\n     cd ApproxMVBB\n     git submodule init\n     git submodule update\n     cd additional/tests/files; cat Lucy* | tar xz\n```\n\nand rebuild the tests. (this will copy the additional files next to the executable)\n\nExecuting the test application `cd tests; ./ApproxMVBBTests` will then run the following tests:\n\n1. Testing the ConvexHull2D for several point clouds in 2D\n2. Minimal area rectangle tests for several point clouds in 2D\n3. Testing the diameter computation and calculation of the initial bounding box `A`\n   (see [section](Function Parameters \u0026 How It Works))\n   for point clouds in 3D\n4. Testing the full optimization pipeline to generate an approximation of the minimal volume bounding box\n\nThe output can be visualized with the `ipython notebook` `/tests/python/PlotTestResults.ipynb`:\n\n```bash\n    cd Build/tests\n    ipython noteboook\n```\n\n\u003cp align=\"center\"\u003e\n\u003cimg src=\"https://github.com/gabyx/ApproxMVBB/wiki/images/ConvexHull.png\"/\u003e\n\u003c/p\u003e\n\n---\n\n## Benchmark\n\nHere are some short benchmarks (single core) from the tests folder:\n\n| Point Cloud     |    # Points | ~ CPU Time `approximateMVBB` |\n| --------------- | ----------: | ---------------------------: |\n| Standford Bunny |      35'945 |                       0.91 s |\n| Standford Lucy  |  14'027'872 |                       1.19 s |\n| Unit Cube       | 140'000'000 |                        7.0 s |\n\n`approximateMVBB` runs `approximateMVBBDiam` and performs a grid search afterwards (here 5x5x5=25 directions with 5 optimization runs for each)\nIt seems to take a long time for 140 million points. The most inefficient task is to get a good initial bounding box. This takes the most time as diameter computations are performed in 3d and then all points are projected in the found diameter direction in 3d and another diameter in the projected plane in 2d is computed. Afterwards the point cloud is sampled (not just random points, its done with a grid) and convex hull, minimal rectangle computations are performed over the grid directions. These algorithms could be made faster by exploiting the following things:\n\n- Use an axis aligned bounding box as the initial bounding box for the grid search (not implemented yet)\n- Parallelism for the projection -\u003e (CUDA, threads)\n\n---\n\n## Multithreading Support\n\nYou can build the library with OpenMP (by default enabled)\nYou can set the cmake cache variables `ApproxMVBB_OPENMP_USE_OPENMP=On` which will further enable `ApproxMVBB_OPENMP_USE_NTHREADS=On/Off`.\nThe variable `ApproxMVBB_OPENMP_USE_NTHREADS` toogles the number of threads to use.\nIf `Off`, the number of threads is determined at runtime (default).\n\nIf you use clang, make sure you have the [OpenMP enabled clang](https://clang-omp.github.io/)! GCC already supports OpenMP.\n\n---\n\n## References\n\nThe main articles this code is based on:\n\n```bibtex\n@Article{malandain2002,\nAuthor = {Gr'egoire Malandain and Jean-Daniel Boissonnat},\nJournal = {International Journal of Computational Geometry \u0026 Applications},\nMonth = {December},\nNumber = {6},\nPages = {489 - 510},\nTimestamp = {2015.09.02},\nTitle = {Computing the Diameter of a Point Set},\nVolume = {12},\nYear = {2002}}\n```\n\nand\n\n```bibtex\n@inproceedings{barequet2001,\nAuthor = {Gill Barequet and Sariel Har-peled},\nBooktitle = {In Proc. 10th ACM-SIAM Sympos. Discrete Algorithms},\nPages = {38--91},\nTimestamp = {2015.09.02},\nTitle = {Efficiently Approximating the Minimum-Volume Bounding Box of a Point Set in Three Dimensions},\nYear = {2001}}\n```\n\nOptimizations for future work:\n\n```bibtex\n@Article{chang2011,\nAcmid = {2019641},\nAddress = {New York, NY, USA},\nArticleno = {122},\nAuthor = {Chang, Chia-Tche and Gorissen, Bastien and Melchior, Samuel},\nDoi = {10.1145/2019627.2019641},\nIssn = {0730-0301},\nIssue_Date = {October 2011},\nJournal = {ACM Trans. Graph.},\nKeywords = {Computational geometry, bounding box, manifolds, optimization},\nMonth = oct,\nNumber = {5},\nNumpages = {16},\nPages = {122:1--122:16},\nPublisher = {ACM},\nTimestamp = {2015.09.03},\nTitle = {Fast Oriented Bounding Box Optimization on the Rotation Group {$SO(3,\\mathbb{R})$}},\nUrl = {http://doi.acm.org/10.1145/2019627.2019641},\nVolume = {30},\nYear = {2011},\nBdsk-Url-1 = {http://doi.acm.org/10.1145/2019627.2019641},\nBdsk-Url-2 = {http://dx.doi.org/10.1145/2019627.2019641}}\n```\n\n---\n\n## Licensing\n\nThis source code is released under MPL 2.0.\n\n---\n\n## Author and Acknowledgements\n\nApproxMVBB was written by Gabriel Nützi, with source code from [Grégoire Malandain \u0026 Jean-Daniel Boissonnat](http://www-sop.inria.fr/members/Gregoire.Malandain/diameter/)\nfor the approximation of the diameter of a point cloud.\nI was inspired by the work and algorithms of [Gill Barequet \u0026 Sariel Har-Peled](http://sarielhp.org/p/98/bbox/) for computing a minimal volume bounding box.\nAdditionally, the geometric predicates (orient2d) used in the convex hull algorithm (graham scan) have been taken from the fine work of [Jonathan Richard Shewchuk](http://www.cs.cmu.edu/~quake/robust.html).\nSpecial thanks go to my significant other which always had an ear during breakfast for this little project :kissing_heart:\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgabyx%2Fapproxmvbb","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgabyx%2Fapproxmvbb","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgabyx%2Fapproxmvbb/lists"}