├── .gitattributes
├── .gitignore
├── Dockerfile
├── LICENCE
├── README.md
├── imgs
└── 3d_interion_model.png
├── ipcp
├── cpp_modules
│ ├── efficient_ransac
│ ├── polyfit
│ ├── polyfit_ransac
│ └── src
│ │ ├── efficient_ransac
│ │ ├── CMakeLists.txt
│ │ └── efficient_ransac.cpp
│ │ ├── polyfit
│ │ ├── CMakeLists.txt
│ │ └── polyfit.cpp
│ │ └── polyfit_ransac
│ │ ├── CMakeLists.txt
│ │ └── polyfit_ransac.cpp
├── datasets
│ ├── apt_subsampled.ply
│ └── output.city.json
├── modules
│ ├── __init__.py
│ ├── floor_split.py
│ ├── mesh_stats.py
│ ├── primitive_detection.py
│ ├── room_detection.py
│ └── room_reconstruct.py
├── notebooks
│ └── Complete Pipeline.ipynb
├── preprocessors
│ ├── __intit__.py
│ ├── sor.py
│ └── spatial_subsample.py
├── script.py
└── src
│ ├── __init__.py
│ ├── interpolation.py
│ ├── pipeline.py
│ ├── region_growing.py
│ └── utils
│ ├── __init__.py
│ ├── cityjson_utils.py
│ ├── clip_utils.py
│ ├── log_utils.py
│ ├── math_utils.py
│ ├── pcd_utils.py
│ └── plot_utils.py
└── requirements.txt
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | share/python-wheels/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 | MANIFEST
28 |
29 | # PyInstaller
30 | # Usually these files are written by a python script from a template
31 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
32 | *.manifest
33 | *.spec
34 |
35 | # Installer logs
36 | pip-log.txt
37 | pip-delete-this-directory.txt
38 |
39 | # Unit test / coverage reports
40 | htmlcov/
41 | .tox/
42 | .nox/
43 | .coverage
44 | .coverage.*
45 | .cache
46 | nosetests.xml
47 | coverage.xml
48 | *.cover
49 | *.py,cover
50 | .hypothesis/
51 | .pytest_cache/
52 | cover/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | .pybuilder/
76 | target/
77 |
78 | # Jupyter Notebook
79 | .ipynb_checkpoints
80 |
81 | # IPython
82 | profile_default/
83 | ipython_config.py
84 |
85 | # pyenv
86 | # For a library or package, you might want to ignore these files since the code is
87 | # intended to run in multiple environments; otherwise, check them in:
88 | # .python-version
89 |
90 | # pipenv
91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
94 | # install all needed dependencies.
95 | #Pipfile.lock
96 |
97 | # poetry
98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99 | # This is especially recommended for binary packages to ensure reproducibility, and is more
100 | # commonly ignored for libraries.
101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102 | #poetry.lock
103 |
104 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
105 | __pypackages__/
106 |
107 | # Celery stuff
108 | celerybeat-schedule
109 | celerybeat.pid
110 |
111 | # SageMath parsed files
112 | *.sage.py
113 |
114 | # Environments
115 | .env
116 | .venv
117 | env/
118 | venv/
119 | ENV/
120 | env.bak/
121 | venv.bak/
122 |
123 | # Spyder project settings
124 | .spyderproject
125 | .spyproject
126 |
127 | # Rope project settings
128 | .ropeproject
129 |
130 | # mkdocs documentation
131 | /site
132 |
133 | # mypy
134 | .mypy_cache/
135 | .dmypy.json
136 | dmypy.json
137 |
138 | # Pyre type checker
139 | .pyre/
140 |
141 | # pytype static type analyzer
142 | .pytype/
143 |
144 | # Cython debug symbols
145 | cython_debug/
146 |
147 | # PyCharm
148 | # JetBrains specific template is maintainted in a separate JetBrains.gitignore that can
149 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
150 | # and can be added to the global gitignore or merged into this file. For a more nuclear
151 | # option (not recommended) you can uncomment the following to ignore the entire idea folder.
152 | #.idea/
153 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM ubuntu:20.04
2 |
3 | ENV DEBIAN_FRONTEND="noninteractive" TZ="Europe/Amsterdam"
4 |
5 | RUN mkdir /usr/app && cd /usr/app
6 | WORKDIR /usr/app
7 | RUN apt-get update -y && apt-get upgrade -y && apt-get install --no-install-recommends -y \
8 | glpk-utils \
9 | libglpk-dev \
10 | glpk-doc \
11 | libmpfr-dev \
12 | tzdata \
13 | build-essential \
14 | python3-dev \
15 | glpk-utils \
16 | libglpk-dev \
17 | glpk-doc \
18 | libmpfr-dev \
19 | libgl1 \
20 | libgomp1 \
21 | libusb-1.0-0 \
22 | libgl1-mesa-dev \
23 | libglib2.0-0 \
24 | python3-pip \
25 | && rm -rf /var/lib/apt/lists/*
26 |
27 | RUN python3 -m pip install --no-cache-dir --upgrade pip && \
28 | python3 -m pip install --no-cache-dir --upgrade jupyter
29 |
30 | COPY requirements.txt .
31 | RUN python3 -m pip install --no-cache-dir -r requirements.txt
32 | RUN rm requirements.txt
33 |
34 | ENTRYPOINT ["jupyter", "notebook", "--ip=0.0.0.0", "--no-browser", "--allow-root"]
--------------------------------------------------------------------------------
/LICENCE:
--------------------------------------------------------------------------------
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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # T3D PointCloud Processing
2 |
3 | This repository contains methods for the **automatic detection of rooms in interior PointClouds**. The methods can serve as inspiration, or can be applied as-is.
4 |
5 | 
6 |
7 | ---
8 |
9 | ## Project Goal
10 |
11 | The goal of this project is to automatically detect rooms in interior point clouds. One of the main challenges in working with interior 3D point cloud data is detecting walls and defining a room boundaries.
12 |
13 | This repository contains a five-staged pipeline that preprocesses, split into floors, detects rooms, reconstructs the surface, and computes volume and area
14 |
15 | For a quick dive into this repository take a look at our [Complete Pipeline](ipcp/notebooks/Complete%20Pipeline.ipynb).
16 |
17 | ---
18 |
19 | ## Folder Structure
20 |
21 | * [`ipcp`](./ipcp)
22 | * [`datasets`](./ipcp/datasets) _Example datasets of interior pointclouds_
23 | * [`notebooks`](./ipcp/notebooks) _Jupyter notebook tutorials_
24 | * [`src`](./ipcp/src) _Python source code_
25 | * [`utils`](./ipcp/src/utils) _Utility functions_
26 | * [`modules`](./ipcp/modules) _Pipeline modules_
27 | * [`cpp_modules`](./ipcp/cpp_modules) _Pipeline C++ modules_
28 | * [`preprocessors`](./ipcp/preprocessors) _Pre-processor modules_
29 |
30 | ---
31 |
32 | ## Dataset
33 |
34 | The sample pointcloud provided is a subsampled version of the "Apartment, merged & resampled" from the [Redwood Indoor Lidar-RGBD Scan Dataset](http://redwood-data.org/indoor_lidar_rgbd/download.html). When using this dataset, please cite the [original source](http://redwood-data.org/indoor_lidar_rgbd/license.html):
35 | > Jaesik Park, Qian-Yi Zhou and Vladlen Koltun, _Colored Point Cloud Registration Revisited_. ICCV, 2017.
36 |
37 | ---
38 |
39 | ## Installation
40 |
41 | There are two ways for using this repository. The easiest and recommended way is to build and use the provided docker image (see instructions below). Option 2 is to build to pipeline from scratch for OS of preference.
42 |
43 | ### Option 1: Docker-image
44 |
45 | 1. Clone this repository
46 |
47 | 2. Build docker image (the building can take a couple of minutes):
48 | ```bash
49 | docker build -f Dockerfile . -t t3d_docker:latest
50 | ```
51 |
52 | 3. Run docker container (as jupyter server on port 8888):
53 | ```bash
54 | docker run -v `pwd`/ipcp:/usr/app/ipcp -it -p 8888:8888 t3d_docker:latest
55 | ```
56 |
57 | 4. Check out the [notebooks](notebooks) in jupter on port 8888 for a demonstration.
58 |
59 | ### Option 2: Build from scratch
60 |
61 | 1. Clone this repository
62 |
63 | 2. Install [CGAL](https://doc.cgal.org/latest/Manual/installation.html) and [GLPK](https://www.gnu.org/software/glpk/#downloading) by following the instructions on their pages.
64 |
65 | 3. Build the C++ modules located in the [cpp_modules](./cpp_modules/src) folder using CMake.
66 |
67 | 4. Install the python dependencies (requires Python >=3.8):
68 | ```bash
69 | python -m pip install -r requirements.txt
70 | ```
71 |
72 | ---
73 |
74 | ## Running
75 |
76 | 1. Using the notebook [Complete Pipeline](notebooks/Complete%20Pipeline.ipynb)
77 |
78 | 2. Using command line `python script.py [-h] --in_file path [--out_folder path]`, e.g.:
79 | ```bash
80 | python script.py --in_file './datasets/apt_subsampled.ply'
81 | ```
82 |
83 | ---
84 |
85 | ## Acknowledgements
86 |
87 | This repository was created by _Falke Boskaljon_ for the City of Amsterdam.
88 |
--------------------------------------------------------------------------------
/imgs/3d_interion_model.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Amsterdam-AI-Team/Indoor-PointCloud-to-CityJSON/fefcbbc201721e34d00f9fb432671028c64c2e3f/imgs/3d_interion_model.png
--------------------------------------------------------------------------------
/ipcp/cpp_modules/efficient_ransac:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Amsterdam-AI-Team/Indoor-PointCloud-to-CityJSON/fefcbbc201721e34d00f9fb432671028c64c2e3f/ipcp/cpp_modules/efficient_ransac
--------------------------------------------------------------------------------
/ipcp/cpp_modules/polyfit:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Amsterdam-AI-Team/Indoor-PointCloud-to-CityJSON/fefcbbc201721e34d00f9fb432671028c64c2e3f/ipcp/cpp_modules/polyfit
--------------------------------------------------------------------------------
/ipcp/cpp_modules/polyfit_ransac:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Amsterdam-AI-Team/Indoor-PointCloud-to-CityJSON/fefcbbc201721e34d00f9fb432671028c64c2e3f/ipcp/cpp_modules/polyfit_ransac
--------------------------------------------------------------------------------
/ipcp/cpp_modules/src/efficient_ransac/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | # Created by the script cgal_create_CMakeLists
2 | # This is the CMake script for compiling a set of CGAL applications.
3 |
4 | project(efficient_ransac)
5 |
6 | cmake_minimum_required(VERSION 3.1...3.23)
7 |
8 | # CGAL and its components
9 | find_package(CGAL REQUIRED)
10 |
11 | # Boost and its components
12 | find_package(Boost REQUIRED)
13 |
14 | if(NOT Boost_FOUND)
15 |
16 | message(
17 | STATUS
18 | "NOTICE: This project requires the Boost library, and will not be compiled."
19 | )
20 |
21 | return()
22 |
23 | endif()
24 |
25 | # Creating entries for all C++ files with "main" routine
26 | # ##########################################################
27 |
28 | find_package(Eigen3 3.1.0) #(requires 3.1.0 or greater)
29 | include(CGAL_Eigen3_support)
30 | if(NOT TARGET CGAL::Eigen3_support)
31 | message(
32 | STATUS
33 | "NOTICE: This project requires Eigen 3.1 (or greater) and will not be compiled."
34 | )
35 | return()
36 | endif()
37 |
38 | create_single_source_cgal_program("efficient_ransac.cpp")
39 | target_link_libraries(efficient_ransac PUBLIC CGAL::Eigen3_support)
40 |
--------------------------------------------------------------------------------
/ipcp/cpp_modules/src/efficient_ransac/efficient_ransac.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | #include
6 | #include
7 | #include
8 |
9 | #include
10 |
11 | #include
12 | #include
13 | #include
14 |
15 | #define MIN_PARAMETERS 8
16 |
17 | typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;
18 | typedef Kernel::FT FT;
19 | typedef Kernel::Point_3 Point;
20 | typedef Kernel::Vector_3 Vector;
21 | // Point with normal, and plane index.
22 | typedef boost::tuple PNI;
23 | typedef std::vector Point_vector;
24 | typedef CGAL::Nth_of_tuple_property_map<0, PNI> Point_map;
25 | typedef CGAL::Nth_of_tuple_property_map<1, PNI> Normal_map;
26 | typedef CGAL::Nth_of_tuple_property_map<2, PNI> Plane_index_map;
27 |
28 | typedef CGAL::Shape_detection::Efficient_RANSAC_traits Traits;
29 | typedef CGAL::Shape_detection::Efficient_RANSAC Efficient_ransac;
30 | typedef CGAL::Shape_detection::Plane Plane;
31 | typedef CGAL::Shape_detection::Point_to_shape_index_map Point_to_shape_index_map;
32 |
33 | // Concurrency
34 | typedef CGAL::Parallel_if_available_tag Concurrency_tag;
35 |
36 | class Index_map
37 | {
38 | public:
39 | using key_type = std::size_t;
40 | using value_type = int;
41 | using reference = value_type;
42 | using category = boost::readable_property_map_tag;
43 |
44 | Index_map() { }
45 | template Index_map(const PointRange& points,
46 | const std::vector< std::vector >& regions)
47 | : m_indices(new std::vector(points.size(), -1)) {
48 | for (std::size_t i = 0; i < regions.size(); ++i)
49 | for (const std::size_t idx : regions[i])
50 | (*m_indices)[idx] = static_cast(i);
51 | }
52 |
53 | inline friend value_type get(const Index_map& index_map,
54 | const key_type key) {
55 | const auto& indices = *(index_map.m_indices);
56 | return indices[key];
57 | }
58 |
59 | private:
60 | std::shared_ptr< std::vector > m_indices;
61 | };
62 |
63 | int main(int argc, char *argv[])
64 | {
65 | if (argc < MIN_PARAMETERS)
66 | {
67 | std::cout << "no valid input found" << std::endl;
68 | return (-1);
69 | }
70 | else
71 | {
72 | std::cout << "Succes" << std::endl;
73 | }
74 | std::string input_file_name = argv[1];
75 | std::string output_file_name = argv[2];
76 | float probability = std::stof(argv[3]);
77 | float min_points = std::stof(argv[4]);
78 | float epsilon = std::stof(argv[5]);
79 | float cluster_epsilon = std::stof(argv[6]);
80 | float normal_threshold = std::stof(argv[7]);
81 |
82 | Point_vector points;
83 |
84 | // Load point set from a file.
85 | const std::string& input_file(input_file_name);
86 | std::cout << "Loading point cloud: " << input_file << "...";
87 | CGAL::Timer t;
88 | t.start();
89 |
90 | // VERSION: given normals
91 | std::ifstream input_stream(argv[1], std::ios_base::binary);
92 | if (!CGAL::IO::read_PLY(input_stream,
93 | std::back_inserter(points),
94 | CGAL::parameters::point_map(Point_map())
95 | .normal_map(Normal_map()))) {
96 | std::cerr << "Error: cannot read file " << input_file << std::endl;
97 | return EXIT_FAILURE;
98 | }
99 | else
100 | std::cout << " Done. " << points.size() << " points. Time: "
101 | << t.time() << " sec." << std::endl;
102 |
103 |
104 | // VERSION: not given normals
105 | // std::ifstream input_stream(argv[1], std::ios_base::binary);
106 | // if (!CGAL::IO::read_PLY(input_stream,
107 | // std::back_inserter(points),
108 | // // CGAL::make_ply_point_reader(Point_map())
109 | // CGAL::parameters::point_map(Point_map()))) {
110 | // std::cerr << "Error: cannot read file " << input_file << std::endl;
111 | // return EXIT_FAILURE;
112 | // }
113 | // else
114 | // std::cout << " Done. " << points.size() << " points. Time: "
115 | // << t.time() << " sec." << std::endl;
116 |
117 | // std::cerr << "Estimating normals...";
118 | // t.reset();
119 |
120 | // // Radius
121 | // CGAL::pca_estimate_normals(points,
122 | // 40, // no limit on the number of neighbors returns
123 | // CGAL::parameters::point_map(Point_map())
124 | // .normal_map(Normal_map())
125 | // .neighbor_radius(0.12));
126 |
127 | // // neighbours
128 | // // const int nb_neighbors = 16;
129 | // // CGAL::pca_estimate_normals(points,
130 | // nb_neighbors,
131 | // CGAL::parameters::point_map(Point_map())
132 | // .normal_map(Normal_map()));
133 |
134 | // std::cout << " Done. Time: " << t.time() << " sec." << std::endl;
135 |
136 | //////////////////////////////////////////////////////////////////////////
137 |
138 | // Shape detection.
139 |
140 | // Set parameters for shape detection.
141 | Efficient_ransac::Parameters parameters;
142 | parameters.probability = probability; // Probability to miss the largest primitive at each iteration.
143 | parameters.min_points = min_points; // Detect shapes with at least number points.
144 | parameters.epsilon = epsilon; // Max distance between a point and a shape.
145 | parameters.cluster_epsilon = cluster_epsilon; // Maximum distance between points to be clustered.
146 | parameters.normal_threshold = normal_threshold; // Mximum normal deviation. 0.9 < dot(surface_normal, point_normal);
147 |
148 | Efficient_ransac ransac;
149 | ransac.set_input(points);
150 | ransac.add_shape_factory();
151 |
152 | std::cout << "Extracting planes...";
153 | t.reset();
154 | ransac.detect(parameters);
155 |
156 | Efficient_ransac::Plane_range planes = ransac.planes();
157 | std::size_t num_planes = planes.size();
158 |
159 | std::cout << " Done. " << planes.size() << " planes extracted. Time: "
160 | << t.time() << " sec." << std::endl;
161 |
162 | // Print number of detected shapes and unassigned points.
163 | std::cout << ransac.shapes().end() - ransac.shapes().begin()
164 | << " detected shapes, "
165 | << ransac.number_of_unassigned_points()
166 | << " unassigned points." << std::endl;
167 |
168 | // Stores the plane index of each point as the third element of the tuple.
169 | Point_to_shape_index_map shape_index_map(points, planes);
170 | for (std::size_t i = 0; i < points.size(); ++i) {
171 | // Uses the get function from the property map that accesses the 3rd element of the tuple.
172 | int plane_index = get(shape_index_map, i);
173 | points[i].get<2>() = plane_index;
174 | }
175 |
176 | //////////////////////////////////////////////////////////////////////////
177 |
178 | // Write point set
179 | const std::string& output_file(output_file_name);
180 | std::ofstream output_stream(output_file, std::ios_base::binary);
181 | CGAL::IO::set_binary_mode(output_stream); // The PLY file will be written in the binary format
182 | if (CGAL::IO::write_PLY_with_properties(output_stream,
183 | points,
184 | CGAL::make_ply_point_writer (Point_map()),
185 | CGAL::make_ply_normal_writer (Normal_map()),
186 | // CGAL::parameters::point_map (Point_map())
187 | // .normal_map (Normal_map()),
188 | std::make_pair(Plane_index_map(), CGAL::IO::PLY_property("plane_index")))) {
189 | std::cout << " Done. Saved to " << output_file << std::endl;
190 | }
191 | else {
192 | std::cerr << " Failed saving file." << std::endl;
193 | return EXIT_FAILURE;
194 | }
195 | return EXIT_SUCCESS;
196 | }
--------------------------------------------------------------------------------
/ipcp/cpp_modules/src/polyfit/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | # Created by the script cgal_create_CMakeLists
2 | # This is the CMake script for compiling a set of CGAL applications.
3 |
4 | project(polyfit)
5 |
6 | cmake_minimum_required(VERSION 3.1...3.23)
7 |
8 | # CGAL and its components
9 | find_package(CGAL REQUIRED)
10 |
11 | # Boost and its components
12 | find_package(Boost REQUIRED)
13 |
14 | if(NOT Boost_FOUND)
15 |
16 | message(
17 | STATUS
18 | "NOTICE: This project requires the Boost library, and will not be compiled."
19 | )
20 |
21 | return()
22 |
23 | endif()
24 |
25 | # Creating entries for all C++ files with "main" routine
26 | # ##########################################################
27 |
28 | find_package(Eigen3 3.1.0) #(requires 3.1.0 or greater)
29 | include(CGAL_Eigen3_support)
30 | if(NOT TARGET CGAL::Eigen3_support)
31 | message(
32 | STATUS
33 | "NOTICE: This project requires Eigen 3.1 (or greater) and will not be compiled."
34 | )
35 | return()
36 | endif()
37 |
38 | find_package(GLPK QUIET)
39 | include(CGAL_GLPK_support)
40 | if(NOT TARGET CGAL::GLPK_support)
41 | message(
42 | STATUS
43 | "NOTICE: This project requires either GLPK, and will not be compiled."
44 | )
45 | return()
46 | endif()
47 |
48 | create_single_source_cgal_program("polyfit.cpp")
49 | target_link_libraries(polyfit PUBLIC CGAL::Eigen3_support)
50 | target_link_libraries(polyfit PUBLIC CGAL::GLPK_support)
--------------------------------------------------------------------------------
/ipcp/cpp_modules/src/polyfit/polyfit.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 |
7 | #ifdef CGAL_USE_SCIP // defined (or not) by CMake scripts, do not define by hand
8 | #include
9 | typedef CGAL::SCIP_mixed_integer_program_traits MIP_Solver;
10 | #elif defined(CGAL_USE_GLPK) // defined (or not) by CMake scripts, do not define by hand
11 | #include
12 | typedef CGAL::GLPK_mixed_integer_program_traits MIP_Solver;
13 | #endif
14 |
15 | #if defined(CGAL_USE_GLPK) || defined(CGAL_USE_SCIP)
16 |
17 | #include
18 |
19 | #include
20 |
21 | #define MIN_PARAMETERS 6
22 |
23 | typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;
24 | typedef Kernel::Point_3 Point;
25 | typedef Kernel::Vector_3 Vector;
26 | typedef CGAL::Polygonal_surface_reconstruction Polygonal_surface_reconstruction;
27 | typedef CGAL::Surface_mesh Surface_mesh;
28 |
29 | // Point with normal, and plane index
30 | typedef boost::tuple PNI;
31 | typedef CGAL::Nth_of_tuple_property_map<0, PNI> Point_map;
32 | typedef CGAL::Nth_of_tuple_property_map<1, PNI> Normal_map;
33 | typedef CGAL::Nth_of_tuple_property_map<2, PNI> Plane_index_map;
34 |
35 | /*
36 | * The following example shows the reconstruction using user-provided
37 | * planar segments stored in PLY format. In the PLY format, a property
38 | * named "segment_index" stores the plane index for each point (-1 if
39 | * the point is not assigned to a plane).
40 | */
41 |
42 | int main(int argc, char *argv[])
43 | {
44 |
45 | if (argc < MIN_PARAMETERS)
46 | {
47 | std::cout << "no valid input found" << std::endl;
48 | return (-1);
49 | }
50 | else
51 | {
52 | std::cout << "Succes" << std::endl;
53 | }
54 | std::string input_file_name = argv[1];
55 | std::string output_path = argv[2];
56 | float fitting = std::stof(argv[3]);
57 | float coverage = std::stof(argv[4]);
58 | float complexity = std::stof(argv[5]);
59 | if ((fitting + coverage + complexity) > 1.0f) {
60 | std::cout << fitting << " " << coverage << " " << complexity << std::endl;
61 | std::cerr << "Parameters sum to greater than 1" << std::endl;
62 | return EXIT_FAILURE;
63 | };
64 |
65 | const std::string& input_file(input_file_name);
66 | std::ifstream input_stream(input_file.c_str(), std::ios::binary);
67 |
68 | std::vector points; // store points
69 |
70 | std::cout << "Loading point cloud: " << input_file << "...";
71 | CGAL::Timer t;
72 | t.start();
73 |
74 | if (!CGAL::IO::read_PLY_with_properties(input_stream,
75 | std::back_inserter(points),
76 | CGAL::make_ply_point_reader(Point_map()),
77 | CGAL::make_ply_normal_reader(Normal_map()),
78 | std::make_pair(Plane_index_map(), CGAL::PLY_property("segment_index"))))
79 | {
80 | std::cerr << "Error: cannot read file " << input_file << std::endl;
81 | return EXIT_FAILURE;
82 | }
83 | else
84 | std::cout << " Done. " << points.size() << " points. Time: " << t.time() << " sec." << std::endl;
85 |
86 | //////////////////////////////////////////////////////////////////////////
87 |
88 | t.reset();
89 |
90 | Polygonal_surface_reconstruction algo(
91 | points,
92 | Point_map(),
93 | Normal_map(),
94 | Plane_index_map()
95 | );
96 |
97 | std::cout << " Done. Time: " << t.time() << " sec." << std::endl;
98 |
99 | //////////////////////////////////////////////////////////////////////////
100 |
101 | Surface_mesh model;
102 |
103 | std::cout << "Reconstructing...";
104 | t.reset();
105 |
106 | if (!algo.reconstruct(model, fitting, coverage, complexity)) {
107 | std::cerr << " Failed: " << algo.error_message() << std::endl;
108 | return EXIT_FAILURE;
109 | }
110 |
111 | if (model.is_empty()) {
112 | std::cerr << " Failed: no vertices" << std::endl;
113 | return EXIT_FAILURE;
114 | }
115 |
116 | // Saves the mesh model
117 | const std::string& output_file(output_path + "/polyfit_result.obj");
118 | std::ofstream output_stream(output_file.c_str());
119 | if (output_stream && CGAL::IO::write_OBJ(output_stream, model))
120 | std::cout << " Done. Saved to " << output_file << ". Time: " << t.time() << " sec." << std::endl;
121 | else {
122 | std::cerr << " Failed saving file." << std::endl;
123 | return EXIT_FAILURE;
124 | }
125 |
126 | return EXIT_SUCCESS;
127 | }
128 |
129 | #else
130 |
131 | int main(int, char**)
132 | {
133 | std::cerr << "This test requires either GLPK or SCIP.\n";
134 | return EXIT_SUCCESS;
135 | }
136 |
137 | #endif // defined(CGAL_USE_GLPK) || defined(CGAL_USE_SCIP)
--------------------------------------------------------------------------------
/ipcp/cpp_modules/src/polyfit_ransac/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | # Created by the script cgal_create_CMakeLists
2 | # This is the CMake script for compiling a set of CGAL applications.
3 |
4 | project(polyfit_ransac)
5 |
6 | cmake_minimum_required(VERSION 3.1...3.23)
7 |
8 | # CGAL and its components
9 | find_package(CGAL REQUIRED)
10 |
11 | # Boost and its components
12 | find_package(Boost REQUIRED)
13 |
14 | if(NOT Boost_FOUND)
15 |
16 | message(
17 | STATUS
18 | "NOTICE: This project requires the Boost library, and will not be compiled."
19 | )
20 |
21 | return()
22 |
23 | endif()
24 |
25 | # Creating entries for all C++ files with "main" routine
26 | # ##########################################################
27 |
28 | find_package(Eigen3 3.1.0) #(requires 3.1.0 or greater)
29 | include(CGAL_Eigen3_support)
30 | if(NOT TARGET CGAL::Eigen3_support)
31 | message(
32 | STATUS
33 | "NOTICE: This project requires Eigen 3.1 (or greater) and will not be compiled."
34 | )
35 | return()
36 | endif()
37 |
38 | find_package(GLPK QUIET)
39 | include(CGAL_GLPK_support)
40 | if(NOT TARGET CGAL::GLPK_support)
41 | message(
42 | STATUS
43 | "NOTICE: This project requires either GLPK, and will not be compiled."
44 | )
45 | return()
46 | endif()
47 |
48 | create_single_source_cgal_program("polyfit_ransac.cpp")
49 | target_link_libraries(polyfit_ransac PUBLIC CGAL::Eigen3_support)
50 | target_link_libraries(polyfit_ransac PUBLIC CGAL::GLPK_support)
--------------------------------------------------------------------------------
/ipcp/cpp_modules/src/polyfit_ransac/polyfit_ransac.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | #include
6 | #include
7 | #include
8 |
9 | #include
10 | #include
11 | #include
12 |
13 | #include
14 | #include
15 | #include
16 |
17 | #ifdef CGAL_USE_SCIP // defined (or not) by CMake scripts, do not define by hand
18 | #include
19 | typedef CGAL::SCIP_mixed_integer_program_traits MIP_Solver;
20 | #elif defined(CGAL_USE_GLPK) // defined (or not) by CMake scripts, do not define by hand
21 | #include
22 | typedef CGAL::GLPK_mixed_integer_program_traits MIP_Solver;
23 | #endif
24 |
25 | #if defined(CGAL_USE_GLPK) || defined(CGAL_USE_SCIP)
26 |
27 | #define MIN_PARAMETERS 11
28 |
29 | typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;
30 | typedef Kernel::FT FT;
31 | typedef Kernel::Point_3 Point;
32 | typedef Kernel::Vector_3 Vector;
33 | // Point with normal, and plane index
34 | typedef boost::tuple PNI;
35 | typedef std::vector Point_vector;
36 | typedef CGAL::Nth_of_tuple_property_map<0, PNI> Point_map;
37 | typedef CGAL::Nth_of_tuple_property_map<1, PNI> Normal_map;
38 | typedef CGAL::Nth_of_tuple_property_map<2, PNI> Plane_index_map;
39 | typedef CGAL::Polygonal_surface_reconstruction Polygonal_surface_reconstruction;
40 | typedef CGAL::Surface_mesh Surface_mesh;
41 | typedef CGAL::Shape_detection::Efficient_RANSAC_traits Traits;
42 | typedef CGAL::Shape_detection::Efficient_RANSAC Efficient_ransac;
43 | typedef CGAL::Shape_detection::Plane Plane;
44 | typedef CGAL::Shape_detection::Point_to_shape_index_map Point_to_shape_index_map;
45 |
46 | // Concurrency
47 | typedef CGAL::Parallel_if_available_tag Concurrency_tag;
48 |
49 | class Index_map
50 | {
51 | public:
52 | using key_type = std::size_t;
53 | using value_type = int;
54 | using reference = value_type;
55 | using category = boost::readable_property_map_tag;
56 |
57 | Index_map() { }
58 | template Index_map(const PointRange& points,
59 | const std::vector< std::vector >& regions)
60 | : m_indices(new std::vector(points.size(), -1)) {
61 | for (std::size_t i = 0; i < regions.size(); ++i)
62 | for (const std::size_t idx : regions[i])
63 | (*m_indices)[idx] = static_cast(i);
64 | }
65 |
66 | inline friend value_type get(const Index_map& index_map,
67 | const key_type key) {
68 | const auto& indices = *(index_map.m_indices);
69 | return indices[key];
70 | }
71 |
72 | private:
73 | std::shared_ptr< std::vector > m_indices;
74 | };
75 |
76 | /*
77 | * The following example shows the reconstruction using user-provided
78 | * planar segments stored in PLY format. In the PLY format, a property
79 | * named "segment_index" stores the plane index for each point (-1 if
80 | * the point is not assigned to a plane).
81 | */
82 |
83 | int main(int argc, char *argv[])
84 | {
85 |
86 | if (argc < MIN_PARAMETERS)
87 | {
88 | std::cout << "no valid input found" << std::endl;
89 | return (-1);
90 | }
91 | else
92 | {
93 | std::cout << "Succes" << std::endl;
94 | }
95 | std::string input_file_name = argv[1];
96 | std::string output_path = argv[2];
97 | float probability = std::stof(argv[3]);
98 | float min_points = std::stof(argv[4]);
99 | float epsilon = std::stof(argv[5]);
100 | float cluster_epsilon = std::stof(argv[6]);
101 | float normal_threshold = std::stof(argv[7]);
102 | float fitting = std::stof(argv[8]);
103 | float coverage = std::stof(argv[9]);
104 | float complexity = std::stof(argv[10]);
105 |
106 | if ((fitting + coverage + complexity) > 1.0f) {
107 | std::cout << fitting << " " << coverage << " " << complexity << std::endl;
108 | std::cerr << "Parameters sum to greater than 1" << std::endl;
109 | return EXIT_FAILURE;
110 | };
111 |
112 | Point_vector points;
113 |
114 | // Load point set from a file.
115 | const std::string& input_file(input_file_name);
116 | std::ifstream input_stream(input_file.c_str(), std::ios::binary);
117 | std::cout << "Loading point cloud: " << input_file << "...";
118 | CGAL::Timer t;
119 | t.start();
120 |
121 | if (!CGAL::IO::read_PLY(input_stream,
122 | std::back_inserter(points),
123 | CGAL::parameters::point_map(Point_map()))) {
124 | std::cerr << "Error: cannot read file " << input_file << std::endl;
125 | return EXIT_FAILURE;
126 | }
127 | else
128 | std::cout << " Done. " << points.size() << " points. Time: "
129 | << t.time() << " sec." << std::endl;
130 |
131 | std::cout << "Estimating normals...";
132 | t.reset();
133 |
134 | // // Radius
135 | // CGAL::pca_estimate_normals(points,
136 | // 16, // limit on the number of neighbors
137 | // CGAL::parameters::point_map(Point_map())
138 | // .normal_map(Normal_map())
139 | // .neighbor_radius(0.10));
140 |
141 | // Radius
142 | CGAL::pca_estimate_normals(points,
143 | 16, // limit on the number of neighbors
144 | CGAL::parameters::point_map(Point_map())
145 | .normal_map(Normal_map()));
146 |
147 | std::cout << " Done. Time: " << t.time() << " sec." << std::endl;
148 |
149 | //////////////////////////////////////////////////////////////////////////
150 |
151 | // Shape detection.
152 |
153 | // Set parameters for shape detection.
154 | Efficient_ransac::Parameters parameters;
155 | parameters.probability = probability; // Probability to miss the largest primitive at each iteration.
156 | parameters.min_points = min_points; // Detect shapes with at least number points.
157 | parameters.epsilon = epsilon; // Max distance between a point and a shape.
158 | parameters.cluster_epsilon = cluster_epsilon; // Maximum distance between points to be clustered.
159 | parameters.normal_threshold = normal_threshold; // Mximum normal deviation. 0.9 < dot(surface_normal, point_normal);
160 |
161 | Efficient_ransac ransac;
162 | ransac.set_input(points);
163 | ransac.add_shape_factory();
164 |
165 | std::cout << "Extracting planes...";
166 | t.reset();
167 | ransac.detect(parameters);
168 |
169 | Efficient_ransac::Plane_range planes = ransac.planes();
170 | std::size_t num_planes = planes.size();
171 |
172 | std::cout << " Done. " << planes.size() << " planes extracted. Time: "
173 | << t.time() << " sec." << std::endl;
174 |
175 | // Print number of detected shapes and unassigned points.
176 | std::cout << ransac.shapes().end() - ransac.shapes().begin()
177 | << " detected shapes, "
178 | << ransac.number_of_unassigned_points()
179 | << " unassigned points." << std::endl;
180 |
181 | // Stores the plane index of each point as the third element of the tuple.
182 | Point_to_shape_index_map shape_index_map(points, planes);
183 | for (std::size_t i = 0; i < points.size(); ++i) {
184 | // Uses the get function from the property map that accesses the 3rd element of the tuple.
185 | int plane_index = get(shape_index_map, i);
186 | points[i].get<2>() = plane_index;
187 | }
188 |
189 | //////////////////////////////////////////////////////////////////////////
190 |
191 | // Write point set
192 | const std::string& output_file_ply(output_path + "/ransac_result.ply");
193 | std::ofstream output_stream_ply(output_file_ply.c_str(), std::ios_base::binary);
194 | CGAL::IO::set_binary_mode(output_stream_ply); // The PLY file will be written in the binary format
195 | if (CGAL::IO::write_PLY_with_properties(output_stream_ply,
196 | points,
197 | CGAL::make_ply_point_writer (Point_map()),
198 | CGAL::make_ply_normal_writer (Normal_map()),
199 | std::make_pair(Plane_index_map(), CGAL::IO::PLY_property("plane_index")))) {
200 | std::cout << " Done. Saved to " << output_file_ply << std::endl;
201 | }
202 | else {
203 | std::cerr << " Failed saving file." << std::endl;
204 | return EXIT_FAILURE;
205 | }
206 |
207 | //////////////////////////////////////////////////////////////////////////
208 |
209 | // Polygonal Surface Reconstruction
210 |
211 | Polygonal_surface_reconstruction algo(
212 | points,
213 | Point_map(),
214 | Normal_map(),
215 | Plane_index_map()
216 | );
217 |
218 | Surface_mesh model;
219 |
220 | std::cout << "Polyfit...";
221 | t.reset();
222 |
223 | if (!algo.reconstruct(model, fitting, coverage, complexity)) {
224 | std::cerr << " Failed: " << algo.error_message() << std::endl;
225 | return EXIT_FAILURE;
226 | }
227 |
228 | std::cout << " Done. Time: " << t.time() << " sec." << std::endl;
229 |
230 | if (model.is_empty()) {
231 | std::cerr << " Failed: no vertices" << std::endl;
232 | return EXIT_FAILURE;
233 | }
234 |
235 | // Saves the mesh model
236 | const std::string& output_file_mesh(output_path + "/polyfit_result.obj");
237 | std::ofstream output_stream_mesh(output_file_mesh.c_str());
238 | if (output_stream_mesh && CGAL::IO::write_OBJ(output_stream_mesh, model))
239 | std::cout << " Done. Saved to " << output_file_mesh << ". Time: " << t.time() << " sec." << std::endl;
240 | else {
241 | std::cerr << " Failed saving file." << std::endl;
242 | return EXIT_FAILURE;
243 | }
244 |
245 | return EXIT_SUCCESS;
246 | }
247 |
248 | #else
249 |
250 | int main(int, char**)
251 | {
252 | std::cerr << "This test requires either GLPK or SCIP.\n";
253 | return EXIT_SUCCESS;
254 | }
255 |
256 | #endif // defined(CGAL_USE_GLPK) || defined(CGAL_USE_SCIP)
--------------------------------------------------------------------------------
/ipcp/datasets/apt_subsampled.ply:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Amsterdam-AI-Team/Indoor-PointCloud-to-CityJSON/fefcbbc201721e34d00f9fb432671028c64c2e3f/ipcp/datasets/apt_subsampled.ply
--------------------------------------------------------------------------------
/ipcp/datasets/output.city.json:
--------------------------------------------------------------------------------
1 | {"type": "CityJSON", "version": "1.0", "CityObjects": {"id-1": {"type": "Building", "geometry": []}, "room_0": {"type": "BuildingPart", "parents": ["id-1"], "geometry": [{"type": "Solid", "lod": 2, "boundaries": [[[[17, 16, 13]], [[13, 16, 14]], [[21, 36, 20]], [[36, 19, 20]], [[5, 37, 38]], [[37, 5, 6]], [[2, 8, 10]], [[8, 2, 7]], [[6, 5, 3]], [[6, 3, 0]], [[0, 7, 6]], [[0, 4, 7]], [[8, 1, 11]], [[8, 9, 1]], [[12, 10, 11]], [[8, 11, 10]], [[9, 8, 7]], [[9, 7, 4]], [[34, 35, 31]], [[34, 31, 23]], [[16, 17, 2]], [[2, 17, 7]], [[16, 18, 14]], [[14, 18, 15]], [[1, 9, 20]], [[21, 20, 9]], [[21, 9, 4]], [[26, 24, 36]], [[36, 24, 19]], [[28, 27, 26]], [[26, 27, 24]], [[24, 27, 25]], [[27, 28, 22]], [[5, 30, 3]], [[3, 30, 29]], [[10, 12, 41]], [[41, 42, 25]], [[25, 42, 24]], [[45, 30, 35]], [[35, 30, 31]], [[44, 0, 32]], [[3, 32, 0]], [[32, 3, 29]], [[13, 37, 17]], [[18, 33, 15]], [[2, 35, 34]], [[35, 2, 22]], [[40, 16, 2]], [[40, 2, 34]], [[16, 33, 18]], [[16, 40, 33]], [[46, 28, 26]], [[4, 44, 21]], [[4, 0, 44]], [[30, 5, 31]], [[31, 5, 23]], [[47, 32, 45]], [[45, 32, 30]], [[30, 32, 29]], [[38, 37, 39]], [[39, 37, 40]], [[47, 46, 43]], [[43, 46, 36]], [[36, 46, 26]], [[40, 37, 13]], [[14, 40, 13]], [[34, 39, 40]], [[34, 23, 39]], [[38, 39, 5]], [[5, 39, 23]], [[41, 12, 42]], [[11, 42, 12]], [[41, 27, 22]], [[41, 22, 2]], [[41, 2, 10]], [[6, 17, 37]], [[6, 7, 17]], [[11, 20, 42]], [[20, 11, 1]], [[15, 33, 40]], [[40, 14, 15]], [[44, 32, 43]], [[28, 46, 22]], [[22, 46, 35]], [[35, 46, 45]], [[43, 21, 44]], [[36, 21, 43]], [[42, 20, 24]], [[24, 20, 19]], [[32, 47, 43]], [[46, 47, 45]], [[41, 25, 27]]]]}]}, "room_1": {"type": "BuildingPart", "parents": ["id-1"], "geometry": [{"type": "Solid", "lod": 2, "boundaries": [[[[69, 70, 52]], [[69, 52, 56]], [[116, 114, 97]], [[97, 114, 98]], [[143, 146, 145]], [[145, 144, 143]], [[84, 85, 71]], [[84, 71, 72]], [[56, 52, 54]], [[56, 54, 49]], [[63, 64, 57]], [[63, 57, 58]], [[79, 80, 73]], [[79, 73, 78]], [[76, 77, 61]], [[76, 61, 67]], [[71, 81, 67]], [[71, 67, 63]], [[64, 63, 67]], [[64, 67, 61]], [[73, 68, 55]], [[73, 55, 75]], [[66, 75, 55]], [[66, 55, 48]], [[78, 76, 67]], [[78, 67, 81]], [[80, 86, 68]], [[80, 68, 73]], [[50, 87, 70]], [[50, 70, 69]], [[72, 71, 63]], [[72, 63, 58]], [[85, 82, 81]], [[85, 81, 71]], [[79, 82, 62]], [[79, 62, 74]], [[76, 78, 73]], [[76, 73, 75]], [[77, 76, 75]], [[77, 75, 66]], [[80, 79, 74]], [[80, 74, 60]], [[82, 79, 78]], [[82, 78, 81]], [[85, 84, 59]], [[85, 59, 53]], [[86, 80, 60]], [[86, 60, 65]], [[87, 50, 83]], [[87, 83, 51]], [[82, 85, 53]], [[82, 53, 62]], [[102, 105, 93]], [[105, 108, 93]], [[103, 94, 104]], [[94, 103, 95]], [[92, 117, 115]], [[115, 99, 92]], [[108, 109, 90]], [[90, 96, 108]], [[99, 107, 106]], [[106, 105, 99]], [[93, 108, 96]], [[89, 93, 96]], [[112, 98, 114]], [[112, 101, 98]], [[99, 105, 102]], [[92, 99, 102]], [[103, 104, 91]], [[104, 113, 91]], [[94, 109, 106]], [[104, 94, 106]], [[106, 107, 104]], [[104, 107, 113]], [[109, 105, 106]], [[108, 105, 109]], [[90, 109, 110]], [[110, 109, 94]], [[99, 115, 112]], [[112, 107, 99]], [[114, 107, 112]], [[113, 107, 114]], [[112, 115, 101]], [[115, 111, 101]], [[113, 114, 116]], [[91, 113, 116]], [[115, 117, 111]], [[111, 117, 100]], [[187, 90, 110]], [[187, 110, 124]], [[98, 101, 150]], [[150, 188, 98]], [[153, 163, 133]], [[133, 163, 137]], [[154, 155, 130]], [[154, 130, 139]], [[169, 147, 159]], [[161, 160, 131]], [[160, 127, 131]], [[164, 84, 72]], [[164, 72, 189]], [[55, 157, 121]], [[55, 121, 48]], [[52, 153, 133]], [[52, 133, 54]], [[158, 56, 128]], [[49, 128, 56]], [[133, 128, 49]], [[133, 49, 54]], [[135, 88, 83]], [[88, 51, 83]], [[189, 163, 190]], [[156, 163, 189]], [[116, 197, 165]], [[116, 165, 91]], [[198, 117, 166]], [[92, 166, 117]], [[132, 141, 142]], [[142, 126, 132]], [[127, 143, 144]], [[131, 127, 144]], [[145, 146, 141]], [[141, 146, 142]], [[221, 222, 187]], [[221, 187, 220]], [[194, 170, 171]], [[167, 161, 123]], [[161, 131, 123]], [[140, 145, 162]], [[145, 140, 150]], [[200, 202, 118]], [[200, 118, 199]], [[204, 210, 206]], [[204, 168, 210]], [[168, 204, 203]], [[152, 94, 95]], [[152, 95, 118]], [[188, 97, 98]], [[97, 188, 119]], [[192, 190, 153]], [[153, 190, 163]], [[140, 162, 155]], [[140, 155, 154]], [[156, 58, 57]], [[156, 57, 122]], [[68, 223, 157]], [[68, 157, 55]], [[70, 192, 153]], [[70, 153, 52]], [[158, 225, 69]], [[56, 158, 69]], [[191, 120, 121]], [[191, 121, 157]], [[159, 170, 128]], [[128, 170, 158]], [[169, 172, 130]], [[173, 129, 161]], [[161, 129, 160]], [[221, 224, 125]], [[221, 125, 136]], [[195, 194, 196]], [[172, 174, 139]], [[172, 139, 130]], [[167, 175, 173]], [[161, 167, 173]], [[208, 209, 201]], [[208, 201, 207]], [[125, 213, 211]], [[211, 136, 125]], [[210, 136, 211]], [[120, 191, 124]], [[120, 124, 151]], [[130, 155, 141]], [[130, 141, 132]], [[147, 171, 159]], [[159, 171, 170]], [[139, 188, 154]], [[188, 139, 119]], [[64, 180, 122]], [[64, 122, 57]], [[134, 183, 53]], [[53, 59, 134]], [[199, 103, 91]], [[199, 91, 165]], [[102, 203, 92]], [[92, 203, 166]], [[197, 215, 165]], [[166, 217, 198]], [[122, 163, 156]], [[137, 163, 122]], [[174, 176, 214]], [[174, 214, 139]], [[216, 177, 175]], [[167, 216, 175]], [[94, 152, 110]], [[152, 124, 110]], [[202, 209, 120]], [[202, 120, 151]], [[202, 151, 118]], [[168, 136, 210]], [[168, 148, 136]], [[179, 181, 207]], [[179, 207, 201]], [[179, 201, 178]], [[205, 206, 211]], [[211, 182, 205]], [[182, 211, 184]], [[211, 212, 184]], [[77, 218, 185]], [[77, 185, 61]], [[74, 186, 219]], [[62, 186, 74]], [[152, 118, 124]], [[151, 124, 118]], [[168, 93, 148]], [[93, 89, 148]], [[200, 215, 214]], [[200, 214, 178]], [[217, 204, 216]], [[216, 204, 205]], [[185, 181, 180]], [[185, 180, 64]], [[185, 64, 61]], [[183, 184, 186]], [[186, 53, 183]], [[53, 186, 62]], [[103, 199, 118]], [[103, 118, 95]], [[102, 168, 203]], [[168, 102, 93]], [[179, 176, 122]], [[179, 122, 180]], [[182, 134, 177]], [[182, 183, 134]], [[147, 169, 130]], [[147, 130, 132]], [[147, 132, 126]], [[146, 196, 142]], [[196, 171, 142]], [[196, 194, 171]], [[172, 169, 159]], [[172, 159, 128]], [[172, 128, 133]], [[173, 135, 129]], [[135, 173, 88]], [[226, 195, 227]], [[225, 195, 226]], [[174, 172, 133]], [[174, 133, 137]], [[173, 175, 88]], [[175, 138, 88]], [[142, 171, 147]], [[126, 142, 147]], [[176, 174, 137]], [[176, 137, 122]], [[175, 177, 138]], [[138, 177, 134]], [[181, 179, 180]], [[183, 182, 184]], [[218, 208, 207]], [[218, 207, 185]], [[212, 213, 219]], [[219, 186, 212]], [[181, 185, 207]], [[186, 184, 212]], [[176, 179, 178]], [[176, 178, 214]], [[182, 177, 205]], [[216, 205, 177]], [[222, 96, 90]], [[222, 90, 187]], [[101, 111, 149]], [[149, 150, 101]], [[189, 72, 58]], [[189, 58, 156]], [[164, 190, 228]], [[189, 190, 164]], [[220, 187, 124]], [[220, 124, 191]], [[162, 145, 141]], [[162, 141, 155]], [[140, 188, 150]], [[154, 188, 140]], [[193, 228, 192]], [[192, 228, 190]], [[144, 150, 149]], [[145, 150, 144]], [[86, 224, 223]], [[86, 223, 68]], [[87, 193, 192]], [[87, 192, 70]], [[225, 226, 50]], [[50, 69, 225]], [[223, 220, 191]], [[223, 191, 157]], [[196, 229, 227]], [[227, 195, 196]], [[229, 146, 143]], [[196, 146, 229]], [[225, 194, 195]], [[225, 170, 194]], [[158, 170, 225]], [[197, 116, 97]], [[197, 97, 119]], [[198, 100, 117]], [[100, 198, 123]], [[202, 200, 178]], [[202, 178, 201]], [[205, 204, 206]], [[209, 208, 121]], [[209, 121, 120]], [[212, 211, 213]], [[215, 197, 119]], [[215, 119, 139]], [[215, 139, 214]], [[198, 217, 123]], [[123, 217, 167]], [[217, 216, 167]], [[209, 202, 201]], [[211, 206, 210]], [[218, 77, 66]], [[60, 74, 219]], [[215, 200, 199]], [[215, 199, 165]], [[217, 203, 204]], [[166, 203, 217]], [[208, 218, 66]], [[208, 66, 48]], [[208, 48, 121]], [[219, 213, 60]], [[60, 213, 65]], [[213, 125, 65]], [[84, 164, 134]], [[84, 134, 59]], [[222, 221, 136]], [[222, 136, 148]], [[224, 221, 220]], [[224, 220, 223]], [[135, 226, 227]], [[129, 135, 227]], [[96, 222, 148]], [[96, 148, 89]], [[149, 111, 123]], [[123, 111, 100]], [[228, 134, 164]], [[138, 134, 228]], [[138, 228, 193]], [[88, 138, 193]], [[131, 144, 149]], [[123, 131, 149]], [[224, 86, 65]], [[224, 65, 125]], [[193, 87, 51]], [[193, 51, 88]], [[50, 226, 83]], [[83, 226, 135]], [[227, 229, 129]], [[129, 229, 160]], [[143, 160, 229]], [[127, 160, 143]]]]}]}, "room_2": {"type": "BuildingPart", "parents": ["id-1"], "geometry": [{"type": "Solid", "lod": 2, "boundaries": [[[[230, 235, 232]], [[230, 232, 233]], [[240, 237, 241]], [[238, 237, 240]], [[235, 230, 234]], [[235, 234, 231]], [[239, 236, 238]], [[237, 238, 236]], [[235, 243, 242]], [[235, 242, 238]], [[235, 238, 240]], [[235, 240, 232]], [[238, 242, 239]], [[243, 235, 231]], [[242, 244, 236]], [[242, 236, 239]], [[241, 233, 240]], [[232, 240, 233]], [[241, 237, 244]], [[233, 241, 244]], [[244, 230, 233]], [[230, 244, 245]], [[234, 230, 245]], [[244, 237, 236]], [[243, 245, 244]], [[243, 244, 242]], [[245, 243, 231]], [[245, 231, 234]]]]}]}, "room_3": {"type": "BuildingPart", "parents": ["id-1"], "geometry": [{"type": "Solid", "lod": 2, "boundaries": [[[[279, 278, 249]], [[249, 278, 252]], [[252, 254, 249]], [[249, 254, 247]], [[256, 255, 251]], [[251, 255, 254]], [[254, 252, 251]], [[251, 252, 248]], [[259, 250, 255]], [[255, 250, 257]], [[260, 259, 256]], [[256, 259, 255]], [[255, 257, 254]], [[254, 257, 247]], [[250, 259, 258]], [[258, 259, 253]], [[259, 260, 253]], [[253, 260, 246]], [[266, 264, 262]], [[266, 262, 261]], [[251, 267, 256]], [[266, 267, 251]], [[266, 251, 264]], [[251, 248, 264]], [[268, 263, 267]], [[265, 267, 263]], [[260, 256, 269]], [[267, 269, 256]], [[269, 267, 265]], [[268, 267, 266]], [[261, 268, 266]], [[260, 269, 246]], [[277, 280, 262]], [[262, 280, 261]], [[274, 269, 265]], [[274, 265, 273]], [[265, 272, 273]], [[272, 265, 263]], [[274, 270, 258]], [[258, 253, 274]], [[274, 253, 269]], [[253, 246, 269]], [[273, 270, 274]], [[270, 273, 271]], [[264, 278, 262]], [[262, 278, 277]], [[278, 279, 277]], [[277, 279, 275]], [[278, 264, 252]], [[252, 264, 248]], [[281, 279, 247]], [[247, 279, 249]], [[280, 281, 282]], [[281, 280, 276]], [[285, 284, 281]], [[281, 284, 282]], [[250, 270, 257]], [[257, 270, 285]], [[285, 270, 271]], [[279, 281, 275]], [[275, 281, 276]], [[283, 284, 272]], [[272, 284, 273]], [[280, 277, 276]], [[276, 277, 275]], [[268, 283, 263]], [[263, 283, 272]], [[284, 285, 273]], [[273, 285, 271]], [[257, 285, 247]], [[247, 285, 281]], [[284, 283, 282]], [[282, 283, 280]], [[283, 268, 280]], [[280, 268, 261]], [[270, 250, 258]]]]}]}, "room_4": {"type": "BuildingPart", "parents": ["id-1"], "geometry": [{"type": "Solid", "lod": 2, "boundaries": [[[[289, 288, 286]], [[286, 288, 287]], [[291, 289, 290]], [[290, 289, 286]], [[293, 291, 290]], [[290, 292, 293]], [[293, 288, 291]], [[291, 288, 289]], [[287, 292, 290]], [[290, 286, 287]], [[293, 292, 288]], [[292, 287, 288]]]]}]}, "room_5": {"type": "BuildingPart", "parents": ["id-1"], "geometry": [{"type": "Solid", "lod": 2, "boundaries": [[[[296, 297, 294]], [[296, 294, 295]], [[300, 301, 299]], [[298, 300, 299]], [[298, 299, 296]], [[295, 298, 296]], [[297, 301, 300]], [[297, 300, 294]], [[300, 298, 294]], [[298, 295, 294]], [[299, 301, 297]], [[299, 297, 296]]]]}]}}, "vertices": [[-3.802734375, 1.5625, -23.296875], [-4.19921875, -0.443359375, -23.296875], [-3.86328125, 1.244140625, -25.03125], [-3.669921875, 2.23828125, -23.296875], [-3.86328125, 1.2578125, -23.296875], [-3.6796875, 2.177734375, -24.1875], [-3.80078125, 1.5693359375, -24.0625], [-3.86328125, 1.251953125, -23.984375], [-3.89453125, 1.095703125, -23.953125], [-3.896484375, 1.087890625, -23.296875], [-3.888671875, 1.1083984375, -25.03125], [-4.19921875, -0.4462890625, -23.625], [-4.19921875, -0.45947265625, -25.046875], [-2.423828125, 1.1826171875, -23.984375], [-2.341796875, 1.1708984375, -25.0], [-2.26171875, 1.1591796875, -25.984375], [-3.748046875, 1.23828125, -25.03125], [-3.728515625, 1.24609375, -23.984375], [-3.763671875, 1.2314453125, -26.0], [-4.43359375, 0.60009765625, -23.296875], [-4.19921875, 0.81201171875, -23.296875], [-4.19921875, 1.2744140625, -23.296875], [-4.15625, 1.2578125, -25.046875], [-3.689453125, 2.12109375, -25.03125], [-4.375, 0.6572265625, -23.859375], [-4.25, 0.78125, -25.046875], [-4.24609375, 1.2705078125, -23.984375], [-4.19921875, 1.0400390625, -25.046875], [-4.19921875, 1.2646484375, -24.53125], [-4.1015625, 2.328125, -23.296875], [-4.0390625, 2.251953125, -24.203125], [-3.982421875, 2.1796875, -25.03125], [-4.19921875, 1.8125, -23.296875], [-3.470703125, 1.498046875, -25.953125], [-3.796875, 1.5791015625, -25.03125], [-4.08203125, 1.6591796875, -25.046875], [-4.30078125, 1.279296875, -23.296875], [-3.474609375, 1.478515625, -24.046875], [-2.884765625, 2.015625, -24.15625], [-2.9453125, 1.9677734375, -25.015625], [-3.47265625, 1.48828125, -25.03125], [-4.19921875, 0.826171875, -25.046875], [-4.19921875, 0.81689453125, -23.890625], [-4.2265625, 1.6806640625, -23.296875], [-4.19921875, 1.673828125, -23.296875], [-4.16015625, 1.6708984375, -24.078125], [-4.19921875, 1.48828125, -24.03125], [-4.19921875, 1.6767578125, -23.609375], [-1.9423828125, -7.51953125, -25.96875], [-0.308349609375, 0.88427734375, -25.96875], [-0.31396484375, 0.89794921875, -23.59375], [-0.61279296875, -0.6337890625, -23.296875], [-0.60009765625, -0.61083984375, -25.71875], [-1.0029296875, -2.640625, -23.296875], [-0.5986328125, -0.6083984375, -25.96875], [-1.943359375, -7.51953125, -25.71875], [-0.308837890625, 0.8857421875, -25.71875], [-0.830078125, -1.7978515625, -25.96875], [-0.8310546875, -1.798828125, -25.71875], [-0.84130859375, -1.80859375, -23.296875], [-1.6044921875, -5.73046875, -23.296875], [-1.2724609375, -4.07421875, -25.96875], [-1.294921875, -4.140625, -23.296875], [-1.009765625, -2.716796875, -25.71875], [-1.0107421875, -2.724609375, -25.96875], [-1.953125, -7.5234375, -23.296875], [-1.61328125, -5.82421875, -25.96875], [-1.2744140625, -4.078125, -25.71875], [-1.9462890625, -7.5234375, -25.0], [-0.310546875, 0.8896484375, -25.03125], [-0.603515625, -0.6171875, -25.03125], [-1.0078125, -2.6953125, -25.03125], [-0.833984375, -1.8017578125, -25.03125], [-1.6103515625, -5.79296875, -25.015625], [-1.52734375, -5.33203125, -23.296875], [-1.6123046875, -5.81640625, -25.71875], [-1.521484375, -5.3515625, -25.71875], [-1.521484375, -5.3515625, -25.96875], [-1.5234375, -5.34375, -25.015625], [-1.5263671875, -5.3359375, -23.59375], [-1.60546875, -5.7421875, -23.59375], [-1.2802734375, -4.09765625, -25.015625], [-1.2919921875, -4.1328125, -23.59375], [-0.314697265625, 0.89990234375, -23.3125], [-0.84033203125, -1.8076171875, -23.59375], [-1.00390625, -2.650390625, -23.59375], [-1.9521484375, -7.5234375, -23.59375], [-0.611328125, -0.630859375, -23.59375], [-1.0537109375, -0.564453125, -23.296875], [-5.7734375, -6.7890625, -23.296875], [-5.78125, -6.78125, -25.03125], [-4.71875, -1.7783203125, -25.953125], [-4.70703125, -1.7900390625, -23.3125], [-5.0546875, -3.423828125, -23.3125], [-5.0546875, -3.3671875, -25.453125], [-5.0546875, -3.353515625, -25.953125], [-5.77734375, -6.78515625, -23.59375], [-4.5, -0.76171875, -25.953125], [-4.49609375, -0.7529296875, -25.46875], [-4.7109375, -1.7880859375, -23.59375], [-4.4765625, -0.71435546875, -23.3125], [-4.4921875, -0.74560546875, -25.046875], [-4.91015625, -2.73046875, -23.3125], [-4.94140625, -2.81640625, -25.953125], [-4.93359375, -2.80078125, -25.453125], [-4.91015625, -2.740234375, -23.59375], [-4.9296875, -2.787109375, -25.046875], [-4.71484375, -1.7822265625, -25.046875], [-5.0546875, -3.416015625, -23.59375], [-5.0546875, -3.37890625, -25.03125], [-5.78515625, -6.78125, -25.453125], [-4.48046875, -0.7197265625, -23.59375], [-4.53125, -0.9130859375, -25.046875], [-4.71484375, -1.7802734375, -25.453125], [-4.53125, -0.912109375, -25.46875], [-4.5234375, -0.91650390625, -23.59375], [-4.53515625, -0.9111328125, -25.953125], [-4.5234375, -0.91748046875, -23.3125], [-4.453125, -3.46875, -25.953125], [-3.96484375, -0.86474609375, -25.953125], [-2.9765625, -7.3203125, -25.953125], [-2.314453125, -7.44921875, -25.96875], [-1.2744140625, -1.794921875, -25.96875], [-3.955078125, -0.81494140625, -23.3125], [-5.1015625, -6.91015625, -25.5], [-2.3203125, -7.453125, -23.296875], [-3.544921875, 1.3681640625, -25.953125], [-3.54296875, 1.3818359375, -23.3125], [-0.76953125, 0.953125, -25.96875], [-1.798828125, 1.1220703125, -23.3125], [-2.009765625, -0.386962890625, -25.96875], [-3.826171875, -0.129638671875, -23.3125], [-3.822265625, -0.10302734375, -25.953125], [-1.0439453125, -0.53857421875, -25.96875], [-1.2822265625, -1.806640625, -23.296875], [-0.77197265625, 0.96826171875, -23.3125], [-3.021484375, -7.3203125, -23.296875], [-1.201171875, -1.396484375, -25.96875], [-1.197265625, -1.3447265625, -23.296875], [-2.126953125, -1.21875, -25.96875], [-2.138671875, -1.197265625, -25.03125], [-3.822265625, -0.10760498046875, -25.5], [-3.544921875, 1.37109375, -25.5], [-3.54296875, 1.380859375, -23.59375], [-3.826171875, -0.126708984375, -23.59375], [-3.82421875, -0.11212158203125, -25.046875], [-3.544921875, 1.373046875, -25.046875], [-1.810546875, 1.1083984375, -25.96875], [-5.1015625, -6.91796875, -23.296875], [-3.95703125, -0.8203125, -23.59375], [-3.9609375, -0.84765625, -25.046875], [-5.1015625, -6.91015625, -25.953125], [-4.45703125, -3.48046875, -25.5], [-1.044921875, -0.541015625, -25.6875], [-2.130859375, -1.2109375, -25.625], [-2.015625, -0.3896484375, -25.625], [-1.275390625, -1.796875, -25.6875], [-2.314453125, -7.44921875, -25.703125], [-0.76953125, 0.95458984375, -25.6875], [-1.802734375, 1.107421875, -25.96875], [-1.8447265625, 1.1279296875, -23.3125], [-2.05859375, -0.406982421875, -23.3125], [-2.02734375, -0.39404296875, -25.03125], [-1.201171875, -1.390625, -25.6875], [-1.28125, -1.8056640625, -23.59375], [-4.13671875, -1.78125, -25.953125], [-4.140625, -1.79296875, -23.3125], [-2.162109375, -1.1591796875, -23.296875], [-4.46484375, -3.537109375, -23.296875], [-1.80859375, 1.0595703125, -25.96875], [-1.8076171875, 1.1103515625, -25.625], [-1.80859375, 1.1103515625, -25.625], [-1.7666015625, -0.42529296875, -25.96875], [-1.75390625, -0.45458984375, -23.3125], [-1.7421875, -1.2919921875, -25.96875], [-1.7314453125, -1.2421875, -23.296875], [-1.7275390625, -1.79296875, -25.96875], [-1.7158203125, -1.8046875, -23.296875], [-2.33984375, -2.755859375, -25.96875], [-1.701171875, -2.7421875, -25.96875], [-1.447265625, -2.736328125, -25.96875], [-1.6669921875, -3.931640625, -25.96875], [-1.69140625, -2.65625, -23.296875], [-1.4365234375, -2.650390625, -23.296875], [-1.6572265625, -3.849609375, -23.296875], [-1.6650390625, -3.998046875, -25.96875], [-1.6513671875, -4.07421875, -23.296875], [-5.1015625, -6.9140625, -25.015625], [-3.962890625, -0.85595703125, -25.5], [-1.27734375, -1.7998046875, -25.03125], [-1.2001953125, -1.3779296875, -25.03125], [-2.98046875, -7.3203125, -25.65625], [-1.046875, -0.5478515625, -25.03125], [-1.052734375, -0.5615234375, -23.59375], [-1.80859375, 1.1103515625, -25.5625], [-1.806640625, 1.11328125, -25.046875], [-1.8173828125, 1.115234375, -25.046875], [-4.09375, -1.5576171875, -25.953125], [-4.09375, -1.548828125, -23.3125], [-4.328125, -2.80078125, -25.953125], [-3.267578125, -2.77734375, -25.953125], [-2.4921875, -3.841796875, -25.96875], [-2.5546875, -3.830078125, -25.96875], [-4.3125, -2.716796875, -23.3125], [-3.31640625, -2.693359375, -23.296875], [-2.373046875, -2.671875, -23.296875], [-2.537109375, -3.84375, -23.296875], [-1.6787109375, -3.99609375, -25.96875], [-1.841796875, -4.87890625, -25.96875], [-2.5, -3.908203125, -25.96875], [-2.544921875, -3.90234375, -23.296875], [-2.490234375, -3.912109375, -23.296875], [-1.697265625, -4.0625, -23.296875], [-1.84375, -4.8671875, -23.296875], [-2.205078125, -1.791015625, -25.96875], [-3.943359375, -1.7822265625, -25.953125], [-2.251953125, -1.8017578125, -23.296875], [-3.927734375, -1.7939453125, -23.3125], [-1.630859375, -5.19140625, -25.96875], [-1.619140625, -5.1953125, -23.296875], [-2.9921875, -7.3203125, -25.015625], [-3.015625, -7.3203125, -23.59375], [-5.1015625, -6.91796875, -23.59375], [-2.31640625, -7.44921875, -25.0], [-2.318359375, -7.453125, -23.59375], [-0.77001953125, 0.95849609375, -25.046875], [-0.771484375, 0.96630859375, -23.59375], [-1.7998046875, 1.1201171875, -23.59375], [-1.197265625, -1.3505859375, -23.59375], [-1.83984375, 1.1259765625, -23.59375], [0.7490234375, -1.099609375, -23.65625], [0.79248046875, -0.9033203125, -25.90625], [0.431640625, -2.830078125, -25.953125], [0.424560546875, -2.83203125, -23.609375], [0.77880859375, -0.93994140625, -23.65625], [0.755859375, -1.099609375, -25.921875], [1.9912109375, -1.220703125, -23.640625], [1.923828125, -1.533203125, -23.625], [1.927734375, -1.6005859375, -25.90625], [2.017578125, -1.1875, -25.890625], [1.6083984375, -3.0859375, -25.9375], [1.5888671875, -3.083984375, -23.59375], [1.671875, -1.107421875, -25.90625], [1.640625, -1.099609375, -25.90625], [1.73046875, -1.1611328125, -23.640625], [1.46875, -1.099609375, -23.640625], [-0.63525390625, -0.580078125, -23.609375], [1.6376953125, -1.099609375, -25.984375], [1.8544921875, -1.20703125, -23.609375], [1.8623046875, -1.15625, -25.984375], [-0.60009765625, -0.53564453125, -26.0], [1.662109375, -1.158203125, -23.609375], [1.859375, -1.171875, -25.25], [-0.625, -0.54638671875, -25.25], [1.6455078125, -1.1181640625, -25.25], [0.7998046875, -0.90478515625, -25.25], [0.7998046875, -0.94189453125, -23.609375], [0.7998046875, -0.88818359375, -25.984375], [-0.6201171875, -0.53076171875, -26.0], [-0.60009765625, -0.55224609375, -25.25], [-0.60009765625, -0.58935546875, -23.609375], [0.84912109375, 1.1435546875, -23.59375], [2.08203125, 0.9072265625, -23.59375], [-0.1690673828125, 1.337890625, -23.609375], [2.02734375, 0.40771484375, -23.59375], [-0.29541015625, 0.818359375, -23.609375], [1.0478515625, 0.5810546875, -23.609375], [0.7998046875, 0.62451171875, -23.609375], [0.7998046875, 1.15234375, -23.59375], [-0.60009765625, -0.43505859375, -23.609375], [-0.60009765625, -0.447021484375, -26.0], [-0.294189453125, 0.81103515625, -25.984375], [-0.1768798828125, 1.2978515625, -25.203125], [-0.294677734375, 0.8134765625, -25.21875], [-0.60009765625, -0.443359375, -25.25], [2.078125, 0.8466796875, -25.96875], [0.869140625, 1.078125, -25.984375], [2.078125, 0.8662109375, -25.203125], [2.029296875, 0.40283203125, -25.21875], [2.029296875, 0.400390625, -25.96875], [0.86279296875, 1.099609375, -25.203125], [1.046875, 0.57421875, -25.984375], [1.046875, 0.576171875, -25.21875], [0.7998046875, 1.111328125, -25.203125], [0.7998046875, 0.6201171875, -25.21875], [0.7998046875, 0.61767578125, -25.984375], [-1.6953125, -6.140625, -23.296875], [-1.6728515625, -6.140625, -26.0], [-0.9521484375, -2.671875, -25.96875], [-0.966796875, -2.6328125, -23.296875], [1.6318359375, -6.875, -23.296875], [2.3515625, -3.17578125, -23.296875], [1.6015625, -6.8671875, -26.015625], [2.3125, -3.20703125, -25.984375], [2.201171875, 0.419189453125, -23.578125], [3.021484375, 0.304443359375, -23.578125], [2.998046875, 0.308837890625, -25.734375], [2.15625, 0.4267578125, -25.890625], [2.74609375, -1.1259765625, -23.59375], [2.724609375, -1.115234375, -25.75], [1.8818359375, -1.025390625, -23.59375], [1.83984375, -1.01171875, -25.90625]], "transform": {"scale": [1.0, 1.0, 1.0], "translate": [0.0, 0.0, 0.0]}}
--------------------------------------------------------------------------------
/ipcp/modules/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Amsterdam-AI-Team/Indoor-PointCloud-to-CityJSON/fefcbbc201721e34d00f9fb432671028c64c2e3f/ipcp/modules/__init__.py
--------------------------------------------------------------------------------
/ipcp/modules/floor_split.py:
--------------------------------------------------------------------------------
1 | """Floor Splitting Module"""
2 | import numpy as np
3 | import logging
4 | import time
5 |
6 |
7 | from scipy.ndimage import label, binary_closing, binary_dilation, binary_erosion
8 | from scipy.interpolate import griddata
9 | from scipy.stats import binned_statistic_2d
10 | from src.interpolation import FastGridInterpolator
11 | from src.utils.clip_utils import poly_box_clip
12 | from rasterio import features, Affine
13 | from shapely import geometry
14 | from shapely.geometry import Polygon, Point
15 | from shapely.ops import unary_union, transform
16 | import matplotlib.pyplot as plt
17 |
18 | NOISE = 0
19 | SLANTED = 1
20 | ALMOST_VERTICAL = 2
21 | ALMOST_HORIZONTAL = 3
22 |
23 | logger = logging.getLogger(__name__)
24 |
25 | class FloorSplitter:
26 | """
27 | FloorSplitter class for the division of pointcloud data into floors.
28 | The class splits the pointcloud into floors using density analysis along the z-axis.
29 |
30 | Parameters
31 | ----------
32 |
33 | """
34 |
35 | def __init__(self, subsample_size=0.03):
36 | self.subsample_size = subsample_size
37 |
38 | def _func(self, values):
39 | """
40 | Converts detected peaks into top and bottom split values
41 |
42 | Parameters
43 | ----------
44 | values : array
45 | The indices of the peaks
46 |
47 | Returns
48 | -------
49 | An array of split values for each floor
50 | """
51 |
52 | def _process_poly(self, poly: Polygon) -> Polygon:
53 | """
54 | Close polygon holes by limitation to the exterior ring.
55 | Args:
56 | poly: Input shapely Polygon
57 | Example:
58 | df.geometry.apply(lambda p: close_holes(p))
59 | """
60 | if poly.interiors:
61 | return Polygon(list(poly.exterior.coords)).buffer(3).buffer(-2).simplify(1)
62 | else:
63 | return poly.buffer(3).buffer(-2).simplify(1)
64 |
65 |
66 |
67 | def _create_3d_grid(self, points, bin_size=.1):
68 | min_x, max_x = min(points[:, 0])-2*bin_size, max(points[:, 0])+2*bin_size
69 | min_y, max_y = min(points[:, 1])-2*bin_size, max(points[:, 1])+2*bin_size
70 | min_z, max_z = min(points[:, 2])-2*bin_size, max(points[:, 2])+2*bin_size
71 | dimx = max_x - min_x
72 | dimy = max_y - min_y
73 | dimz = max_z - min_z
74 | bins = [np.uint(dimx/bin_size), np.uint(dimy/bin_size), np.uint(dimz/bin_size)]
75 | hist_range = [[min_x, max_x], [min_y, max_y], [min_z, max_z]]
76 |
77 | counts, edges = np.histogramdd(points, range=hist_range, bins=bins)
78 | origin = (hist_range[0][0]+bin_size/2,hist_range[1][0]+bin_size/2, hist_range[2][0]+bin_size/2)
79 | grid = counts > 0
80 |
81 | return grid, edges, bins, hist_range, origin
82 |
83 | def _check_multistory(self, primitives, labels, min_floor_height=1.8, min_slab_size=4):
84 | slab_z = []
85 | for i,r in primitives.items():
86 | if r['type'] != ALMOST_VERTICAL:
87 | if np.sum(labels==i) * (self.subsample_size**2) > min_slab_size:
88 | slab_z.append(r['bbox'][:,2].max())
89 | if len(slab_z) > 1:
90 | slab_z = np.sort(slab_z)
91 | ceil_slabs = slab_z[slab_z > slab_z[0] + min_floor_height]
92 | if len(ceil_slabs) > 0:
93 | if np.sum(ceil_slabs > ceil_slabs[0] + min_floor_height) > 0:
94 | return 2
95 | else:
96 | return 1
97 | return 0
98 |
99 | def _extract_floor(self, points, labels, primitives, bin_size, min_floor_size, min_cluster_size):
100 |
101 | # create grid
102 | grid, edges, bins, hist_range, origin = self._create_3d_grid(points, bin_size)
103 |
104 | # Define floor primitives
105 | floor_primitives = []
106 | for i,r in primitives.items():
107 | mask = labels==i
108 | if r['type'] == ALMOST_HORIZONTAL and np.sum(mask) > min_floor_size/(self.subsample_size**2):
109 | floor_primitives.append([i,points[mask][:,2].min(), points[mask][:,2].max()])
110 | if len(floor_primitives) == 0:
111 | return np.ones(len(points), dtype=bool)
112 | floor_primitives = np.asarray(floor_primitives)
113 | floor_idx = np.argmin(floor_primitives[:,1])
114 | floor_point_mask = labels==floor_primitives[floor_idx,0]
115 |
116 | # floor grid bounds
117 | l, t = np.digitize(floor_primitives[floor_idx,1:], edges[2])-1
118 | r = int(t+np.ceil(1.5/bin_size))
119 | floor_proj = binary_dilation(np.histogram2d(*points[floor_point_mask,:2].T, range=hist_range[:2], bins=bins[:2])[0]>0)
120 | # plt.imshow(floor_proj)
121 | # plt.show()
122 |
123 | # Project space above floor
124 | space_proj = binary_dilation(np.sum(grid[:,:,l:r],axis=2)>0)
125 | lcc_space_proj = label(space_proj)[0]
126 | lcc_space_mask = np.where(np.unique(lcc_space_proj, return_counts=True)[1] < min_cluster_size/(bin_size**2))
127 | lcc_space_proj[np.isin(lcc_space_proj, lcc_space_mask)] = 0 # remove small blobs in space projection
128 | space_proj = np.isin(lcc_space_proj, [l for l in np.unique(lcc_space_proj[floor_proj]) if l > 0])
129 |
130 | # Merge floor & space
131 | floor_proj = space_proj | floor_proj
132 | ceil_proj = np.zeros(floor_proj.shape, dtype=bool)
133 | ceiling_map = np.full(floor_proj.shape, np.nan)
134 | cnf_proj = np.copy(floor_proj)
135 | # plt.imshow(floor_proj)
136 | # plt.show()
137 |
138 | # list candidate ceilings
139 | ceiling_candidates = []
140 | for i,r in primitives.items():
141 | if r['type'] != ALMOST_VERTICAL and np.sum(labels==i) > min_cluster_size/(self.subsample_size**2):
142 | if points[labels==i][:,2].max() > floor_primitives[floor_idx,1]+1.8:
143 | ceiling_candidates.append((i,points[labels==i][:,2].min(), points[labels==i][:,2].max()))
144 | ceiling_candidates = np.asarray(ceiling_candidates)
145 | ceiling_candidates = ceiling_candidates[np.argsort(ceiling_candidates[:,1])]
146 |
147 | # Loop through ceiling candidates
148 | for l, _, ceil_max_z in ceiling_candidates:
149 | cand_z_proj = binned_statistic_2d(*points[labels==l].T, statistic='max', range=hist_range[:2], bins=bins[:2])[0]
150 | cand_proj = binary_closing(~np.isnan(cand_z_proj))
151 |
152 | # fig, ax = plt.subplots(1, 3, sharey=True)
153 | # ax[0].imshow(floor_proj)
154 | # ax[1].imshow(cand_proj)
155 | # ax[2].imshow(ceil_proj)
156 | # plt.show()
157 | # print(l, np.sum(labels==l), np.sum(floor_proj[cand_proj]), np.sum(cand_proj))
158 |
159 | floor_overlap = (np.sum(floor_proj[cand_proj]) / np.sum(cand_proj)).round(2)
160 | ceiling_overlap = (np.sum(ceil_proj[cand_proj]) / np.sum(cand_proj)).round(2)
161 | # print(l, ceiling_overlap, floor_overlap)
162 |
163 | # Check if ceiling is valid
164 | if floor_overlap > .5 and ceiling_overlap < .1:
165 | floor_proj[cand_proj] = False
166 | cnf_proj[cand_proj] = True
167 | ceiling_map[cand_proj] = cand_z_proj[cand_proj] + .1 # some nan ? interpolation
168 |
169 | # Tracking purposes..
170 | ceil_proj[cand_proj] = True
171 | keep_searching = np.any(np.unique(label(binary_erosion(floor_proj))[0], return_counts=True)[1][1:] > 0.8*min_cluster_size/(bin_size**2))
172 | if not keep_searching:
173 | break
174 |
175 | # Interpolate ceiling
176 | ceil_mask = ~np.isnan(ceiling_map)
177 | ceiling_map[~ceil_mask] = griddata(np.vstack(np.where(ceil_mask)).T, ceiling_map[ceil_mask], np.where(~ceil_mask), method='nearest')
178 |
179 | # Floor polygon
180 | floor_complete = binary_dilation(cnf_proj).astype(np.uint8)
181 | generator = features.shapes(floor_complete, mask=floor_complete>0)
182 | floor_polygons = [self._process_poly(geometry.shape(shape)) for shape, _ in generator]
183 | floor_polygon = transform(lambda x, y, z=None: (y*bin_size+origin[0], x*bin_size+origin[1]), unary_union(floor_polygons))
184 |
185 | # Create mask
186 | max_z_interpolator = FastGridInterpolator(bin_x=edges[0], bin_y=edges[1], values=ceiling_map)
187 | min_z = floor_primitives[floor_idx,1]-.1
188 | floor_mask = poly_box_clip(points, floor_polygon, bottom=min_z, top=np.max(ceiling_map)+.15)
189 | height_mask = points[floor_mask, 2] <= max_z_interpolator(points[floor_mask])
190 | floor_mask[floor_mask] = height_mask
191 |
192 | return floor_mask
193 |
194 |
195 |
196 | def process(self, pcd, labels, primitives):
197 | """
198 | Parameters
199 | ----------
200 | points : array of shape (n_points, 3)
201 | The point cloud .
202 |
203 | Returns
204 | -------
205 | An array of masks, where each mask represents a floor in the pointcloud.
206 | """
207 |
208 | logger.debug('Analysing pointcloud for floors...')
209 | points = np.asarray(pcd.points)
210 | un_mask = np.ones(len(points), dtype=bool)
211 | floors = []
212 | start = time.time()
213 | while self._check_multistory(primitives, labels[un_mask]) > 0:
214 | # TODO: error test
215 | mask = self._extract_floor(points[un_mask], labels[un_mask], primitives, bin_size=0.1, min_floor_size=5, min_cluster_size=.5)
216 | floor_mask = np.zeros(len(points), dtype=bool)
217 | floor_mask[un_mask] = mask
218 | floors.append(floor_mask)
219 | un_mask[floor_mask] = False
220 |
221 | logger.debug(f"Done. Number of floor extracted {len(floors)} floors. {round(time.time()-start,2)}s\n")
222 |
223 | return floors
224 |
--------------------------------------------------------------------------------
/ipcp/modules/mesh_stats.py:
--------------------------------------------------------------------------------
1 | """Mesh Area Volume Module"""
2 | import numpy as np
3 | import logging
4 |
5 | import pymeshlab
6 | import json
7 | import argparse
8 | import os
9 |
10 | logger = logging.getLogger(__name__)
11 |
12 | class MeshAnalyser:
13 | """
14 | MeshAnalyser class for the volume and area computation of a mesh.
15 | The class compute both the volume and area for a given mesh.
16 |
17 | Parameters
18 | ----------
19 | face_condition : float (default=-0.95)
20 | The condition for face selection.
21 | """
22 |
23 | def __init__(self, face_condition=-0.95):
24 | self.face_condition = face_condition
25 |
26 | def _get_area_volume(self, meshset):
27 | meshset.meshing_remove_duplicate_vertices()
28 | meshset.meshing_merge_close_vertices()
29 | meshset.meshing_re_orient_faces_coherentely()
30 |
31 | geom = meshset.get_geometric_measures()
32 | if 'mesh_volume' in geom.keys():
33 | volume = geom['mesh_volume']
34 | else:
35 | volume = 0
36 | logger.debug(f'volume is {volume}')
37 |
38 | if volume<0:
39 | meshset.meshing_invert_face_orientation()
40 | geom = meshset.get_geometric_measures()
41 | volume = geom['mesh_volume']
42 | logger.debug(f'after inverting, volume is now {volume}')
43 |
44 | statement = ('(fnz < ' + str(self.face_condition) + ')')
45 | meshset.compute_selection_by_condition_per_face(condselect=statement)
46 | meshset.apply_selection_inverse(invfaces = True)
47 | meshset.meshing_remove_selected_faces()
48 |
49 | geom2 = meshset.get_geometric_measures()
50 | logger.debug(f'floor area is {geom2["surface_area"]}')
51 |
52 | floorarea = geom2['surface_area']
53 |
54 | return volume, floorarea
55 |
56 |
57 | def process(self, mesh):
58 | """
59 | Parameters
60 | ----------
61 | mesh : pmeshlab.Mesh
62 | The pymeshlab Meshset.
63 |
64 | Returns
65 | -------
66 | volume : float
67 | The volume of the input mesh.
68 | floorarea : float
69 | The floorarea of the input mesh.
70 | """
71 |
72 | logger.debug(f'Analysing mesh...')
73 |
74 | try:
75 | volume, floorarea = self._get_area_volume(mesh)
76 | logger.debug(f'The volume of room is {volume:.2f} and the floorarea is {floorarea:.2f}')
77 | except:
78 | volume, floorarea = None, None
79 | logger.debug(f'metrics cannot be calculated')
80 |
81 | return volume, floorarea
82 |
--------------------------------------------------------------------------------
/ipcp/modules/primitive_detection.py:
--------------------------------------------------------------------------------
1 | """Primitive Detection Module"""
2 |
3 | import os
4 | import logging
5 | import subprocess
6 | import numpy as np
7 | import open3d as o3d
8 | from scipy.spatial import KDTree
9 |
10 | import src.utils.math_utils as math_utils
11 | from src.region_growing import RegionGrowing
12 | from src.utils.pcd_utils import merge_point_clouds
13 |
14 | logger = logging.getLogger(__name__)
15 |
16 | NOISE = 0
17 | SLANTED = 1
18 | ALMOST_VERTICAL = 2
19 | ALMOST_HORIZONTAL = 3
20 |
21 | class PrimitiveDetector:
22 | """
23 | PrimitiveDetector class for the geometric primitives in the pointcloud.
24 | The class labels primitives as horizontal, vertical or slanted.
25 |
26 | Parameters
27 | ----------
28 | min_peak_height : int (default=2500)
29 | The required height of a peak in the vertical density profile.
30 | threshold : int (default=250)
31 | The required threshold of peaks, the vertical distance to its neighboring samples.
32 | distance : int (default=20)
33 | The required minimal horizontal distance (>= 1) in samples between neighbouring peaks.
34 | prominence : int (default=2)
35 | The required prominence of peaks.
36 | min_floor_height : float (default=2.1)
37 | The minimal height a floor must be.
38 | floor_buffer : float (default=0.1)
39 | The buffer used to include the whole floor/ceiling.
40 | """
41 |
42 | def __init__(self, excecutable_path, subsample_size=0.03):
43 | self.excecutable_path = excecutable_path
44 | self.subsample_size = subsample_size
45 |
46 | def _plane_normal(self, pcd):
47 | a,b,c,_ = pcd.segment_plane(distance_threshold=0.03,
48 | ransac_n=5,
49 | num_iterations=10)[0]
50 | normal = np.array([a,b,c])
51 | normal /= np.linalg.norm(normal)
52 | return normal
53 |
54 | def _merge_parallel(self, pcd, labels):
55 | un_labels_ = np.unique(labels[labels>-1])
56 | normals = {}
57 | for label in un_labels_:
58 | pcd_label = pcd.select_by_index(np.where(labels==label)[0])
59 | normal = self._plane_normal(pcd_label)
60 | normals[label] = normal
61 |
62 | points = np.asarray(pcd.points)
63 | labels_iter = list(un_labels_)
64 | merge_count = 0
65 | pairs = []
66 | while len(labels_iter) > 0:
67 | label = labels_iter.pop(0)
68 | label_mask = np.where(labels==label)[0]
69 | kd_i = KDTree(points[label_mask])
70 | label_normal = normals[label]
71 |
72 | for i in labels_iter:
73 | angle = np.rad2deg(angle_between(label_normal[:2], normals[i][:2]))
74 | if angle < 3:
75 | num_pairs = np.sum(kd_i.query(points[labels==i], k=1, distance_upper_bound=.12)[1] 10:
77 | pairs.append((label,i))
78 | merge_count += 1
79 |
80 | lookup = {}
81 | for i,j in pairs:
82 | if j in lookup:
83 | lookup[i] = lookup[j]
84 | elif i in lookup:
85 | lookup[j] = lookup[i]
86 | else:
87 | lookup[j] = i
88 |
89 | for k,v in lookup.items():
90 | labels[labels==k] = v
91 |
92 | labels = consecutive_labels(labels)
93 |
94 | logger.debug(f'merged: {merge_count}')
95 | return labels
96 |
97 | def _detect_vertical(self, pcd):
98 | tmp_file = './tmp_pr/cloud.ply'
99 | if not os.path.isdir('./tmp_pr'):
100 | os.mkdir('./tmp_pr')
101 |
102 | # point selection
103 | labels = np.full(len(pcd.points),-1)
104 | verticality = compute_verticality(pcd, radius=.2)
105 | mask = np.where(verticality > 0.75)[0]
106 | pcd_ = pcd.select_by_index(mask)
107 | planarity = compute_planarity(pcd_, radius=.15)
108 | mask = mask[planarity > .3]
109 |
110 | # detect primtives
111 | pcd_ = pcd.select_by_index(mask)
112 | pcd_, ransac_lables = efficient_ransac(pcd_, self.excecutable_path, tmp_file)
113 | labels[-len(mask):] = ransac_lables
114 | pcd = merge_point_clouds(pcd.select_by_index(mask, invert=True), pcd_)
115 |
116 | # region grow
117 | region_growing = RegionGrowing()
118 | labels = region_growing.process(pcd, labels)
119 |
120 | # merge primitives
121 | labels = self._merge_parallel(pcd, labels)
122 |
123 | return pcd, labels
124 |
125 | def _detect_non_vertical(self, pcd):
126 | tmp_file = './tmp_pr/cloud.ply'
127 | if not os.path.isdir('./tmp_pr'):
128 | os.mkdir('./tmp_pr')
129 |
130 | # point selection
131 | labels = np.full(len(pcd.points), -1)
132 | planarity = compute_planarity(pcd, radius=.15)
133 | mask = np.where(planarity > .5)[0]
134 |
135 | # detect primitives
136 | pcd_ = pcd.select_by_index(mask)
137 | pcd_, ransac_lables = efficient_ransac(pcd_,
138 | self.excecutable_path, tmp_file, prob='0.005',
139 | eps='0.06', cluster_thres='0.15')
140 | labels[-len(mask):] = ransac_lables
141 | pcd = merge_point_clouds(pcd.select_by_index(mask, invert=True), pcd_)
142 |
143 | # clean verticals
144 | un_labels_ = np.unique(labels[labels>-1])
145 | for label in un_labels_:
146 | pcd_ = pcd.select_by_index(np.where(labels==label)[0])
147 | normal = self._plane_normal(pcd_)
148 | angle = np.rad2deg(np.arccos(np.abs(normal[2] / 1)))
149 | if angle > 85:
150 | labels[labels==label] = -1
151 |
152 | # region grow
153 | region_growing = RegionGrowing()
154 | labels = region_growing.process(pcd, labels)
155 |
156 | return pcd, labels
157 |
158 | def _labels_to_primitives(self, pcd, labels, exclude_labels=[-1], min_points=200):
159 | planes = {}
160 | rectangle_labels = [r for r in np.unique(labels) if r not in exclude_labels and np.sum(labels==r) > min_points]
161 | for i in rectangle_labels:
162 | region_cloud = pcd.select_by_index(np.where(labels==i)[0])
163 | region_pts = np.asarray(region_cloud.points)
164 | pts_surface = len(region_pts)*(self.subsample_size**2)
165 |
166 | # TODO: filter outliers out!
167 | a, b, c, d = region_cloud.segment_plane(distance_threshold=0.01,
168 | ransac_n=5,
169 | num_iterations=100)[0]
170 | normal = np.array([a,b,c])
171 | normal /= np.linalg.norm(normal)
172 | center = np.mean(region_pts,axis=0)
173 | slope = np.rad2deg(np.arccos(np.abs(normal[2] / 1)))
174 |
175 | # Compute bounding box
176 | if slope < 5:
177 | plane_type = ALMOST_HORIZONTAL
178 | min_bbox = math_utils.minimum_bounding_rectangle(region_pts[:,:2])
179 | if min_bbox[2] < .2:
180 | continue
181 | bbox_points = min_bbox[0]
182 | bbox_points = np.concatenate((bbox_points, np.full((4,1), center[2])),axis=1)
183 | else:
184 | xaxis = np.cross(normal, [0, 0, 1])
185 | yaxis = np.cross(normal, xaxis)
186 | xaxis /= np.linalg.norm(xaxis)
187 | yaxis /= np.linalg.norm(yaxis)
188 |
189 | new_x = np.dot(region_pts-center, xaxis)
190 | new_y = np.dot(region_pts-center, yaxis)
191 |
192 | xmin, ymin, xmax, ymax = math_utils.compute_bounding_box(np.vstack([new_x, new_y]).T)
193 | bbox_points = np.array([[xmin, ymin], [xmax, ymin], [xmax, ymax], [xmin, ymax]])
194 | bbox_points = center + bbox_points[:,0][:, None]*xaxis + bbox_points[:,1][:, None]*yaxis
195 | if slope > 80:
196 | plane_type = ALMOST_VERTICAL
197 | else:
198 | plane_type = SLANTED
199 |
200 | surface = bbox_area(bbox_points)
201 | coverage = pts_surface/surface
202 | if coverage < 0.05: # minimal coverage
203 | continue
204 |
205 | line_set = o3d.geometry.LineSet(
206 | points=o3d.utility.Vector3dVector(bbox_points),
207 | lines=o3d.utility.Vector2iVector([[0, 1],[1, 2],[2, 3],[3, 0]]),
208 | )
209 |
210 | plane_object = {
211 | 'region': i,
212 | 'bbox': bbox_points,
213 | 'lineset': line_set,
214 | 'surface': surface,
215 | 'coverage': coverage,
216 | 'center': center,
217 | 'normal': normal,
218 | 'D': d,
219 | 'slope': slope,
220 | 'type': plane_type
221 | }
222 |
223 | planes[i] = plane_object
224 |
225 | return planes
226 |
227 | def process(self, pcd):
228 | """
229 | Parameters
230 | ----------
231 | points : array of shape (n_points, 3)
232 | The point cloud .
233 |
234 | Returns
235 | -------
236 | An array of masks, where each mask represents a floor in the pointcloud.
237 | """
238 |
239 | logger.debug('Detecting primitives in pointcloud...')
240 | labels = np.full(len(pcd.points), SLANTED, dtype=np.uint8)
241 |
242 | logger.debug('Searching vertical primitives...')
243 | pcd, labels = self._detect_vertical(pcd)
244 | logger.debug(f'Done. Found {len(np.unique(labels))-1} primitives')
245 |
246 | logger.debug('Searching other primitives...')
247 | idx = np.where(labels==-1)[0]
248 | pcd_ = pcd.select_by_index(idx)
249 | pcd_, labels_ = self._detect_non_vertical(pcd_)
250 | logger.debug(f'Done. Found {len(np.unique(labels))-1} primitives')
251 |
252 | # Merge
253 | pcd = merge_point_clouds(pcd.select_by_index(idx, invert=True), pcd_)
254 | labels_[labels_>-1] += labels.max()+1
255 | labels = np.concatenate((labels[labels!=-1], labels_))
256 | primitives = self._labels_to_primitives(pcd, labels)
257 |
258 | return pcd, primitives, labels
259 |
260 | def compute_verticality(pcd, radius):
261 | '''Bla'''
262 | pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamRadius(radius=radius))
263 | verticality = 1 - np.abs(np.asarray(pcd.normals)[:,2])
264 | return verticality
265 |
266 | def compute_planarity(pcd, radius):
267 | '''Bla'''
268 | pcd.estimate_covariances(
269 | search_param=o3d.geometry.KDTreeSearchParamRadius(radius=radius))
270 | eig_val, _ = np.linalg.eig(np.asarray(pcd.covariances))
271 | eig_val = np.sort(eig_val, axis=1)
272 | planarity = (eig_val[:,1]-eig_val[:,0])/eig_val[:,2]
273 | return planarity
274 |
275 | def efficient_ransac(pcd, excecutable_path, file_path, normals_radius=.12, prob='0.001',
276 | min_pts='200', eps='0.03', cluster_thres='0.12', normal_thres='0.5'):
277 | '''Bla'''
278 |
279 | labels = np.full(len(pcd.points),-1)
280 |
281 | try:
282 | # Compute normals
283 | if not pcd.has_normals():
284 | pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamRadius(radius=normals_radius))
285 |
286 | # Write point cloud
287 | o3d.io.write_point_cloud(file_path, pcd)
288 |
289 | # RANSAC
290 | subprocess.run([excecutable_path, file_path, file_path, prob, min_pts, eps, cluster_thres, normal_thres],
291 | timeout=20, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
292 |
293 | # Read point cloud
294 | pcd_ = o3d.t.io.read_point_cloud(file_path)
295 | pcd = pcd_.to_legacy()
296 | labels = np.hstack(pcd_.point['plane_index'].numpy())
297 |
298 | except subprocess.TimeoutExpired:
299 | logger.error('RANSAC timeout')
300 | except subprocess.CalledProcessError as CPE:
301 | logger.error(f'Error in RANSAC with returncode {CPE.returncode}.')
302 | except Exception as e:
303 | logger.error(str(e))
304 |
305 | if os.path.isfile(file_path):
306 | os.remove(file_path)
307 |
308 | return pcd, labels
309 |
310 | def unit_vector(vector):
311 | """ Returns the unit vector of the vector. """
312 | return vector / np.linalg.norm(vector)
313 |
314 | def angle_between(v1, v2):
315 | """ Returns the angle in radians between vectors 'v1' and 'v2'::
316 |
317 | >>> angle_between((1, 0, 0), (0, 1, 0))
318 | 1.5707963267948966
319 | >>> angle_between((1, 0, 0), (1, 0, 0))
320 | 0.0
321 | >>> angle_between((1, 0, 0), (-1, 0, 0))
322 | 3.141592653589793
323 | """
324 | v1_u = unit_vector(v1)
325 | v2_u = unit_vector(v2)
326 | return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
327 |
328 | def consecutive_labels(labels):
329 | labels[labels>-1] = np.unique(labels[labels>-1], return_inverse=True)[1]
330 | return labels
331 |
332 | def bbox_area(bbox):
333 | return np.linalg.norm(bbox[0,:]-bbox[1,:]) * np.linalg.norm(bbox[2,:]-bbox[1,:])
334 |
--------------------------------------------------------------------------------
/ipcp/modules/room_detection.py:
--------------------------------------------------------------------------------
1 | """Room Detection Module"""
2 | import os
3 | import logging
4 |
5 | import cv2
6 | import open3d as o3d
7 | import numpy as np
8 | import random as rng
9 | import open3d as o3d
10 | from scipy import signal
11 | import matplotlib.pyplot as plt
12 | from shapely.geometry import Polygon
13 | import src.utils.clip_utils as clip_utils
14 | import src.utils.math_utils as math_utils
15 | from skspatial.objects import Plane
16 | import networkx as nx
17 | from scipy.stats import binned_statistic_2d
18 | from scipy.ndimage import binary_closing, binary_dilation, binary_erosion, generate_binary_structure, binary_fill_holes
19 | import rasterio
20 | from rasterio import features
21 | import shapely
22 | from shapely.geometry import Point, Polygon
23 | from shapely.ops import transform
24 | from skimage import measure
25 | from src.interpolation import FastGridInterpolator
26 |
27 | logger = logging.getLogger(__name__)
28 |
29 | # Point labels
30 | NOISE = 0
31 | SLANTED = 1
32 | ALMOST_VERTICAL = 2
33 | ALMOST_HORIZONTAL = 3
34 |
35 | # Primitive Connections
36 | WALL_WALL = 1
37 | WALL_CEILING = 2
38 | WALL_FLOOR = 3
39 | CEILING_CEILING = 4
40 | WALL_SLANTEDWALL = 5
41 |
42 | # Primitive Classes
43 | WALL = 1
44 | CEILING = 2
45 | FLOOR = 3
46 | SLANTED_WALL = 4
47 | CLUTTER = 5
48 |
49 | class RoomDetector:
50 | """
51 | RoomDetector class for the detection of rooms in a pointcloud floor.
52 | The class .....
53 |
54 | Parameters
55 | ----------
56 | min_peak_height : int (default=1500)
57 | The required height of a peak in the vertical density profile.
58 | threshold : int (default=250)
59 | The required threshold of peaks, the vertical distance to its neighboring samples.
60 | distance : int (default=20)
61 | The required minimal horizontal distance (>= 1) in samples between neighbouring peaks.
62 | prominence : int (default=2)
63 | The required prominence of peaks.
64 | thickness : int (default=20)
65 | The description of the parameter.
66 | """
67 |
68 | def __init__(self, subsample_size=0.03, plot=False):
69 | self.subsample_size = subsample_size
70 | self.plot = plot
71 |
72 | def _get_edge_type(self, primitive_i, primitive_j):
73 | if primitive_i['type'] == ALMOST_VERTICAL and primitive_j['type'] == ALMOST_VERTICAL:
74 | return WALL_WALL
75 | elif primitive_i['type'] == ALMOST_VERTICAL:
76 | if primitive_i['bbox'][:,2].mean() > primitive_j['bbox'][:,2].max():
77 | return WALL_FLOOR
78 | else:
79 | return WALL_CEILING
80 | elif primitive_j['type'] == ALMOST_VERTICAL:
81 | if primitive_i['bbox'][:,2].max() < primitive_j['bbox'][:,2].mean():
82 | return WALL_FLOOR
83 | else:
84 | return WALL_CEILING
85 | else:
86 | return CEILING_CEILING
87 |
88 | def _find_neighbouring_primitives(self, points, labels, primitives):
89 | neighbours = set()
90 | buffer = .5
91 |
92 | for _,r in primitives.items():
93 | bbox = r['bbox']
94 | rp = Polygon(bbox[:,:2]).buffer(buffer)
95 | c_mask = clip_utils.poly_box_clip(points, rp, bbox[:,2].min()-buffer, bbox[:,2].max()+buffer)
96 | for rn in np.unique(labels[c_mask]):
97 | if rn != r['region'] and rn in primitives.keys():
98 | neighbours.add(tuple(sorted((int(rn),r['region']))))
99 |
100 | logger.debug(f'Found {len(neighbours)} neighbouring planes.')
101 | return neighbours
102 |
103 | def _adjacency_graph(self, points, labels, primitives, neighbours):
104 |
105 | G = nx.Graph()
106 | G.add_nodes_from([(i,{'type':r['type']}) for i,r in primitives.items()])
107 |
108 | d_adj = .25
109 | l_intersect = .2
110 |
111 | # Create edges
112 | valid_pairs = 0
113 | for (i,j) in neighbours:
114 | angle_ij = math_utils.vector_angle(primitives[i]['normal'], primitives[j]['normal'])
115 | angle_ij = 90-abs(90-angle_ij)
116 | if angle_ij > 5:
117 | plane_i = Plane(primitives[i]['bbox'].mean(axis=0), primitives[i]['normal'])
118 | plane_j = Plane(primitives[j]['bbox'].mean(axis=0), primitives[j]['normal'])
119 | ij_intersect = plane_i.intersect_plane(plane_j)
120 | dist_i = math_utils.line_dist(points[labels==i], ij_intersect.point, ij_intersect.vector)
121 | dist_j = math_utils.line_dist(points[labels==j], ij_intersect.point, ij_intersect.vector)
122 | if np.sum(dist_i10 and np.sum(dist_j 10:
123 | proj_i = np.dot((points[labels==i][dist_il_intersect:
128 | edge_type = self._get_edge_type(primitives[i],primitives[j])
129 | G.add_edges_from([(i, j, {'type':edge_type})])
130 | valid_pairs+=1
131 |
132 | logger.debug(f'Number of valid pairs: {valid_pairs}')
133 | return G
134 |
135 | def _classify_graph(self, G):
136 | for V in nx.nodes(G):
137 | if G.nodes[V]['type'] == ALMOST_VERTICAL:
138 | if np.sum([G.edges[V,j]['type'] == WALL_CEILING for j in G[V]]) >= 1:
139 | G.nodes[V]['label'] = WALL
140 | elif np.sum([G.edges[V,j]['type'] == WALL_WALL for j in G[V]]) > 0 and \
141 | np.sum([G.edges[V,j]['type'] == WALL_SLANTEDWALL for j in G[V]]) > 0:
142 | G.nodes[V]['label'] = SLANTED_WALL
143 | else:
144 | G.nodes[V]['label'] = CLUTTER
145 | elif G.nodes[V]['type'] == ALMOST_HORIZONTAL: # MISSING wall-wall edge count
146 | if np.sum([G.edges[V,j]['type'] == WALL_CEILING for j in G[V]]) >= 2:
147 | G.nodes[V]['label'] = CEILING
148 | elif np.sum([G.edges[V,j]['type'] == WALL_FLOOR for j in G[V]]) >= 2:
149 | G.nodes[V]['label'] = FLOOR
150 | else:
151 | G.nodes[V]['label'] = CLUTTER
152 | elif G.nodes[V]['type'] == SLANTED: # MISSING wall-wall edge count
153 | if np.sum([G.edges[V,j]['type'] == WALL_CEILING for j in G[V]]) >= 2:
154 | G.nodes[V]['label'] = CEILING
155 | else:
156 | G.nodes[V]['label'] = CLUTTER
157 | else:
158 | G.nodes[V]['label'] = CLUTTER
159 |
160 | return G
161 |
162 | def _get_rooms(self, projection, origin, bin_size):
163 | room_labels = measure.label(~projection, background=0)
164 | min_surface = 0.6
165 | min_width = 0.65
166 |
167 | # Removes pillars and inner walls in top down projection
168 | for i in np.unique(room_labels):
169 | if i > 0:
170 | lcc_pts = np.vstack(np.where(room_labels==i)).T
171 | if len(lcc_pts) < min_surface/(bin_size**2): # min. sqr meters
172 | room_labels[np.where(room_labels==i)] = 0
173 | else:
174 | min_dims, max_dims = math_utils.minimum_bounding_rectangle(lcc_pts)[2:4]
175 | if min_dims < min_width / bin_size: # min. room dimension
176 | room_labels[np.where(room_labels==i)] = 0
177 | else:
178 | room_labels[binary_closing(room_labels==i, structure=generate_binary_structure(2, 2), iterations=2)] = i
179 |
180 | if self.plot:
181 | plt.figure(figsize=(6, 6))
182 | plt.subplot(111)
183 | plt.imshow(room_labels.T, cmap='nipy_spectral')
184 | plt.axis('off')
185 |
186 | # Convert to polygons
187 | rooms = []
188 | for shape, value in features.shapes(room_labels.astype(np.int16), mask=(room_labels>0), transform=rasterio.Affine(1.0, 0, 0, 0, 1.0, 0)):
189 | room_polygon = shapely.geometry.shape(shape).simplify(0.75)
190 | room_polygon = transform(lambda x, y, z=None: (y*bin_size+origin[0], x*bin_size+origin[1]), room_polygon)
191 | shape_proj = binary_fill_holes(room_labels==value)
192 | rooms.append((room_polygon, shape_proj))
193 |
194 | return rooms
195 |
196 | def _clean_mid_horizontal(self, pcd, labels, primitives):
197 |
198 | horizontal_labels = [i for i,k in primitives.items() if k['type'] != ALMOST_VERTICAL]
199 | horizontal_mask = np.isin(labels, horizontal_labels)
200 | points = np.asarray(pcd.points)[horizontal_mask]
201 |
202 | x_bins = np.arange(points[:,0].min(), points[:,0].max()+.125, 0.25)
203 | y_bins = np.arange(points[:,1].min(), points[:,1].max()+.125, 0.25)
204 |
205 | stat_min = binned_statistic_2d(points[:,0], points[:,1], points[:,2], 'min', bins=[x_bins, y_bins])[0]
206 | min_z = FastGridInterpolator(x_bins, y_bins, stat_min)
207 | floor_offset = points[:,2] - min_z(points)
208 |
209 | stat_max = binned_statistic_2d(points[:,0], points[:,1], points[:,2], 'max', bins=[x_bins, y_bins])[0]
210 | max_z = FastGridInterpolator(x_bins, y_bins, stat_max)
211 | ceil_offset = max_z(points) - points[:,2]
212 |
213 | for label in horizontal_labels:
214 | label_mask = labels[horizontal_mask] == label
215 | if floor_offset[label_mask].mean() > .4 and ceil_offset[label_mask].mean() > .4:
216 | labels[labels==label] = -1
217 | if label in primitives:
218 | del primitives[label]
219 |
220 | def _labels_to_primitives(self, pcd, labels, exclude_labels=[-1]):
221 | planes = {}
222 | # TODO: change to box_area
223 | rectangle_labels = [r for r in np.unique(labels) if r not in exclude_labels and np.sum(labels==r) > .3/(self.subsample_size**2)]
224 | for i in rectangle_labels:
225 | region_cloud = pcd.select_by_index(np.where(labels==i)[0])
226 | region_pts = np.asarray(region_cloud.points)
227 |
228 | # TODO: filter outliers out!
229 | a, b, c, d = region_cloud.segment_plane(distance_threshold=0.01,
230 | ransac_n=5,
231 | num_iterations=100)[0]
232 | normal = np.array([a,b,c])
233 | normal /= np.linalg.norm(normal)
234 | center = np.mean(region_pts,axis=0)
235 | slope = np.rad2deg(np.arccos(np.abs(normal[2] / 1)))
236 |
237 | # Compute bounding box
238 | if slope < 5:
239 | plane_type = ALMOST_HORIZONTAL
240 | bbox_points = math_utils.minimum_bounding_rectangle(region_pts[:,:2])[0]
241 | bbox_points = np.concatenate((bbox_points, np.full((4,1), center[2])),axis=1)
242 | else:
243 | xaxis = np.cross(normal, [0, 0, 1])
244 | yaxis = np.cross(normal, xaxis)
245 | xaxis /= np.linalg.norm(xaxis)
246 | yaxis /= np.linalg.norm(yaxis)
247 |
248 | new_x = np.dot(region_pts-center, xaxis)
249 | new_y = np.dot(region_pts-center, yaxis)
250 |
251 | xmin, ymin, xmax, ymax = math_utils.compute_bounding_box(np.vstack([new_x, new_y]).T)
252 | bbox_points = np.array([[xmin, ymin], [xmax, ymin], [xmax, ymax], [xmin, ymax]])
253 | bbox_points = center + bbox_points[:,0][:, None]*xaxis + bbox_points[:,1][:, None]*yaxis
254 | if slope > 80:
255 | plane_type = ALMOST_VERTICAL
256 | else:
257 | plane_type = SLANTED
258 |
259 | surface = bbox_area(bbox_points)
260 | line_set = o3d.geometry.LineSet(
261 | points=o3d.utility.Vector3dVector(bbox_points),
262 | lines=o3d.utility.Vector2iVector([[0, 1],[1, 2],[2, 3],[3, 0]]),
263 | )
264 |
265 | plane_object = {
266 | 'region': i,
267 | 'bbox': bbox_points,
268 | 'lineset': line_set,
269 | 'surface': surface,
270 | 'center': center,
271 | 'normal': normal,
272 | 'D': d,
273 | 'slope': slope,
274 | 'type': plane_type
275 | }
276 | planes[i] = plane_object
277 |
278 | return planes
279 |
280 | def process(self, pcd, labels):
281 | """
282 | Parameters
283 | ----------
284 | points : array of shape (n_points, 3)
285 | The point cloud of a floor.
286 |
287 | Returns
288 | -------
289 | An array of masks, where each mask represents a floor in the pointcloud.
290 | """
291 |
292 | points = np.asarray(pcd.points)
293 | logger.debug(f'detecting rooms in floor of {len(points)} points')
294 |
295 | # Classify primitives
296 | logger.debug(f'Classify primitives...')
297 | primitives = self._labels_to_primitives(pcd, labels)
298 |
299 | # Clear middle planes
300 | self._clean_mid_horizontal(pcd, labels, primitives)
301 |
302 | # Primitive adjacency classification
303 | neighbours = self._find_neighbouring_primitives(points, labels, primitives)
304 | primitive_graph = self._adjacency_graph(points, labels, primitives, neighbours)
305 | primitive_graph = self._classify_graph(primitive_graph)
306 | ceiling_nodes = [v for v in primitive_graph.nodes() if primitive_graph.nodes[v]['label']==CEILING]
307 | floor_nodes = [v for v in primitive_graph.nodes() if primitive_graph.nodes[v]['label']==FLOOR]
308 | wall_nodes = [v for v in primitive_graph.nodes() if primitive_graph.nodes[v]['label']==WALL]
309 | slantedwall_nodes = [v for v in primitive_graph.nodes() if primitive_graph.nodes[v]['label']==SLANTED_WALL]
310 | clutter_nodes = [v for v in primitive_graph.nodes() if primitive_graph.nodes[v]['label']==CLUTTER]
311 | prim_regions = wall_nodes+floor_nodes+ceiling_nodes
312 | logger.debug(f'{(len(ceiling_nodes),len(floor_nodes),len(wall_nodes),len(slantedwall_nodes),len(clutter_nodes))}')
313 |
314 | # plot
315 | pcd_group_1 = pcd.select_by_index(np.where(np.isin(labels, floor_nodes))[0])
316 | pcd_group_1 = pcd_group_1.paint_uniform_color([1.0,0.3,0.3])
317 | pcd_group_2 = pcd.select_by_index(np.where(np.isin(labels, ceiling_nodes))[0])
318 | pcd_group_2 = pcd_group_2.paint_uniform_color([0.2,0.2,1.0])
319 | pcd_group_3 = pcd.select_by_index(np.where(np.isin(labels, wall_nodes))[0])
320 | pcd_group_3 = pcd_group_3.paint_uniform_color([0.2,1.0,0.2])
321 | pcd_group_4 = pcd.select_by_index(np.where(np.isin(labels, clutter_nodes))[0])
322 | pcd_group_4 = pcd_group_4.paint_uniform_color([0,0,0])
323 | pcd_group_5 = pcd.select_by_index(np.where(np.isin(labels, slantedwall_nodes))[0])
324 | pcd_group_5 = pcd_group_5.paint_uniform_color([0,1,1])
325 | if self.plot:
326 | o3d.visualization.draw_geometries([pcd_group_1, pcd_group_2, pcd_group_3, pcd_group_4])
327 |
328 | # Detect Rooms
329 | logger.debug(f'Detect rooms...')
330 |
331 | # create grid
332 | bin_size = 0.05
333 | x_bins = np.arange(points[:,0].min()-bin_size/2,points[:,0].max()+bin_size,bin_size)
334 | y_bins = np.arange(points[:,1].min()-bin_size/2,points[:,1].max()+bin_size,bin_size)
335 | origin = [x_bins[0]+bin_size/2,y_bins[0]-bin_size/2]
336 |
337 | # Create projection
338 | walls = np.zeros((len(x_bins)-1,len(y_bins)-1))
339 | for i,r in primitives.items():
340 | if i in wall_nodes:
341 | length = np.linalg.norm(r['bbox'][0,:2]-r['bbox'][1,:2])
342 | line = np.linspace(r['bbox'][0,:2],r['bbox'][1,:2], int(length*20))
343 | walls += np.histogram2d(line[:,0],line[:,1],[x_bins, y_bins])[0]
344 | walls = walls>0
345 | walls = binary_dilation(walls, structure=generate_binary_structure(2, 2), iterations=3, border_value=1)
346 | walls = binary_erosion(walls, structure=generate_binary_structure(2, 2), iterations=2)
347 | ceiling_mask = np.isin(labels, ceiling_nodes + floor_nodes)
348 | projection, xedges, yedges = np.histogram2d(points[ceiling_mask,0], points[ceiling_mask,1], bins=[x_bins,y_bins])
349 | projection = binary_closing(projection!=0, np.ones((3,3)), iterations=2)
350 | projection = np.logical_or(~projection,walls)
351 | if self.plot:
352 | plt.figure(figsize=(6, 6))
353 | plt.subplot(111)
354 | plt.imshow(projection.T)
355 | plt.axis('off')
356 |
357 | # Get room polygons
358 | room_polys = self._get_rooms(projection, origin, bin_size)
359 |
360 | room_mask = np.zeros((len(points),len(room_polys)), dtype=bool)
361 | for i, item in enumerate(room_polys):
362 | room_poly = item[0]
363 | clip_mask = clip_utils.poly_clip(points, room_poly.buffer(0.2))
364 |
365 | search = binary_dilation(binary_erosion(item[1]) ^ binary_dilation(item[1]), iterations=4)
366 | wall_mask = clip_mask & np.isin(labels, wall_nodes)
367 | walls = np.histogram2d(points[wall_mask,0],points[wall_mask,1],[x_bins, y_bins])[0]>0
368 | walls_dil = binary_dilation(walls, iterations=6)
369 | search[walls_dil] = False
370 |
371 | # Add missing walls
372 | outside_primitives = [i for i in np.unique(labels[clip_mask]) if i in clutter_nodes]
373 | track = walls.astype(int)
374 | news = []
375 | for label in outside_primitives:
376 | label_mask = (labels==label) & clip_mask
377 | label_grid = np.histogram2d(points[label_mask,0],points[label_mask,1],[x_bins, y_bins])[0]>0
378 | if search[label_grid].sum() > 10:
379 | track[label_grid] = 2
380 | news.append(label)
381 | wall_nodes.append(label)
382 | clutter_nodes.remove(label)
383 |
384 | # Clean inside walls
385 | # TODO: delete all points?
386 | room_inside = binary_erosion(item[1], iterations=6)
387 | room_primitives = [i for i in np.unique(labels[clip_mask]) if i in wall_nodes]
388 | track = room_inside.astype(int)
389 | inside = []
390 | for label in room_primitives:
391 | label_mask = (labels==label) & clip_mask
392 | label_grid = np.histogram2d(points[label_mask,0],points[label_mask,1],[x_bins, y_bins])[0]>0
393 | if label_grid[~room_inside].sum() == 0:
394 | track[label_grid] = 2
395 | inside.append(label)
396 | clutter_nodes.append(label)
397 | wall_nodes.remove(label)
398 |
399 | prim_regions = wall_nodes+floor_nodes+ceiling_nodes
400 | room_mask[:,i] = clip_mask & np.isin(labels, prim_regions)
401 |
402 | return room_mask, labels #, room_polys, (wall_nodes,floor_nodes,ceiling_nodes)
403 |
404 | def bbox_area(bbox):
405 | return np.linalg.norm(bbox[0,:]-bbox[1,:]) * np.linalg.norm(bbox[2,:]-bbox[1,:])
406 |
--------------------------------------------------------------------------------
/ipcp/modules/room_reconstruct.py:
--------------------------------------------------------------------------------
1 | """room_reconstruct Module"""
2 | import numpy as np
3 | import logging
4 | import os
5 |
6 | import subprocess
7 | import pymeshlab
8 | from pathlib import Path
9 | import src.utils.pcd_utils as pcd_utils
10 | import open3d as o3d
11 | import time
12 | import shutil
13 |
14 | logger = logging.getLogger(__name__)
15 |
16 | ALMOST_HORIZONTAL = 3
17 |
18 | class RoomReconstructor:
19 | """
20 | PlaneReconstruct class for the reconstruction of a point cloud
21 | to a mesh.
22 |
23 | Parameters
24 | ----------
25 | fitting : float (default=0.25)
26 | The fitting parameter for PolyFit.
27 | coverage : float (default=0.45)
28 | The coverage parameter for PolyFit.
29 | complexity : float (default=0.60)
30 | The complexity parameter for PolyFit.
31 | """
32 |
33 | def __init__(self, exe_ransac_polyfiy, exe_polyfit, fitting=0.5, coverage=0.27,
34 | complexity=0.23):
35 | self.exe_ransac_polyfiy = exe_ransac_polyfiy
36 | self.exe_polyfit = exe_polyfit
37 | self.fitting = fitting
38 | self.coverage = coverage
39 | self.complexity = complexity
40 |
41 | def _clean_mesh(self, meshset):
42 | meshset.meshing_remove_duplicate_vertices()
43 | meshset.meshing_merge_close_vertices()
44 | meshset.meshing_re_orient_faces_coherentely()
45 | volume = meshset.get_geometric_measures()['mesh_volume']
46 | if volume < 0:
47 | meshset.meshing_invert_face_orientation()
48 | volume = meshset.get_geometric_measures()['mesh_volume']
49 |
50 | return meshset
51 |
52 | def _add_missing(self, points, labels, primitives):
53 | horizontal_z = [points[labels==l,2].min() for l in np.unique(labels) if l in primitives.keys() and primitives[l]['type'] == ALMOST_HORIZONTAL]
54 | if len(horizontal_z) == 0 or np.min(horizontal_z) - points[:,2].min() > 0.75:
55 | logger.info("No floor, create")
56 | bin_size = 0.15
57 | x_bins = np.arange(points[:,0].min(),points[:,0].max(),bin_size)
58 | y_bins = np.arange(points[:,1].min(),points[:,1].max(),bin_size)
59 | projection, xedges, yedges = np.histogram2d(points[:,0], points[:,1], bins=(x_bins, y_bins))
60 | coords = np.where(projection>0)
61 | coords = np.vstack([xedges[coords[0]], yedges[coords[1]], np.full(len(coords[0]), points[:,2].min())]).T
62 | points = np.append(points, coords, axis=0)
63 | labels = np.append(labels, np.full(len(coords), labels.max()+1))
64 |
65 | return points, labels
66 |
67 | def _ransac_polyfit(self, pcd):
68 |
69 | meshset = None
70 | try:
71 | # Write file
72 | logger.debug(f'Write temp file to {self.ply_infile}')
73 | pcd = o3d.t.geometry.PointCloud(pcd.point['positions'])
74 | o3d.t.io.write_point_cloud(self.ply_infile, pcd, write_ascii=True)
75 |
76 | logger.debug(f'Run PolyFit')
77 | subprocess.run([self.exe_ransac_polyfiy, self.ply_infile, self.dir_path,'0.01','100','0.1','1.5','0.6','0.5','0.27','0.23'],
78 | timeout=10, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
79 |
80 | meshset = pymeshlab.MeshSet()
81 | meshset.load_new_mesh(self.mesh_outfile)
82 | meshset = self._clean_mesh(meshset)
83 |
84 | logger.debug('Succes.')
85 |
86 | except subprocess.TimeoutExpired:
87 | logger.debug('Ployfit timeout')
88 | except subprocess.CalledProcessError as CPE:
89 | logger.debug(f'Error in Ployfit with returncode {CPE.returncode}.')
90 | except Exception as e:
91 | logger.debug('Hai', str(e))
92 |
93 | return meshset
94 |
95 | def _user_polyfit(self, pcd):
96 |
97 | meshset = None
98 |
99 | try:
100 | # Write file
101 | logger.debug(f'Write temp file to {self.ply_infile}')
102 | o3d.t.io.write_point_cloud(self.ply_infile, pcd, write_ascii=True)
103 |
104 | logger.debug(f'Run PolyFit')
105 |
106 | subprocess.run([self.exe_polyfit, self.ply_infile, self.dir_path,
107 | str(self.fitting), str(self.coverage),
108 | str(self.complexity)], timeout=15,
109 | check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
110 |
111 | meshset = pymeshlab.MeshSet()
112 | meshset.load_new_mesh(self.mesh_outfile)
113 | meshset = self._clean_mesh(meshset)
114 |
115 | logger.debug('Succes.')
116 |
117 | except:
118 | meshset = self._ransac_polyfit(pcd)
119 |
120 | return meshset
121 |
122 | def process(self, points, primitive_index, primitives):
123 | """
124 | Parameters
125 | ----------
126 | points : array of shape (n_points, 3)
127 | The point cloud of a room to reconsturct.
128 |
129 | Returns
130 | -------
131 | mesh : MeshSet
132 | The volume of the input mesh.
133 | """
134 | logger.debug(f'Room reconstruction for pointcloud of {len(points)} points and {len(np.unique(primitive_index))} faces')
135 |
136 | meshset = None
137 |
138 | self.dir_path = './tmp_pr'
139 | self.ply_infile = self.dir_path + '/polyfit_input.ply'
140 | self.mesh_outfile = self.dir_path + '/polyfit_result.obj'
141 | if not os.path.isdir(self.dir_path):
142 | os.mkdir(self.dir_path)
143 |
144 | # points, primitive_index = self._add_missing(points, primitive_index, primitives)
145 |
146 | pcd = o3d.t.geometry.PointCloud(o3d.core.Tensor(points, o3d.core.float32))
147 | segment_index = np.unique(primitive_index, return_inverse=True)[1][:,np.newaxis]
148 | pcd.point['segment_index'] = o3d.core.Tensor(segment_index, o3d.core.int32)
149 |
150 | if len(points) > 20000:
151 | pcd = pcd.voxel_down_sample(0.1)
152 |
153 | meshset = self._user_polyfit(pcd)
154 |
155 | shutil.rmtree('./tmp_pr')
156 |
157 | return meshset
158 |
--------------------------------------------------------------------------------
/ipcp/notebooks/Complete Pipeline.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": null,
6 | "metadata": {},
7 | "outputs": [],
8 | "source": [
9 | "import sys\n",
10 | "sys.path.append('../')"
11 | ]
12 | },
13 | {
14 | "cell_type": "code",
15 | "execution_count": null,
16 | "metadata": {},
17 | "outputs": [],
18 | "source": [
19 | "import numpy as np\n",
20 | "import open3d as o3d\n",
21 | "import time\n",
22 | "import logging\n",
23 | "from tqdm import tqdm\n",
24 | "import pymeshlab\n",
25 | "import matplotlib.pyplot as plt\n",
26 | "\n",
27 | "from src.utils import pcd_utils\n",
28 | "from src.utils import cityjson_utils\n",
29 | "from src.utils import log_utils\n",
30 | "from src.utils import plot_utils\n",
31 | "\n",
32 | "from preprocessors.sor import SOR\n",
33 | "from preprocessors.spatial_subsample import SpatialSubsample\n",
34 | "from modules.floor_split import FloorSplitter\n",
35 | "from modules.room_detection import RoomDetector\n",
36 | "from modules.primitive_detection import PrimitiveDetector\n",
37 | "from modules.room_reconstruct import RoomReconstructor\n",
38 | "from modules.mesh_stats import MeshAnalyser"
39 | ]
40 | },
41 | {
42 | "cell_type": "markdown",
43 | "metadata": {},
44 | "source": [
45 | "#### Load the interior PointCloud"
46 | ]
47 | },
48 | {
49 | "cell_type": "code",
50 | "execution_count": null,
51 | "metadata": {},
52 | "outputs": [],
53 | "source": [
54 | "in_file = '../datasets/apt_subsampled.ply'"
55 | ]
56 | },
57 | {
58 | "cell_type": "code",
59 | "execution_count": null,
60 | "metadata": {},
61 | "outputs": [],
62 | "source": [
63 | "pcd = pcd_utils.read_pointcloud(in_file)\n",
64 | "len(pcd.points)"
65 | ]
66 | },
67 | {
68 | "cell_type": "markdown",
69 | "metadata": {},
70 | "source": [
71 | "#### 1. Preprocessing"
72 | ]
73 | },
74 | {
75 | "cell_type": "code",
76 | "execution_count": null,
77 | "metadata": {},
78 | "outputs": [],
79 | "source": [
80 | "ss = SpatialSubsample(min_distance=0.03)\n",
81 | "sor = SOR(knn=6, n_sigma=2)\n",
82 | "\n",
83 | "preprocessors = [ss, sor]\n",
84 | "\n",
85 | "for obj in preprocessors:\n",
86 | " start = time.time()\n",
87 | " pcd = obj.process(pcd)\n",
88 | " duration = time.time() - start\n",
89 | " print(f'Processor finished in {duration:.2f}s, {len(pcd.points)} points.') "
90 | ]
91 | },
92 | {
93 | "cell_type": "markdown",
94 | "metadata": {},
95 | "source": [
96 | "#### 2. Primitive Detection"
97 | ]
98 | },
99 | {
100 | "cell_type": "code",
101 | "execution_count": null,
102 | "metadata": {},
103 | "outputs": [],
104 | "source": [
105 | "ransac_exe_path = '../cpp_modules/efficient_ransac'\n",
106 | "primitive_detector = PrimitiveDetector(ransac_exe_path)\n",
107 | "\n",
108 | "pcd, primitives, primitive_labels = primitive_detector.process(pcd)"
109 | ]
110 | },
111 | {
112 | "cell_type": "code",
113 | "execution_count": null,
114 | "metadata": {},
115 | "outputs": [],
116 | "source": [
117 | "## Comment line when running as docker\n",
118 | "# plot_utils.show_pcd(pcd, primitive_labels)"
119 | ]
120 | },
121 | {
122 | "cell_type": "markdown",
123 | "metadata": {},
124 | "source": [
125 | "#### 3. Detect Floors"
126 | ]
127 | },
128 | {
129 | "cell_type": "code",
130 | "execution_count": null,
131 | "metadata": {},
132 | "outputs": [],
133 | "source": [
134 | "floor_splitter = FloorSplitter()\n",
135 | "floors = floor_splitter.process(pcd, primitive_labels, primitives)\n",
136 | "\n",
137 | "print(f'Done. Detected {len(floors)} floors.')"
138 | ]
139 | },
140 | {
141 | "cell_type": "code",
142 | "execution_count": null,
143 | "metadata": {},
144 | "outputs": [],
145 | "source": [
146 | "## Comment line when running as docker\n",
147 | "# plot_utils.show_pcd_floors(pcd, floors)"
148 | ]
149 | },
150 | {
151 | "cell_type": "markdown",
152 | "metadata": {},
153 | "source": [
154 | "#### 4. Room Detection"
155 | ]
156 | },
157 | {
158 | "cell_type": "code",
159 | "execution_count": null,
160 | "metadata": {},
161 | "outputs": [],
162 | "source": [
163 | "room_detector = RoomDetector(plot=False)\n",
164 | "\n",
165 | "rooms = []\n",
166 | "for floor_mask in floors:\n",
167 | " floor_pcd = pcd.select_by_index(np.where(floor_mask)[0])\n",
168 | " floor_labels = primitive_labels[floor_mask]\n",
169 | " floor_rooms, floor_labels = room_detector.process(floor_pcd, floor_labels)\n",
170 | " primitive_labels[floor_mask] = floor_labels\n",
171 | " for room_i in range(floor_rooms.shape[1]):\n",
172 | " room_mask = np.zeros(len(pcd.points), dtype=bool)\n",
173 | " room_mask[floor_mask] = floor_rooms[:,room_i]\n",
174 | " rooms.append(room_mask)\n",
175 | " \n",
176 | "print(f'Done. Detected {len(rooms)} rooms.')"
177 | ]
178 | },
179 | {
180 | "cell_type": "markdown",
181 | "metadata": {},
182 | "source": [
183 | "#### 5. Room Reconstruction"
184 | ]
185 | },
186 | {
187 | "cell_type": "code",
188 | "execution_count": null,
189 | "metadata": {},
190 | "outputs": [],
191 | "source": [
192 | "room_reconstructor = RoomReconstructor('../cpp_modules/polyfit_ransac', '../cpp_modules/polyfit')\n",
193 | "\n",
194 | "room_meshes = []\n",
195 | "failed = []\n",
196 | "for i in tqdm(np.arange(len(rooms))):\n",
197 | " room_mask = rooms[i]\n",
198 | " room_pts = np.asarray(pcd.points)[room_mask]\n",
199 | "\n",
200 | " meshset = room_reconstructor.process(room_pts, primitive_labels[room_mask], primitives)\n",
201 | " if meshset is None:\n",
202 | " failed.append(i)\n",
203 | " else:\n",
204 | " room_meshes.append(meshset)\n",
205 | "\n",
206 | "if len(failed) > 0: \n",
207 | " print(f'Failed to reconstruct rooms {failed}')"
208 | ]
209 | },
210 | {
211 | "cell_type": "markdown",
212 | "metadata": {},
213 | "source": [
214 | "#### 6. CityJSON Export"
215 | ]
216 | },
217 | {
218 | "cell_type": "code",
219 | "execution_count": null,
220 | "metadata": {},
221 | "outputs": [],
222 | "source": [
223 | "out_path = '../datasets/output.city.json'\n",
224 | "\n",
225 | "cityjson = cityjson_utils.to_cityjson_v1(room_meshes)\n",
226 | "cityjson_utils.save_to_file(cityjson, out_path)"
227 | ]
228 | },
229 | {
230 | "cell_type": "markdown",
231 | "metadata": {},
232 | "source": [
233 | "#### 7. Room Statistics"
234 | ]
235 | },
236 | {
237 | "cell_type": "code",
238 | "execution_count": null,
239 | "metadata": {},
240 | "outputs": [],
241 | "source": [
242 | "mesh_analyser = MeshAnalyser() \n",
243 | "\n",
244 | "for i in range(len(room_meshes)):\n",
245 | " room_mesh = room_meshes[i]\n",
246 | " volume, floorarea = mesh_analyser.process(room_mesh)\n",
247 | " try: \n",
248 | " print(f'Room {i}: {volume:.2f}, {floorarea:.2f}')\n",
249 | " except:\n",
250 | " print(f'Room {i} analysis failed.')"
251 | ]
252 | },
253 | {
254 | "cell_type": "code",
255 | "execution_count": null,
256 | "metadata": {},
257 | "outputs": [],
258 | "source": []
259 | }
260 | ],
261 | "metadata": {
262 | "kernelspec": {
263 | "display_name": "Python 3 (ipykernel)",
264 | "language": "python",
265 | "name": "python3"
266 | },
267 | "language_info": {
268 | "codemirror_mode": {
269 | "name": "ipython",
270 | "version": 3
271 | },
272 | "file_extension": ".py",
273 | "mimetype": "text/x-python",
274 | "name": "python",
275 | "nbconvert_exporter": "python",
276 | "pygments_lexer": "ipython3",
277 | "version": "3.8.10"
278 | },
279 | "vscode": {
280 | "interpreter": {
281 | "hash": "f57f7d9456f5b7dc730d015ec7d854ad65788762049c2fb9123860f88d8941f7"
282 | }
283 | }
284 | },
285 | "nbformat": 4,
286 | "nbformat_minor": 2
287 | }
288 |
--------------------------------------------------------------------------------
/ipcp/preprocessors/__intit__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Amsterdam-AI-Team/Indoor-PointCloud-to-CityJSON/fefcbbc201721e34d00f9fb432671028c64c2e3f/ipcp/preprocessors/__intit__.py
--------------------------------------------------------------------------------
/ipcp/preprocessors/sor.py:
--------------------------------------------------------------------------------
1 | """Statistical Outlier Removal Preprocessor"""
2 | import numpy as np
3 | import logging
4 | import open3d as o3d
5 |
6 | logger = logging.getLogger(__name__)
7 |
8 | class SOR:
9 | """
10 | Preprocessor class for the statistical outlier removal of pointcloud data.
11 | It computes first the average distance of each point to its neighbors.
12 | Then it rejects the points that are farther than the average distance plus
13 | a number of times the standard deviation (the max distance will be:
14 | average distance + n * standard deviation).
15 |
16 | Parameters
17 | ----------
18 | knn : int (default=6)
19 | The number of neighbours that will be used to compute
20 | the 'mean distance to neighbors' for each point.
21 | n_sigma : float (default=1.0)
22 | The standard deviation.
23 | """
24 |
25 | def __init__(self, knn=6, n_sigma=1.0):
26 | """ Init variables """
27 | self.knn = knn
28 | self.n_sigma = n_sigma
29 |
30 | def process(self, pcd):
31 | """
32 | Parameters
33 | ----------
34 | points : array of shape (n_points, 3)
35 | The point cloud .
36 | """
37 |
38 | logger.info(f'Removing outliers...')
39 |
40 | refCloud, _ = pcd.remove_statistical_outlier(nb_neighbors=self.knn, std_ratio=self.n_sigma)
41 | return refCloud
42 |
--------------------------------------------------------------------------------
/ipcp/preprocessors/spatial_subsample.py:
--------------------------------------------------------------------------------
1 | """Spatial Subsample Preprocessor"""
2 | import numpy as np
3 | import logging
4 | import open3d as o3d
5 |
6 | logger = logging.getLogger(__name__)
7 |
8 | class SpatialSubsample:
9 | """
10 | Preprocessor class for the subsampling of pointcloud data.
11 | The class reduce the number of points in the pointcloud using spatial.
12 |
13 | Parameters
14 | ----------
15 | min_distance : float (default=0.05)
16 | The minimal space between points.
17 | """
18 |
19 | def __init__(self, min_distance=0.05):
20 | """ Init variables """
21 | self.min_distance = min_distance
22 |
23 | def process(self, pcd):
24 | """
25 | Parameters
26 | ----------
27 | points : array of shape (n_points, 3)
28 | The point cloud .
29 | """
30 |
31 | logger.info(f'Reducing pointcloud...')
32 |
33 | refCloud = pcd.voxel_down_sample(self.min_distance)
34 |
35 | return refCloud
36 |
--------------------------------------------------------------------------------
/ipcp/script.py:
--------------------------------------------------------------------------------
1 | import argparse
2 | import os
3 | import sys
4 |
5 | from src.pipeline import Pipeline
6 | from preprocessors.sor import SOR
7 | from preprocessors.spatial_subsample import SpatialSubsample
8 | from modules.primitive_detection import PrimitiveDetector
9 | from modules.floor_split import FloorSplitter
10 | from modules.room_detection import RoomDetector
11 | from modules.room_reconstruct import RoomReconstructor
12 | from modules.mesh_stats import MeshAnalyser
13 |
14 | ransac_exe = './cpp_modules/efficient_ransac'
15 | reconstruct_exe = './cpp_modules/polyfit'
16 | reconstruct_ransac_exe = './cpp_modules/polyfit_ransac'
17 |
18 | def main(in_file, out_folder):
19 | sor = SOR()
20 | ss = SpatialSubsample()
21 | primitive_detector = PrimitiveDetector(ransac_exe)
22 | floor_splitter = FloorSplitter()
23 | room_detector = RoomDetector()
24 | room_reconstructor = RoomReconstructor(reconstruct_ransac_exe, reconstruct_exe)
25 | mesh_analyser = MeshAnalyser()
26 |
27 | pipeline = Pipeline(primitive_detector, floor_splitter, room_detector, room_reconstructor, mesh_analyser, preprocessors=[ss,sor])
28 |
29 | pipeline.process_file(in_file, out_folder)
30 |
31 | if __name__ == "__main__":
32 | global args
33 |
34 | desc_str = '''This script provides room reconstruction for indoor point clouds.'''
35 | parser = argparse.ArgumentParser(description=desc_str)
36 |
37 | parser.add_argument('--in_file', metavar='path', action='store',
38 | type=str, required=True)
39 | parser.add_argument('--out_folder', metavar='path', action='store',
40 | type=str, required=False)
41 | args = parser.parse_args()
42 |
43 | main(args.in_file, args.out_folder)
--------------------------------------------------------------------------------
/ipcp/src/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Amsterdam-AI-Team/Indoor-PointCloud-to-CityJSON/fefcbbc201721e34d00f9fb432671028c64c2e3f/ipcp/src/__init__.py
--------------------------------------------------------------------------------
/ipcp/src/interpolation.py:
--------------------------------------------------------------------------------
1 | """
2 | This module provides tools for interpolating data.
3 | """
4 |
5 | import numpy as np
6 |
7 | class FastGridInterpolator:
8 | """
9 | Class to perform fast interpolation using gridded data. The interpolator
10 | simply returns the values of the grid cells in which the queried points
11 | fall. Grid coordinates are assumed to be the centroids of each grid cell.
12 |
13 | Parameters
14 | ----------
15 | bin_x : list or array-like
16 | The x-coordinates of the grid (ascending).
17 |
18 | bin_y : list or array-like
19 | The y-coordinates of the grid (decsending).
20 |
21 | values : array of shape (Ny, Nx)
22 | The values of the gridded data.
23 | """
24 |
25 | def __init__(self, bin_x, bin_y, values):
26 | self.bin_x = bin_x[:-1]
27 | self.bin_y = bin_y[:-1]
28 | self.values = values
29 |
30 | def __call__(self, positions):
31 | """
32 | Evaluate the interpolator at the given positions.
33 |
34 | Parameters
35 | ----------
36 | positions : array of shape (Np, 2)
37 | Array of points to query. The first column contains the x-values,
38 | the second column contains the y-values.
39 | """
40 | x_idx = np.digitize(positions[:, 0], self.bin_x) - 1
41 | y_idx = np.digitize(positions[:, 1], self.bin_y) - 1
42 | return self.values[x_idx, y_idx]
--------------------------------------------------------------------------------
/ipcp/src/pipeline.py:
--------------------------------------------------------------------------------
1 | """Room Reconstruction Pipeline"""
2 |
3 | import os
4 | import pathlib
5 | import time
6 | import logging
7 | import gc
8 | import pymeshlab
9 | import numpy as np
10 | import open3d as o3d
11 | from tqdm import tqdm
12 |
13 | from .utils import cityjson_utils
14 | from .utils import pcd_utils
15 |
16 | logger = logging.getLogger(__name__)
17 |
18 |
19 | class Pipeline:
20 | """
21 | Pipeline for room reconstruction. The class processes a single point cloud
22 | or a folder of pointclouds by applying the given modules consecutively.
23 |
24 | Parameters
25 | ----------
26 | floor_splitter : FloorSplitter
27 | The module that splits the point cloud into separate floors
28 | room_detector : RoomDetector
29 | The module that detects rooms within a single floor.
30 | surface_reconstructor : SurfaceReconstructor
31 | The module that reconstructs the surface to a mesh.
32 | mesh_volume : MeshVolume
33 | The module that computes the area and volume of a mesh.
34 | preprocessors : iterable of type PreProcessor
35 | The preprocessors to apply, in order.
36 | """
37 |
38 | FILE_TYPES = ('.LAS', '.las', '.LAZ', '.laz', '.ply')
39 |
40 | def __init__(self, primitive_detector, floor_splitter, room_detector,
41 | room_reconstructor, mesh_analyser, preprocessors=[]):
42 | if len(preprocessors) == 0:
43 | logger.info('No preprocessors specified.')
44 | self.preprocessors = preprocessors
45 | self.primitive_detector = primitive_detector
46 | self.floor_splitter = floor_splitter
47 | self.room_detector = room_detector
48 | self.room_reconstructor = room_reconstructor
49 | self.mesh_analyser = mesh_analyser
50 |
51 | def _process_cloud(self, pcd):
52 | """
53 | Process a single point cloud.
54 |
55 | Parameters
56 | ----------
57 | points : array of shape (n_points, 3)
58 | The point cloud .
59 |
60 | Returns
61 | -------
62 | An cityJSON object representing the indoor of a building.
63 | """
64 |
65 |
66 |
67 | # 1. Preprocess pointcloud
68 | logger.info(f'Preprocessing...')
69 | for obj in self.preprocessors:
70 | start = time.time()
71 | pcd = obj.process(pcd)
72 | duration = time.time() - start
73 | logger.info(f'Processor finished in {duration:.2f}s, ' +
74 | f'{len(pcd.points)} points.')
75 | gc.collect()
76 |
77 |
78 | # 2. Primitive Detection
79 | start = time.time()
80 | logger.info(f'Detecting primitives...')
81 | pcd, primitives, primitive_labels = self.primitive_detector.process(pcd)
82 | duration = time.time() - start
83 | logger.info(f'Done. Detected {len(primitives.keys())}. {duration:.2f}s')
84 | gc.collect()
85 |
86 | # 3. Detect floors
87 | start = time.time()
88 | logger.info(f'Detecting floors...')
89 | floors = self.floor_splitter.process(pcd, primitive_labels, primitives)
90 | duration = time.time() - start
91 | logger.info(f'Done. Detected {len(floors)} floors. {duration:.2f}s')
92 | gc.collect()
93 |
94 | # 4. Detect Rooms
95 | start = time.time()
96 | logger.info(f'Detecting rooms...')
97 | rooms = []
98 | for floor_mask in floors:
99 | floor_pcd = pcd.select_by_index(np.where(floor_mask)[0])
100 | floor_labels = primitive_labels[floor_mask]
101 | floor_rooms, _ = self.room_detector.process(floor_pcd, floor_labels)
102 | for room_i in range(floor_rooms.shape[1]):
103 | room_mask = np.zeros(len(pcd.points), dtype=bool)
104 | room_mask[floor_mask] = floor_rooms[:,room_i]
105 | rooms.append(room_mask)
106 | gc.collect()
107 | duration = time.time() - start
108 | logger.info(f'Done. Detected {len(rooms)} rooms. {duration:.2f}s')
109 |
110 | # 5. Reconstruct rooms
111 | start = time.time()
112 | logger.info(f'Reconstructing rooms into meshes...')
113 | room_meshes = []
114 | for room_mask in tqdm(rooms):
115 | meshset = self.room_reconstructor.process(np.asarray(pcd.points)[room_mask], primitive_labels[room_mask], primitives)
116 | if meshset is not None:
117 | room_meshes.append(meshset)
118 | gc.collect()
119 | duration = time.time() - start
120 | logger.info(f'Done. Succesfully reconstructed {len(room_meshes)}/{len(rooms)} rooms. {duration:.2f}s')
121 |
122 | # 6. Convert CityJSON
123 | cityjson = cityjson_utils.to_cityjson_v1(room_meshes)
124 |
125 | # 7. Compute Area and Volume
126 | start = time.time()
127 | logger.info(f'Computing mesh metrics')
128 | room_stats = []
129 | for i, room_mesh in enumerate(room_meshes):
130 | volume, floorarea = self.mesh_analyser.process(room_mesh)
131 | room_stats.append((volume, floorarea))
132 | logger.debug(f'volume room {i}: {volume}, floorarea: {floorarea}')
133 | duration = time.time() - start
134 | logger.info(f'Done. {duration:.2f}s')
135 |
136 | return cityjson, room_stats
137 |
138 | def process_file(self, in_file, out_folder=None, out_prefix=''):
139 | """
140 | Process a single LAS file and save the result as .laz file.
141 |
142 | Parameters
143 | ----------
144 | in_file : str
145 | The file to process.
146 | out_file : str (default: None)
147 | The name of the output file. If None, the input will be
148 | overwritten.
149 | """
150 | logger.info(f'Processing file {in_file}.')
151 | start = time.time()
152 | if not os.path.isfile(in_file):
153 | logger.error('The input file specified does not exist')
154 | return None
155 | elif not in_file.endswith(self.FILE_TYPES):
156 | logger.error('The input file specified has the wrong format')
157 | return None
158 |
159 | filename = pathlib.Path(in_file).stem
160 | outputname = out_prefix + filename
161 | in_folder = os.path.dirname(in_file)
162 | if out_folder is None:
163 | out_folder = in_folder
164 | else:
165 | pathlib.Path(out_folder).mkdir(parents=True, exist_ok=True)
166 | out_path = out_folder + '/' + outputname + '.city.json'
167 |
168 | pcd = pcd_utils.read_pointcloud(in_file)
169 |
170 | citysjon, room_stats = self._process_cloud(pcd)
171 | cityjson_utils.save_to_file(citysjon, out_path)
172 |
173 | # write stats
174 | lines = []
175 | for i, stats in enumerate(room_stats):
176 | line = 'Room ' + str(i) + ': volume='+str(stats[0])+', surface='+str(stats[1])+'\n'
177 | lines.append(line)
178 | stats_path = out_folder + '/' + outputname + '_stats.txt'
179 | with open(stats_path, 'w') as f:
180 | f.writelines(lines)
181 |
182 | duration = time.time() - start
183 | # stats = analysis_tools.get_label_stats(labels)
184 | # logger.info('STATISTICS\n' + stats)
185 | logger.info(f'File processed in {duration:.2f}s, ' +
186 | f'output written to {out_path}.\n' + '='*20)
187 |
--------------------------------------------------------------------------------
/ipcp/src/region_growing.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import open3d as o3d
3 | import copy
4 | import logging
5 | import time
6 | from tqdm import tqdm
7 | from tqdm.contrib.logging import logging_redirect_tqdm
8 |
9 | from scipy.spatial import KDTree
10 |
11 | import warnings
12 |
13 | warnings.filterwarnings('error')
14 |
15 | from scipy import spatial
16 |
17 | logger = logging.getLogger(__name__)
18 |
19 |
20 | class RegionGrowing:
21 | """
22 | Region growing implementation based on:
23 | https://pcl.readthedocs.io/projects/tutorials/en/latest/region_growing_segmentation.html
24 | """
25 | def __init__(self):
26 | """ Init variables. """
27 |
28 | def _ransac_plane_fit(self, pcd):
29 | plane_model, _ = pcd.segment_plane(distance_threshold=0.01,
30 | ransac_n=5,
31 | num_iterations=100)
32 | [a, b, c, d] = plane_model
33 | normal = np.array([a,b,c])
34 | normal /= np.linalg.norm(normal)
35 | center, _ = pcd.compute_mean_and_covariance()
36 | return normal, center
37 |
38 | def _growing_neighbours(self, tree, points, radius=.2):
39 | return flatten(tree.query_ball_point(points, r=radius))
40 |
41 | def _region_growing(self, pcd, regions, exclude=[-1], max_iter=2):
42 | """
43 | The work of this region growing algorithm is based on the comparison
44 | of the angles between the points normals.
45 |
46 | The same can also be performed in Python using scipy.spatial.cKDTree
47 | with query_ball_tree or query.
48 | """
49 |
50 | regions_to_grow = np.unique(regions)
51 | regions_to_grow = regions_to_grow[~np.isin(regions_to_grow, exclude)]
52 | regions_to_grow = np.sort(regions_to_grow)
53 |
54 | unassigned_mask = regions == -1
55 | conv = np.where(unassigned_mask)[0]
56 |
57 | P = np.asarray(pcd.points)
58 | N = np.asarray(pcd.normals)
59 | tree = KDTree(P[unassigned_mask])
60 |
61 | for region_label in tqdm(regions_to_grow):
62 | R = np.where(regions==region_label)[0] # Region
63 | F = R.tolist() # Front
64 | if len(F) < 5:
65 | continue
66 |
67 | pcd_ = pcd.select_by_index(np.where(regions==region_label)[0])
68 | n, c = self._ransac_plane_fit(pcd_) # Normal & Center
69 |
70 | i = 0
71 | while len(F) > 0 and i < max_iter:
72 | i += 1
73 | try:
74 | k_idx = conv[self._growing_neighbours(tree, P[F], .2)]
75 | F = k_idx[~np.isin(k_idx, R)] # remove points in R and grown
76 | F = F[np.rad2deg(np.arccos(np.abs(np.clip(np.dot(N[F], n),-1.0,1.0)))) < 25] # normal criterium
77 | F = F[np.abs(np.dot(P[F] - c, n)) < 0.06] # distance criterium
78 | R = np.append(R, F)
79 | except:
80 | F = []
81 | regions[R] = region_label
82 |
83 | logger.debug(f'Done. Added {np.sum(regions[conv]!=-1)} points.')
84 |
85 | return regions
86 |
87 |
88 | def _edge_refinement(self, pcd, regions):
89 | logger.debug('Refine edges ...')
90 | P = np.asarray(pcd.points)
91 | start = time.time()
92 | assigned_mask = regions >= 0
93 | assigned_tree = KDTree(P[assigned_mask])
94 |
95 | d, idx = assigned_tree.query(P[~assigned_mask], k=1, distance_upper_bound=0.25)
96 | unassigned_regions = np.full(np.sum(~assigned_mask),-1)
97 |
98 | idx_unassigned = np.where(idx0)} points. {round(time.time()-start,2)}\n")
110 |
111 | return regions
112 |
113 | def process(self, pcd, labels):
114 | """
115 | Returns the label mask for the given pointcloud.
116 |
117 | Parameters
118 | ----------
119 | points : array of shape (n_points, 3)
120 | The point cloud .
121 |
122 | Returns
123 | -------
124 | An array of shape (n_points,) with dtype=bool indicating which points
125 | should be labelled according to this fuser.
126 | """
127 | logger.debug('KDTree based Region Growing.')
128 |
129 | grown_labels = np.copy(labels)
130 |
131 | grown_labels = self._region_growing(pcd, grown_labels)
132 | grown_labels = self._edge_refinement(pcd, grown_labels)
133 |
134 | return grown_labels
135 |
136 | def flatten(l):
137 | return np.unique([j for i in l for j in i])
138 |
139 | def detection_prob(n, s, N, k=1):
140 | return 1 - np.power(1 - np.power((n/N),k),s)
141 |
--------------------------------------------------------------------------------
/ipcp/src/utils/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Amsterdam-AI-Team/Indoor-PointCloud-to-CityJSON/fefcbbc201721e34d00f9fb432671028c64c2e3f/ipcp/src/utils/__init__.py
--------------------------------------------------------------------------------
/ipcp/src/utils/cityjson_utils.py:
--------------------------------------------------------------------------------
1 | """
2 | CityJSON tools for polygon meshes.
3 |
4 | The documentation of CityJSON can be found here:
5 | https://www.cityjson.org/
6 | """
7 | import os
8 | import json
9 | import logging
10 | import numpy as np
11 |
12 |
13 | logger = logging.getLogger(__name__)
14 |
15 | def add_point_set():
16 | # # room coordinates to vertices
17 | # coords = [point for room in rooms for primitive in room for point in primitive]
18 |
19 | # # create vertices
20 | # vertices, inv_vertices = np.unique(coords, axis=0, return_inverse=True)
21 | # cityjson['vertices'] = vertices.tolist()
22 |
23 | # # convert to wavefront type format
24 | # v_index = inv_vertices.tolist()
25 | # for i in range(len(rooms)):
26 | # outer_shell = [[[v_index.pop(0) for x in primitive]] for primitive in rooms[i]]
27 | # building_part = {
28 | # "type": "BuildingPart",
29 | # "parents": [parent_id],
30 | # "geometry": [{
31 | # "type": "Solid",
32 | # "lod": 2,
33 | # "boundaries": [outer_shell]
34 | # }]
35 | # }
36 | # cityjson['CityObjects']['room_'+str(i+1)] = building_part
37 | return False
38 |
39 | def add_buildingpart_to_cjson(cityjson, parent_id, meshset, part_name):
40 |
41 | num_vertices = len(cityjson['vertices'])
42 |
43 | # Load building part
44 | meshset.meshing_merge_close_vertices()
45 | mesh = meshset.mesh(0)
46 | faces = mesh.face_matrix()
47 | vertices = mesh.vertex_matrix().astype(np.float16)
48 |
49 | # Create building part
50 | boundaries = (np.uint32(faces[np.newaxis,:,np.newaxis,:]+num_vertices)).tolist()
51 | building_part = {
52 | "type": "BuildingPart",
53 | "parents": [parent_id],
54 | "geometry": [{
55 | "type": "Solid",
56 | "lod": 2,
57 | "boundaries": boundaries
58 | }]
59 | }
60 |
61 | # Add building part & update vertices
62 | cityjson['CityObjects'][part_name] = building_part
63 | cityjson['vertices'].extend(vertices.tolist())
64 |
65 | return cityjson
66 |
67 | def add_buildingroom_to_cjson(cityjson, parent_id, meshset, part_name):
68 |
69 | num_vertices = len(cityjson['vertices'])
70 |
71 | # Load building part
72 | meshset.meshing_merge_close_vertices()
73 | mesh = meshset.mesh(0)
74 | faces = mesh.face_matrix()
75 | vertices = mesh.vertex_matrix().astype(np.float16)
76 |
77 | # Create building part
78 | boundaries = (np.uint32(faces[np.newaxis,:,np.newaxis,:]+num_vertices)).tolist()
79 | building_part = {
80 | "type": "BuildingRoom",
81 | "parents": [parent_id],
82 | "geometry": [{
83 | "type": "Solid",
84 | "lod": 2,
85 | "boundaries": boundaries
86 | }]
87 | }
88 |
89 | # Add building part & update vertices
90 | cityjson['CityObjects'][part_name] = building_part
91 | cityjson['vertices'].extend(vertices.tolist())
92 |
93 | return cityjson
94 |
95 | def save_to_file(cityjson, outfile):
96 | try:
97 | if os.path.isfile(outfile):
98 | os.remove(outfile)
99 | with open(outfile, "w", encoding="utf8") as file:
100 | json.dump(cityjson,file)
101 | logger.info(f'Succesfully saved output to {str(outfile)}')
102 | except:
103 | logger.error('Failed to save file.')
104 |
105 | def to_cityjson_v1(rooms):
106 | """
107 | A function that converts a list of geometrical defined rooms to CityJSON v1.0 format.
108 |
109 | Parameters
110 | ----------
111 | rooms : list
112 | A list containing the rooms that should be converted. A room is a list of primitives/surfaces.
113 | Each primitive is a list of vertices (x,y,z), only linear and planar primitives are allowed.
114 |
115 | Returns
116 | -------
117 | A CityJSON object
118 | """
119 |
120 | # Assertions
121 | assert isinstance(rooms, list), "Argument rooms is not of type List."
122 |
123 | cityjson = {
124 | "type": "CityJSON",
125 | "version": "1.0",
126 | "CityObjects": {},
127 | "vertices": [],
128 | "transform": {
129 | "scale":[1.0,1.0,1.0],
130 | "translate":[0.0,0.0,0.0]
131 | }
132 | }
133 |
134 | # add parent
135 | parent_id = "id-1"
136 | cityjson['CityObjects'][parent_id] = {"type":"Building", "geometry":[]}
137 |
138 | for i, meshset in enumerate(rooms):
139 | try:
140 | part_name = "room_" + str(i)
141 | add_buildingpart_to_cjson(cityjson, parent_id, meshset, part_name)
142 | except Exception as e:
143 | logger.error(f'Failed {part_name}')
144 |
145 | return cityjson
146 |
147 | def to_cityjson_v1_1(rooms):
148 | """
149 | A function that converts a list of geometrical defined rooms to CityJSON v1.1.2 format.
150 |
151 | Parameters
152 | ----------
153 | rooms : list
154 | A list containing the rooms that should be converted. A room is a list of primitives/surfaces.
155 | Each primitive is a list of vertices (x,y,z), only linear and planar primitives are allowed.
156 | outfile : str
157 | The output path to be used for saving the CityJSON file.
158 |
159 | Returns
160 | -------
161 | A CityJSON object
162 | """
163 |
164 | # Assertions
165 | assert isinstance(rooms, list), "Argument rooms is not of type List."
166 |
167 | cityjson = {
168 | "type": "CityJSON",
169 | "version": "1.1",
170 | "CityObjects": {},
171 | "vertices": [],
172 | "transform": {
173 | "scale":[1.0,1.0,1.0],
174 | "translate":[0.0,0.0,0.0]
175 | }
176 | }
177 |
178 | # add parent
179 | parent_id = "id-1"
180 | cityjson['CityObjects'][parent_id] = {"type":"Building"}
181 |
182 | # add parent
183 | parent_id = "id-1"
184 | cityjson['CityObjects'][parent_id] = {"type":"Building"}
185 |
186 | i = 1
187 | for meshset in rooms:
188 | try:
189 | part_name = "room_" + str(i)
190 | add_buildingroom_to_cjson(cityjson, parent_id, meshset, part_name)
191 | except Exception as e:
192 | logger.error(f'Failed {part_name}')
193 | i += 1
194 |
195 | return cityjson
--------------------------------------------------------------------------------
/ipcp/src/utils/clip_utils.py:
--------------------------------------------------------------------------------
1 | """
2 | Clipping tools for point clouds and polygons.
3 |
4 | The method poly_clip() is adapted from:
5 | https://github.com/brycefrank/pyfor/blob/master/pyfor/clip.py
6 |
7 | The method _point_inside_poly is adapted from:
8 | https://github.com/sasamil/PointInPolygon_Py
9 | """
10 | import numpy as np
11 | from numba import jit
12 | import numba
13 | import logging
14 |
15 | from ..utils import math_utils
16 |
17 | logger = logging.getLogger(__name__)
18 |
19 |
20 | @jit(nopython=True, cache=True)
21 | def rectangle_clip(points, rect):
22 | """
23 | Clip all points within a rectangle.
24 |
25 | Parameters
26 | ----------
27 | points : array of shape (n_points, 2)
28 | The points.
29 | rect : tuple of floats
30 | (x_min, y_min, x_max, y_max)
31 |
32 | Returns
33 | -------
34 | A boolean mask with True entries for all points within the rectangle.
35 | """
36 | clip_mask = ((points[:, 0] >= rect[0]) & (points[:, 0] <= rect[2])
37 | & (points[:, 1] >= rect[1]) & (points[:, 1] <= rect[3]))
38 | return clip_mask
39 |
40 |
41 | @jit(nopython=True, cache=True)
42 | def box_clip(points, rect, bottom=-np.inf, top=np.inf):
43 | """
44 | Clip all points within a 3D box.
45 |
46 | Parameters
47 | ----------
48 | points : array of shape (n_points, 2)
49 | The points.
50 | rect : tuple of floats
51 | (x_min, y_min, x_max, y_max)
52 | bottom : float (default: -inf)
53 | Bottom of the box.
54 | top : float (default: inf)
55 | Top of the box.
56 |
57 | Returns
58 | -------
59 | A boolean mask with True entries for all points within the 3D box.
60 | """
61 | box_mask = rectangle_clip(points, rect)
62 | box_mask = box_mask & ((points[:, 2] <= top) & (points[:, 2] >= bottom))
63 | return box_mask
64 |
65 |
66 | @jit(nopython=True, cache=True)
67 | def circle_clip(points, center, radius):
68 | """
69 | Clip all points within a circle (or unbounded cylinder).
70 |
71 | Parameters
72 | ----------
73 | points : array of shape (n_points, 2)
74 | The points.
75 | center : tuple of floats (x, y)
76 | Center point of the circle.
77 | radius : float
78 | Radius of the circle.
79 |
80 | Returns
81 | -------
82 | A boolean mask with True entries for all points within the circle.
83 | """
84 | clip_mask = (np.power((points[:, 0] - center[0]), 2)
85 | + np.power((points[:, 1] - center[1]), 2)
86 | <= np.power(radius, 2))
87 | return clip_mask
88 |
89 |
90 | @jit(nopython=True, cache=True)
91 | def cylinder_clip(points, center, radius, bottom=-np.inf, top=np.inf):
92 | """
93 | Clip all points within a cylinder.
94 |
95 | Parameters
96 | ----------
97 | points : array of shape (n_points, 2)
98 | The points.
99 | center : tuple of floats (x, y)
100 | Center point of the circle.
101 | radius : float
102 | Radius of the circle.
103 | bottom : float (default: -inf)
104 | Bottom of the cylinder.
105 | top : float (default: inf)
106 | Top of the cylinder.
107 |
108 | Returns
109 | -------
110 | A boolean mask with True entries for all points within the circle.
111 | """
112 | clip_mask = circle_clip(points, center, radius)
113 | clip_mask = clip_mask & ((points[:, 2] <= top) & (points[:, 2] >= bottom))
114 | return clip_mask
115 |
116 |
117 | @jit(nopython=True, cache=True)
118 | def _point_inside_poly(polygon, point):
119 | """
120 | Improved version of the Crossing Number algorithm that checks if a point is
121 | inside a polygon.
122 | Implementation taken from https://github.com/sasamil/PointInPolygon_Py
123 | """
124 | length = len(polygon) - 1
125 | dy2 = point[1] - polygon[0][1]
126 | intersections = 0
127 | ii = 0
128 | jj = 1
129 |
130 | while ii < length:
131 | dy = dy2
132 | dy2 = point[1] - polygon[jj][1]
133 |
134 | # consider only lines which are not completely above/below/right from
135 | # the point
136 | if dy*dy2 <= 0.0 and (point[0] >= polygon[ii][0]
137 | or point[0] >= polygon[jj][0]):
138 |
139 | # non-horizontal line
140 | if dy < 0 or dy2 < 0:
141 | F = (dy * (polygon[jj][0] - polygon[ii][0])
142 | / (dy-dy2) + polygon[ii][0])
143 |
144 | if point[0] > F:
145 | # if line is left from the point - the ray moving towards
146 | # left, will intersect it
147 | intersections += 1
148 | elif point[0] == F: # point on line
149 | return 2
150 |
151 | # point on upper peak (dy2=dx2=0) or horizontal line (dy=dy2=0 and
152 | # dx*dx2<=0)
153 | elif (dy2 == 0
154 | and (point[0] == polygon[jj][0]
155 | or (dy == 0 and (point[0] - polygon[ii][0])
156 | * (point[0] - polygon[jj][0]) <= 0))):
157 | return 2
158 |
159 | ii = jj
160 | jj += 1
161 |
162 | return intersections & 1
163 |
164 |
165 | @jit(nopython=True, cache=True, parallel=True)
166 | def is_inside(x, y, polygon):
167 | """
168 | Checks for each point in a list whether that point is inside a polygon.
169 |
170 | Parameters
171 | ----------
172 | x : list
173 | X-coordinates.
174 | y : list
175 | Y-coordinates.
176 | polygon : list of tuples
177 | Polygon as linear ring.
178 |
179 | Returns
180 | -------
181 | An array of shape (len(x),) with dtype bool, where each entry indicates
182 | whether the corresponding point is inside the polygon.
183 | """
184 | n = len(x)
185 | mask = np.empty((n,), dtype=numba.boolean)
186 | for i in numba.prange(n):
187 | mask[i] = _point_inside_poly(polygon, (x[i], y[i]))
188 | return mask
189 |
190 |
191 | def poly_clip(points, poly):
192 | """
193 | Clip all points within a polygon.
194 |
195 | Parameters
196 | ----------
197 | points : array of shape (n_points, 2)
198 | The points.
199 | poly : shapely.geometry Polygon object
200 | Polygon to clip. Can have interior gaps.
201 |
202 | Returns
203 | -------
204 | A boolean mask with True entries for all points within the polygon.
205 | """
206 | # Convert to numpy to work with numba jit in nopython mode.
207 | exterior = np.array(poly.exterior.coords)
208 | interiors = [np.array(interior.coords) for interior in poly.interiors]
209 |
210 | clip_mask = np.zeros((len(points),), dtype=bool)
211 |
212 | # Clip exterior to include points.
213 | bbox_mask = rectangle_clip(
214 | points, math_utils.compute_bounding_box(exterior))
215 | exterior_mask = is_inside(points[bbox_mask, 0], points[bbox_mask, 1],
216 | exterior)
217 | bbox_inds = np.where(bbox_mask)[0]
218 | clip_mask[bbox_inds[exterior_mask]] = True
219 |
220 | # Clip interior(s) to exclude points.
221 | for interior in interiors:
222 | bbox_mask = rectangle_clip(
223 | points, math_utils.compute_bounding_box(interior))
224 | interior_mask = is_inside(points[bbox_mask, 0], points[bbox_mask, 1],
225 | interior)
226 | bbox_inds = np.where(bbox_mask)[0]
227 | clip_mask[bbox_inds[interior_mask]] = False
228 |
229 | return clip_mask
230 |
231 |
232 | def poly_box_clip(points, poly, bottom=-np.inf, top=np.inf):
233 | """
234 | Clip all points within a 3D polygon with fixed height.
235 |
236 | Parameters
237 | ----------
238 | points : array of shape (n_points, 2)
239 | The points.
240 | poly : shapely.geometry Polygon object
241 | Polygon to clip. Can have interior gaps.
242 | bottom : float (default: -inf)
243 | Bottom height of the 3D polygon.
244 | top : float (default: inf)
245 | Top height of the 3D polygon.
246 |
247 | Returns
248 | -------
249 | A boolean mask with True entries for all points within the 3D polygon.
250 | """
251 | clip_mask = poly_clip(points, poly)
252 | clip_mask = clip_mask & ((points[:, 2] <= top) & (points[:, 2] >= bottom))
253 | return clip_mask
254 |
--------------------------------------------------------------------------------
/ipcp/src/utils/log_utils.py:
--------------------------------------------------------------------------------
1 | # Urban_PointCloud_Processing by Amsterdam Intelligence, GPL-3.0 license
2 |
3 | import logging
4 | import pathlib
5 | import sys
6 |
7 | BASE_NAME = 'upcp'
8 | BASE_LEVEL = logging.DEBUG
9 |
10 |
11 | class LastPartFilter(logging.Filter):
12 | def filter(self, record):
13 | record.name_last = record.name.rsplit('.', 1)[-1]
14 | return True
15 |
16 |
17 | def reset_logger(base_level=BASE_LEVEL):
18 | logger = logging.getLogger(BASE_NAME)
19 | logger.setLevel(base_level)
20 | logger.handlers = []
21 |
22 |
23 | def add_console_logger(level=logging.INFO):
24 | logger = logging.getLogger(BASE_NAME)
25 | ch = logging.StreamHandler(sys.stdout)
26 | ch.set_name('UPCP Console Logger')
27 | ch.setLevel(level)
28 | formatter = logging.Formatter(
29 | '%(levelname)s - %(message)s')
30 | ch.setFormatter(formatter)
31 | logger.addHandler(ch)
32 |
33 |
34 | def add_file_logger(logfile, level=logging.DEBUG, clear_log=False):
35 | log_path = pathlib.Path(logfile)
36 | if log_path.is_file():
37 | if clear_log:
38 | open(log_path, "w").close()
39 | else:
40 | pathlib.Path(log_path.parent).mkdir(parents=True, exist_ok=True)
41 | logger = logging.getLogger(BASE_NAME)
42 | fh = logging.FileHandler(log_path)
43 | fh.set_name('UPCP File Logger')
44 | fh.setLevel(level)
45 | formatter = logging.Formatter(
46 | '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
47 | datefmt="%Y-%m-%d %H:%M:%S")
48 | fh.setFormatter(formatter)
49 | fh.addFilter(LastPartFilter())
50 | logger.addHandler(fh)
51 |
52 |
53 | def set_console_level(level=logging.INFO):
54 | logger = logging.getLogger(BASE_NAME)
55 | for hl in logger.handlers:
56 | if hl.get_name() == 'UPCP Console Logger':
57 | hl.setLevel(level)
58 |
--------------------------------------------------------------------------------
/ipcp/src/utils/math_utils.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | from numba import jit
3 | from scipy.spatial import ConvexHull
4 | from shapely.geometry import Polygon
5 |
6 |
7 | def vector_angle(u, v=np.array([0., 0., 1.])):
8 | """
9 | Returns the angle in degrees between vectors 'u' and 'v'. If only 'u' is
10 | provided, the angle between 'u' and the vertical axis is returned.
11 | """
12 | # see https://stackoverflow.com/a/2827466/425458
13 | c = np.dot(u/np.linalg.norm(u), v/np.linalg.norm(v))
14 | clip = np.minimum(1, np.maximum(c, -1))
15 | return np.rad2deg(np.arccos(clip))
16 |
17 | def lineseg_dist(p, a, b):
18 | """
19 | Returns the distance between a set of points and a linesegment.
20 | It takes into account the ending of the line.
21 | """
22 | # see https://stackoverflow.com/a/56467661
23 |
24 | d = np.divide(b - a, np.linalg.norm(b - a))
25 | s = np.dot(a - p, d)
26 | t = np.dot(p - b, d)
27 | h = np.maximum.reduce([s, t, 0])
28 | c = np.cross(p - a, d)
29 | return np.hypot(h, np.linalg.norm(c))
30 |
31 | #@jit(nopython=True, cache=True, parallel=True)
32 | def line_dist(p, a, d):
33 | """
34 | Returns the distance between a set of points and a linesegment.
35 | It takes into account the ending of the line.
36 | """
37 | return np.linalg.norm(np.cross(p - a, d), axis=1)
38 |
39 | @jit(nopython=True, cache=True, parallel=True)
40 | def compute_bounding_box(points):
41 | """
42 | Get the min/max values of a point list.
43 |
44 | Parameters
45 | ----------
46 | points : array of shape (n_points, 2)
47 | The (x, y) coordinates of the points. Any further dimensions will be
48 | ignored.
49 |
50 | Returns
51 | -------
52 | tuple
53 | (x_min, y_min, x_max, y_max)
54 | """
55 | x_min = np.min(points[:, 0])
56 | x_max = np.max(points[:, 0])
57 | y_min = np.min(points[:, 1])
58 | y_max = np.max(points[:, 1])
59 |
60 | return (x_min, y_min, x_max, y_max)
61 |
62 |
63 | def convex_hull_poly(points):
64 | """Return convex hull as a shapely Polygon."""
65 | hull = points[ConvexHull(points).vertices]
66 | return Polygon(np.vstack((hull, hull[0])))
67 |
68 |
69 | def minimum_bounding_rectangle(points):
70 | """
71 | Find the smallest bounding rectangle for a set of points.
72 | Returns a set of points representing the corners of the bounding box.
73 |
74 | :param points: an nx2 matrix of coordinates
75 | :rval: an nx2 matrix of coordinates
76 | """
77 | pi2 = np.pi/2.
78 |
79 | # get the convex hull for the points
80 | hull_points = points[ConvexHull(points).vertices]
81 |
82 | # calculate edge angles
83 | edges = np.zeros((len(hull_points)-1, 2))
84 | edges = hull_points[1:] - hull_points[:-1]
85 |
86 | angles = np.zeros((len(edges)))
87 | angles = np.arctan2(edges[:, 1], edges[:, 0])
88 |
89 | angles = np.abs(np.mod(angles, pi2))
90 | angles = np.unique(angles)
91 |
92 | # find rotation matrices
93 | rotations = np.vstack([
94 | np.cos(angles),
95 | np.cos(angles-pi2),
96 | np.cos(angles+pi2),
97 | np.cos(angles)]).T
98 | rotations = rotations.reshape((-1, 2, 2))
99 |
100 | # apply rotations to the hull
101 | rot_points = np.dot(rotations, hull_points.T)
102 |
103 | # find the bounding points
104 | min_x = np.nanmin(rot_points[:, 0], axis=1)
105 | max_x = np.nanmax(rot_points[:, 0], axis=1)
106 | min_y = np.nanmin(rot_points[:, 1], axis=1)
107 | max_y = np.nanmax(rot_points[:, 1], axis=1)
108 |
109 | # find the box with the best area
110 | areas = (max_x - min_x) * (max_y - min_y)
111 | best_idx = np.argmin(areas)
112 |
113 | # return the best box
114 | x1 = max_x[best_idx]
115 | x2 = min_x[best_idx]
116 | y1 = max_y[best_idx]
117 | y2 = min_y[best_idx]
118 | r = rotations[best_idx]
119 |
120 | # Calculate center point and project onto rotated frame
121 | center_x = (x1 + x2) / 2
122 | center_y = (y1 + y2) / 2
123 | center_point = np.dot([center_x, center_y], r)
124 |
125 | min_bounding_rect = np.zeros((4, 2))
126 | min_bounding_rect[0] = np.dot([x1, y2], r)
127 | min_bounding_rect[1] = np.dot([x2, y2], r)
128 | min_bounding_rect[2] = np.dot([x2, y1], r)
129 | min_bounding_rect[3] = np.dot([x1, y1], r)
130 |
131 | # Compute the dims of the min bounding rectangle
132 | dims = [(x1 - x2), (y1 - y2)]
133 |
134 | return min_bounding_rect, hull_points, min(dims), max(dims), center_point
135 |
--------------------------------------------------------------------------------
/ipcp/src/utils/pcd_utils.py:
--------------------------------------------------------------------------------
1 | import os
2 | from laspy import read as read_las
3 | import numpy as np
4 | import open3d as o3d
5 |
6 | def read_pointcloud(infile):
7 | """Read a file and return the pointcloud object."""
8 | filename, file_extension = os.path.splitext(infile)
9 |
10 | if file_extension == '.ply':
11 | return o3d.io.read_point_cloud(infile)
12 | else:
13 | las = read_las(infile)
14 | points = np.vstack([las.x,las.y,las.z]).T
15 | return o3d.geometry.PointCloud(o3d.utility.Vector3dVector(points))
16 |
17 | def write_pointcloud(points, filename):
18 | pcd = o3d.geometry.PointCloud(o3d.utility.Vector3dVector(points))
19 | o3d.io.write_point_cloud(filename, pcd)
20 | return True
21 |
22 | def merge_point_clouds(pcd_1, pcd_2):
23 | points = np.concatenate((pcd_1.points, pcd_2.points))
24 | normals = np.concatenate((pcd_1.normals, pcd_2.normals))
25 |
26 | pcd = o3d.geometry.PointCloud()
27 | pcd.points = o3d.utility.Vector3dVector(points)
28 | pcd.normals = o3d.utility.Vector3dVector(normals)
29 |
30 | return pcd
31 |
32 |
--------------------------------------------------------------------------------
/ipcp/src/utils/plot_utils.py:
--------------------------------------------------------------------------------
1 | import matplotlib.pyplot as plt
2 | import open3d as o3d
3 | import numpy as np
4 |
5 | def show_pcd(pcd, labels, exclude_labels=[]):
6 |
7 | mask = np.where(~np.isin(labels, exclude_labels))[0]
8 | pcd_ = pcd.select_by_index(mask)
9 | labels_ = labels[mask]
10 |
11 | # mix
12 | mask_noise = labels_ != -1
13 | un_labels = np.unique(labels_[mask_noise])
14 | shuffle_ = np.random.choice(len(un_labels), len(un_labels),replace=False)
15 | inv = np.unique(labels_[mask_noise], return_inverse=True)[1]
16 | labels_[mask_noise] = shuffle_[inv]
17 |
18 | max_label = labels_.max()
19 | colors = plt.get_cmap("gist_rainbow")(labels_ / (max_label if max_label > 0 else 1))
20 | colors[labels_ < 0] = 0
21 | pcd_.colors = o3d.utility.Vector3dVector(colors[:, :3])
22 | o3d.visualization.draw_geometries([pcd_])
23 |
24 | def show_pcd_floors(pcd, floors):
25 | pcds_ = []
26 | for i in range(len(floors)):
27 | mask = floors[i]
28 | pcd_ = pcd.select_by_index(np.where(mask)[0])
29 | color = plt.get_cmap("tab20")(i / len(floors))
30 | pcd_.paint_uniform_color(color[:3])
31 | pcds_.append(pcd_)
32 |
33 | o3d.visualization.draw_geometries(pcds_)
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | laspy==2.0.3
2 | matplotlib==3.5.3
3 | networkx==2.8.6
4 | numba==0.56.2
5 | numpy==1.23.2
6 | open3d==0.15.2
7 | opencv_python==4.6.0.66
8 | pymeshlab==2022.2.post2
9 | rasterio==1.3.2
10 | scikit_image==0.19.3
11 | scikit_spatial==6.6.0
12 | scipy==1.9.0
13 | Shapely==1.8.4
14 | tqdm==4.64.0
15 |
--------------------------------------------------------------------------------