├── .gitignore
├── LICENSE
├── README.md
├── lod3_result.png
├── requirements.txt
├── stage_1
├── run.py
├── scripts
│ └── filter_images.py
└── src
│ ├── api_request.py
│ ├── array_image.py
│ ├── array_math.py
│ ├── extract_texture.py
│ ├── furthest_pair.py
│ └── visible_view.py
├── stage_2
└── test.py
├── stage_3
├── CSV
│ ├── output_stage1.csv
│ └── output_stage2.csv
├── CityGML
│ └── LOD2_120700-485100.gml
├── images
│ ├── 0363100012152551_8.426128.jpeg
│ ├── 0363100012152951_8.338701.jpeg
│ ├── 0363100012157182_6.40601.jpeg
│ ├── 0363100012159183_8.463423.jpeg
│ ├── 0363100012165513_6.381795.jpeg
│ └── 0363100012166458_6.476083.jpeg
├── insert_bboxes.py
├── prepare_lod3.py
└── src
│ ├── furthest_pair.py
│ ├── geometry.py
│ └── optional.py
└── system-overview.png
/.gitignore:
--------------------------------------------------------------------------------
1 | *.pyc
2 | __pycache__/
3 | .DS_Store
4 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
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 | .
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Extraction of façade details from street-view panoramic images and integration in a 3D city model
2 |
3 | In this repository, a method is presented to automatically enhance Level Of Detail 2 buildings in a 3D city model with window and door geometries, by using a panoramic image sequence. The figure below shows a schematic overview of the proposed method, a **three staged pipeline**. The first stage is based on identifying, rectifying and extracting the texture region of a building from a panoramic image sequence. In the next stage, the extracted façade texture images are used as input in a deep convolutional neural network for parsing façade details, such as windows and doors. In the third and final stage of the pipeline, the previously parsed window and door rectangles are aligned with the input LOD2 model to construct a LOD3 model. More on https://medium.com/@chrise96/a-deep-learning-approach-to-enhance-3d-city-models-caba7b2073d6.
4 |
5 | 
6 |
7 |
8 | ---
9 |
10 | ## Project Folder Structure
11 |
12 | - [`stage_1`](./stage_1): Folder for the panoramic image and building analysis implementation
13 | - [`stage_2`](./stage_2): Folder for the Faster/Mask R-CNN implementation
14 | - [`stage_3`](./stage_3): Folder for the CityGML LOD2 to LOD3 implementation
15 | - [`stage_1/src`](./stage_1/src): Folder for the source files specific to the stage
16 | - [`stage_1/scripts`](./stage_1/scripts): Folder for the helper files
17 |
18 |
19 | ---
20 |
21 | ## Description of output files
22 | - [`*.jpeg`](./stage_3/images/0363100012152551_8.426128.jpeg): Rectified façade images with the naming based on two values
23 | - A pand ID according to Key register Addresses and Buildings (BAG). For example: https://api.data.amsterdam.nl/bag/pand/0363100012061378/
24 | - A unique value, calculated using the distance in meters from the capture location of a panoramic image to the middlepoint of a façade.
25 |
26 | - [`output_stage1.csv`](./stage_3/CSV/output_stage1.csv): A CSV file with a reference to the extracted rectified façade images. The CSV file contains the columns
27 | - `pand_id`: BAG pand ID.
28 | - `visible_point_one`: The bottom-left Rijksdriehoek coordinate of the façade (perspective of the camera/image).
29 | - `visible_point_two`: The bottom-right Rijksdriehoek coordinate of the façade (perspective of the camera/image).
30 | - `texture_filename`: The actual filename of the `*.jpeg` images.
31 |
32 | - [`output_stage2.csv`](./stage_3/CSV/output_stage2.csv): The CSV file contains the columns
33 | - `bboxes_window`: A list of predicted windows, given via four pixel values: xleft, ybottom, xright, ytop.
34 | - `bboxes_door`: A list of predicted doors, given via four pixel values: xleft, ybottom, xright, ytop.
35 | - `texture_filename`: The actual filename of the `*.jpeg` images.
36 |
37 |
38 | ---
39 |
40 | ## Datasets
41 | ### Amsterdam DataPunt
42 | [APIs](https://api.data.amsterdam.nl/) (Open Data and internal) offered by Amsterdam Data en Informatie.
43 |
44 | ### Dataset of façade images by City of Amsterdam
45 | For this project, the City of Amsterdam annotated over 980 segmentation mask images for training the network. Regions in Amsterdam North and West are considered with diverse architectural style buildings, to ensure the robustness and the generalization of the network. The images were manually annotated with three classes (i.e. door, window, sky) by outlining their masks and adding corresponding class labels. The dataset is split into train and val folders with two corresponding JSON files in the MS COCO format. The dataset is available here: [Updated Google Drive link](https://drive.google.com/file/d/1nkZXSTCM019HGX1QtG2z3sZ3jLoXVL3f/view?usp=drive_link)
46 |
47 | ### 3D Amsterdam
48 | The [3D Amsterdam city model](https://3d.amsterdam.nl/) was published in 2019 as open data and contains information about every registered building in Amsterdam, as well as streets and trees. The city model consists of LOD2 style buildings in the standard CityGML or CityJSON format. It uses the Rijksdriehoek Coordinate System (EPSG:28992) and the Normaal Amsterdams Peil height system.
49 |
50 |
51 | ---
52 |
53 | ## Windows and doors in 3D Amsterdam
54 | A screenshot of a virtual street scene in LOD3 is given below to demonstrate the enhancement results on a street-level. Visualized with Azul CityGML viewer.
55 |
56 | 
57 |
58 | ---
59 |
60 | ## Installation
61 | 1. Clone this repository:
62 |
63 | ```
64 | git clone https://github.com/chrise96/3D_building_reconstruction.git
65 | ```
66 |
67 | 2. Install the dependencies:
68 |
69 | ```
70 | pip install -r requirements.txt
71 | ```
72 |
73 | And install GDAL and scikit-geometry. Available as a conda package or a system install but not in pip:
74 |
75 | ```
76 | conda install -c conda-forge gdal=2.4.2
77 | conda install -c conda-forge scikit-geometry
78 | ```
79 |
80 |
81 | ---
82 |
83 | ## Notes
84 | - The accuracy of the GNSS/INS sensor values is an important factor that significantly affects the quality of the
85 | determined texture region of a building. Pose (location and orientation) optimization techniques can be used in future work to further
86 | improve the quality of façade texture images during the extraction process. For now, validate the quality of the extracted façade texture images, manually remove invalid ones and run:
87 |
88 | cd stage_1
89 | python3 -m scripts.filter_images
90 | - The system treats each wall as though it is 30 meters tall. Accordingly, the visual content is partly cut off when buildings are above 30 meter. Also, the system omits buildings with an area size of 400 m2 or larger, which is calculated using the building footprint data provided by BAG. Large buildings often impose badly distorted rectification results.
91 | - An optional step is performed on invalid CityGML files to remove duplicate buildings and keep unique ones.
92 | - In the final stage of the pipeline, it often occurs that an opening geometry intersects with two or more exterior polygons (LOD2 wallsurface members). As interior polygons define openings in an exterior polygon, they have to be completely included in the area defined by the exterior polygon. In this case, a part of the intersecting opening geometry is simply placed over a wall surface and not propertly integrated into the building.
93 |
94 | ---
95 |
--------------------------------------------------------------------------------
/lod3_result.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chrise96/3D_building_reconstruction/86539cd14689109ca9bc41b6fc7e21231623bc77/lod3_result.png
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | scipy==1.2.1
2 | numpy==1.19.1
3 | matplotlib==3.3.1
4 | pillow==7.2.0
5 | pandas==1.1.1
6 | requests==2.24.0
7 | Shapely==1.6.4
8 | lxml==4.5.1
9 |
10 |
11 |
--------------------------------------------------------------------------------
/stage_1/run.py:
--------------------------------------------------------------------------------
1 | """
2 | The first stage of the pipeline determines — within a captured panoramic image sequence — the
3 | texture region for each building (pand_id) to be reconstructed.
4 |
5 | There are three input sources used in this stage: BAG building footprint data, panoramic
6 | images, and GNSS/INS sensor values. The initial GNSS/INS sensor specifies the camera’s
7 | geospatial location and orientation information that correspond to each of the panoramic
8 | images.
9 |
10 | NOTE: Change the variables BBOX_REGION and MISSION_YEAR to your own settings!
11 | """
12 |
13 | import os
14 | import time
15 | from multiprocessing import Process, Manager
16 | from shapely.geometry import Point, Polygon
17 | import pandas as pd
18 | import numpy as np
19 |
20 | # External Python files
21 | from src.api_request import *
22 | from src.extract_texture import export_line_to_texture
23 | from src.visible_view import generate_arrangement, get_visibility_polygon, point_in_visibility_polygon
24 | from src.array_math import get_midpoint, vector_length, vector
25 | from src.furthest_pair import get_furthest_pair
26 |
27 | # Multiprocessing options
28 | NUM_CPUS = 5
29 |
30 | # API options
31 | BBOX_REGION = [122300.00,486628.78,122400.00,486475.48]
32 | MISSION_YEAR = 2018 # API tag
33 | SEARCH_RADIUS = 10 # Building search radius from an initial panoramic image location
34 |
35 | # Texture options
36 | TEXTURE_RESOLUTION = 30
37 | IMAGE_HEIGHT_IRL = 30 # In meters, buildings above 30m are therefore partly cropped
38 | CAMERA_HEIGHT = 2 # Height of the camera mounted on the car
39 |
40 | # Validation options before rectification (strict settings)
41 | MIN_DISTANCE = 1.7 # Min distance camera to building
42 | MAX_DISTANCE = 9
43 | MIN_BUILDING_AREA = 15
44 | MAX_BUILDING_AREA = 400
45 |
46 | IMAGES_OUTPUT = "texture_output/"
47 | OUTPUT_NAME = "output_stage1"
48 |
49 | def get_visible_building_edges(pano_ids, facade_data):
50 | """
51 | Estimation of buildings in range and identify visible building
52 | edges in 2D map.
53 |
54 | Function will be executed on different workers
55 | """
56 | for pano_id in pano_ids:
57 | # Get the panoramic image url and the location of the "observer"
58 | image_url, observer = get_pano_image(pano_id)
59 |
60 | # Get BAG "pand" information. Search radius in meters from point "near"
61 | pand_json = get_buildings_in_range(observer, SEARCH_RADIUS)
62 |
63 | # Get a dict of the buildings (footprint data) in range
64 | building_polygons = get_building_polygons(pand_json)
65 |
66 | # Validation checks on the GPS location and building polygons
67 | building_polygons = get_admissible_data(observer, building_polygons)
68 |
69 | if not building_polygons:
70 | #print("No admissible building polygons in range. Go to the next panorama")
71 | continue
72 |
73 | # Generate the outlines of the arrangement
74 | arr = generate_arrangement(observer, building_polygons.values())
75 |
76 | # Get the Visibility Polygon for point q
77 | visibility_polygon = get_visibility_polygon(arr, observer)
78 |
79 | # Get two most distant visible points of a builing
80 | get_facade_coordinates(building_polygons, visibility_polygon, observer, image_url, facade_data)
81 |
82 | def extract_facade_texture(grouped_chunk):
83 | """
84 | Extract facade textures from panoramic images.
85 |
86 | Function will be executed on different workers
87 | """
88 | for group_name, df_group in grouped_chunk:
89 | # Get the panoramic image
90 | source_image = download_pano_image(group_name)
91 | if source_image is not None:
92 | # Iterate over the rows that are inside a group
93 | for _, row in df_group.iterrows():
94 | # Create the facade texture
95 | image_file = export_line_to_texture((row["visible_point_one"], row["visible_point_two"]),
96 | TEXTURE_RESOLUTION, IMAGE_HEIGHT_IRL, CAMERA_HEIGHT,
97 | source_image, row["observer"])
98 | # Save the facade texture
99 | filename = row["texture_filename"]
100 | image_file.save(f"{IMAGES_OUTPUT}{filename}.jpeg", "jpeg")
101 |
102 | def get_admissible_data(observer, building_polygons):
103 | """
104 | Validate the GPS location of a panoramic image
105 | and the size of a building.
106 | """
107 | observer_point = Point(observer)
108 |
109 | admissible_building_polygons = {}
110 | for k, v in list(building_polygons.items()):
111 | building_poly = Polygon(v)
112 |
113 | # Check if point q is too close to a building
114 | if building_poly.exterior.distance(observer_point) < MIN_DISTANCE:
115 | print("GNSS/INS measurement error found! Too close to building.")
116 | return {}
117 |
118 | # Check if point q is inside a building (GNSS/INS error)
119 | if observer_point.intersects(building_poly):
120 | print("GNSS/INS measurement error found! Point inside building.")
121 | return {}
122 |
123 | # Check for building area sizes that we ignore (Too large: Bijenkorf, too small: mini snackbar)
124 | if MIN_BUILDING_AREA < building_poly.area < MAX_BUILDING_AREA:
125 | admissible_building_polygons[k] = v
126 |
127 | return admissible_building_polygons
128 |
129 | def get_facade_coordinates(building_polygons, visibility_polygon, observer, image_url, facade_data):
130 | """ Get the two most distant visible points of a builing """
131 | for pand_id in building_polygons.keys():
132 | new_data = {}
133 |
134 | # Get all the points from this polygon that are in the visibility polygon
135 | visible_points = point_in_visibility_polygon(building_polygons[pand_id], visibility_polygon)
136 |
137 | # Check if there are two or more visible points for a building
138 | if len(visible_points) >= 2:
139 | # Get from a list of items the furthest pair where we keep the (winding) order of the list
140 | visible_points_left_right = get_furthest_pair(visible_points, observer)
141 |
142 | # Two validation checks
143 |
144 | # Calculate the distance between two points
145 | vector_facade = vector(visible_points_left_right[0], visible_points_left_right[1])
146 | facade_length = vector_length(vector_facade)
147 |
148 | # Validation 1. The length of a "normal" facade is at least more than 2 meters
149 | if facade_length < 2:
150 | # Go to next iteration of for loop, check for other buildings in same panorama
151 | break
152 |
153 | # Distance observer to middlepoint
154 | midpoint = get_midpoint(visible_points_left_right)
155 | vector_distance = vector(midpoint, observer)
156 | new_data["distance"] = round(vector_length(vector_distance), 6)
157 |
158 | # Validation 2. Errors are found in the rectification process when the distance is above 9
159 | if new_data["distance"] > MAX_DISTANCE:
160 | # Go to next iteration of for loop, check for other buildings in same panorama
161 | break
162 |
163 | # Fill dict after all the validation checks
164 | new_data["pand_id"] = str(pand_id)
165 | new_data["visible_point_one"] = tuple(visible_points_left_right[0]) # TODO why a tuple
166 | new_data["visible_point_two"] = tuple(visible_points_left_right[1])
167 | new_data["pano_image_url"] = image_url
168 | new_data["observer"] = observer
169 | # The distance value makes the filename unique
170 | new_data["texture_filename"] = str(pand_id) + "_" + str(new_data["distance"])
171 |
172 | facade_data.append(new_data)
173 |
174 | def save_results(df):
175 | """ Save results of extracted facade textures """
176 | df_output = df[["pand_id", "visible_point_one", "visible_point_two", "texture_filename"]]
177 | compression_opts = dict(method="zip", archive_name=OUTPUT_NAME + ".csv")
178 | df_output.to_csv(OUTPUT_NAME + ".zip", index=False, compression=compression_opts)
179 |
180 | def main():
181 | """
182 | Identify, rectify and extract the texture region of buildings
183 | from a panoramic image sequence.
184 | """
185 |
186 | # Create a directory, first check if it already exists
187 | if not os.path.exists(IMAGES_OUTPUT):
188 | os.makedirs(IMAGES_OUTPUT)
189 | else:
190 | print("The 'texture_output' folder already exists.")
191 |
192 | print("--- Start ---")
193 |
194 | # Start timer
195 | start_time = time.time()
196 |
197 | # Get the panoramas (from API)
198 | pano_ids = get_pano_id(MISSION_YEAR, BBOX_REGION)
199 |
200 | # Split the array into N chunks
201 | pano_id_chunk = np.array_split(pano_ids, NUM_CPUS)
202 |
203 | print("Step 1: Identify visible building edges in range of a panoramic image")
204 |
205 | facade_data = Manager().list()
206 | jobs = []
207 | for s in pano_id_chunk:
208 | j = Process(target=get_visible_building_edges, args=(s, facade_data))
209 | jobs.append(j)
210 | j.start()
211 | for j in jobs:
212 | j.join()
213 |
214 | print("Step 2: Drop duplicate facade textures")
215 |
216 | # Create pandas dataframe to easily manipulate the data
217 | df = pd.DataFrame(list(facade_data))
218 |
219 | # Drop duplicate facade rows, keep the ones with shortest distance.
220 | df = df.sort_values("distance", ascending=True).drop_duplicates(subset =
221 | ["visible_point_one", "visible_point_two"]).sort_index().reset_index(drop=True)
222 |
223 | # Group by image_url and later iterate over dataframe grouped by image_url
224 | df_group = df.groupby(["pano_image_url"]) # Unfortunately, no parallel apply function in pandas
225 |
226 | # Split the dataframe into N chunks (sub-dataframes)
227 | df_group_chunk = np.array_split(df_group, NUM_CPUS)
228 |
229 | print("Step 3: Extract facade textures from panoramic images")
230 |
231 | jobs = []
232 | for s in df_group_chunk:
233 | j = Process(target=extract_facade_texture, args=([s]))
234 | jobs.append(j)
235 | j.start()
236 | for j in jobs:
237 | j.join()
238 |
239 | print("Step 4: Save the results")
240 | save_results(df)
241 |
242 | print("--- %s seconds ---" % (time.time() - start_time))
243 |
244 | if __name__ == "__main__":
245 | main()
246 |
--------------------------------------------------------------------------------
/stage_1/scripts/filter_images.py:
--------------------------------------------------------------------------------
1 | """
2 | While the overall accuracy of the GNSS/INS sensor values are fairly high, it must
3 | be noted that faulty location values still occur.
4 |
5 | Validate the quality of the extracted facade texture images in the folder IMAGES_PATH
6 | and manually remove invalid ones.
7 |
8 | Run from the root of the "stage_1" folder, use: python3 -m scripts.filter_images
9 | """
10 |
11 | import pandas as pd
12 | import time
13 | import os
14 | import shutil
15 |
16 | IMAGES_PATH = "texture_output/"
17 | INPUT_NAME = "output_stage1.csv"
18 | OUTPUT_NAME = "output_stage1_filtered"
19 |
20 | def main():
21 | print("--- Start ---")
22 |
23 | # Start timer
24 | start_time = time.time()
25 |
26 | # Get the input csv with metadata of facade texture images
27 | df = pd.read_csv(INPUT_NAME, dtype={"pand_id": object})
28 |
29 | images = []
30 | for data in os.listdir(IMAGES_PATH):
31 | if data.endswith(".jpeg"):
32 | filename = os.path.splitext(data)[0]
33 | images.append(filename)
34 |
35 | df_output = df[df["texture_filename"].isin(images)].reset_index()
36 |
37 | # Save the filtered file
38 | filtered_df = df_output[["pand_id", "visible_point_one", "visible_point_two", "texture_filename"]]
39 | compression_opts = dict(method="zip", archive_name=OUTPUT_NAME + ".csv")
40 | filtered_df.to_csv(OUTPUT_NAME + ".zip", index=False,
41 | compression=compression_opts)
42 |
43 | print("--- %s seconds ---" % (time.time() - start_time))
44 |
45 | if __name__ == "__main__":
46 | main()
47 |
--------------------------------------------------------------------------------
/stage_1/src/api_request.py:
--------------------------------------------------------------------------------
1 | """
2 | Amsterdam API description: https://api.data.amsterdam.nl/api/
3 | """
4 |
5 | from io import BytesIO
6 | import json
7 | import requests
8 | from PIL import Image
9 | from osgeo import ogr, osr
10 |
11 | def get_pano_id(mission_year, bbox):
12 | """
13 | Get panoramic image id's for a user defined bounding box region
14 | """
15 | pano_url = f"https://api.data.amsterdam.nl/panorama/panoramas/?tags=mission-{mission_year}&bbox={bbox[0]},{bbox[1]},{bbox[2]},{bbox[3]}&srid=28992"
16 |
17 | with requests.get(pano_url) as response:
18 | pano_data_all = json.loads(response.content)
19 |
20 | pano_data = pano_data_all['_embedded']['panoramas']
21 |
22 | pano_id = []
23 | for item in pano_data:
24 | pano_id.append(item['pano_id'])
25 |
26 | # Check for next page with data
27 | next_page = pano_data_all['_links']['next']['href']
28 |
29 | # Exit the while loop if there is no next page
30 | while next_page:
31 | with requests.get(next_page) as response:
32 | pano_data_all = json.loads(response.content)
33 |
34 | pano_data = pano_data_all['_embedded']['panoramas']
35 |
36 | # Append the panorama id's to the list
37 | for item in pano_data:
38 | pano_id.append(item['pano_id'])
39 |
40 | # Check for next page
41 | next_page = pano_data_all['_links']['next']['href']
42 |
43 | return pano_id
44 |
45 | def get_pano_image(pano_id):
46 | """
47 | Get a panoramic image and its initial location coordinates
48 | and convert it from WGS84 (EPSG:4326) to Rijksdriehoek (EPSG:28992)
49 | """
50 | pano_url = f"https://api.data.amsterdam.nl/panorama/panoramas/{pano_id}/"
51 | with requests.get(pano_url) as response:
52 | pano_data = json.loads(response.content)
53 |
54 | geom = pano_data['geometry']['coordinates']
55 |
56 | # WGS84 to Rijksdriehoek (RD) conversion
57 | point = ogr.Geometry(ogr.wkbPoint)
58 | point.AddPoint(geom[0], geom[1])
59 | source = osr.SpatialReference()
60 | source.ImportFromEPSG(4326)
61 | target = osr.SpatialReference()
62 | target.ImportFromEPSG(28992)
63 | transform = osr.CoordinateTransformation(source, target)
64 | point.Transform(transform)
65 |
66 | # Get image_url from API
67 | image_url = pano_data['_links']['equirectangular_medium']['href']
68 |
69 | return str(image_url), (point.GetX(), point.GetY())
70 |
71 | def get_buildings_in_range(observer, radius):
72 | """
73 | For a panoramic image, get the buildings that are whitin a user defined range.
74 | """
75 | bag_url = f"https://api.data.amsterdam.nl/bag/pand/?locatie={observer[0]},{observer[1]},{radius}&detailed=!"
76 | with requests.get(bag_url) as response:
77 | bag_data = json.loads(response.content)['results']
78 |
79 | return bag_data
80 |
81 | def get_building_polygons(pand_json):
82 | """ Get the polygon of a building """
83 | building_polygons = {}
84 |
85 | # Loop over json content
86 | for item in pand_json:
87 | pand_id = item['pandidentificatie']
88 | pand_polygon = item['geometrie']['coordinates'][0]
89 |
90 | # A polygon should have at least 3 vertices to be a valid polygon
91 | if(len(pand_polygon) > 2 and pand_id):
92 | # Verify counter-clockwise winding order
93 | # TODO (Removed this because it happens rarely and slows the process down)
94 |
95 | building_polygons[pand_id] = pand_polygon
96 |
97 | return building_polygons
98 |
99 | def download_pano_image(pano_url):
100 | """ Download a panoramic image from the API """
101 | try:
102 | response = requests.get(pano_url)
103 | source_image = Image.open(BytesIO(response.content))
104 | except requests.exceptions.RequestException:
105 | print('HTTP Request failed. Aborting.')
106 | return
107 |
108 | return source_image
109 |
--------------------------------------------------------------------------------
/stage_1/src/array_image.py:
--------------------------------------------------------------------------------
1 | from numpy import squeeze, dsplit, asarray, dstack
2 | from scipy.ndimage import map_coordinates
3 |
4 | def get_as_rgb_array(image_file):
5 | """
6 | Gets the raw image prepared for calculations.
7 |
8 | :param image_file: loaded image file
9 | :return: numpy image array, an array of three color channels
10 | """
11 |
12 | # read image as numpy rgb image array
13 | panorama_array_image = asarray(image_file, dtype="int32")
14 | # split image in the 3 RGB channels
15 | return squeeze(dsplit(panorama_array_image, 3))
16 |
17 | def sample_rgb_array_image_as_array(coordinates, rgb_array):
18 | """
19 | Resampling of the source image
20 |
21 | :param coordinates: meshgrid of numpy arrays where each target coordinate is mapped to a coordinate set
22 | of the source
23 | :param rgb_array: the source image as a numpy rgb array representation
24 | :return: the sampled target image as a scipy rgb array representation
25 | """
26 | x = coordinates[0]
27 | y = coordinates[1]
28 |
29 | """
30 | Resample each channel of the source image.
31 | This needs to be done "per channel", otherwise the map_coordinates method
32 | works on the wrong dimension. From numpy.asarray(image) the first dimension
33 | is the channel (r, g and b), and 2nd and 3rd dimensions are y and x. But,
34 | map_coordinates expects the coordinates to map to be 1st and 2nd.
35 | Therefore, we extract each channel, so that y and x become 1st and 2nd
36 | array. After resampling, we stack the three channels on top of each other,
37 | to restore the rgb image array.
38 | """
39 |
40 | r = map_coordinates(rgb_array[0], [y, x], order=1)
41 | g = map_coordinates(rgb_array[1], [y, x], order=1)
42 | b = map_coordinates(rgb_array[2], [y, x], order=1)
43 |
44 | # Merge channels
45 | return dstack((r, g, b))
46 |
--------------------------------------------------------------------------------
/stage_1/src/array_math.py:
--------------------------------------------------------------------------------
1 | from numpy.core.umath import sqrt, square, arccos, arctan2, mod, pi
2 |
3 | # Helper constants for readability
4 | X, Y = 0, 1
5 |
6 | def vector(from_2d, to_2d):
7 | return to_2d[X] - from_2d[X], to_2d[Y] - from_2d[Y]
8 |
9 | def vector_length(vector_2d):
10 | return sqrt(vector_2d[X]**2 + vector_2d[Y]**2)
11 |
12 | def get_midpoint(vertices):
13 | return ((vertices[0][X] + vertices[1][X]) / 2, (vertices[0][Y] + vertices[1][Y]) / 2)
14 |
15 | def get_vector(to_point, from_point):
16 | """
17 | Calculate a 3D vector from from_point to to_point,
18 | also works on numpy 2D arrays of points
19 |
20 |
21 | :param to_point: 3d tuple of the point the vector will point to
22 | :param from_point: 3d tuple of the point the vector will point from
23 | :return: 3D tuple of the vector
24 | """
25 |
26 | return to_point[0] - from_point[0], \
27 | to_point[1] - from_point[1], \
28 | to_point[2] - from_point[2]
29 |
30 |
31 | def get_cartesian_vector_from_rd(to_point, from_point):
32 | """
33 | Calculate a 3D vector from from_point to to_point,
34 | also works on numpy 2D arrays of points,
35 | reorders dimensions from rd to cartesian
36 |
37 |
38 | :param to_point: 3d tuple of the point the vector will point to
39 | :param from_point: 3d tuple of the point the vector will point from
40 | :return: 3D tuple of the reordered vector
41 | """
42 |
43 | return to_point[1] - from_point[1], \
44 | to_point[0] - from_point[0], \
45 | to_point[2] - from_point[2]
46 |
47 |
48 | def cartesian2cylindrical(vector, source_width, source_height, r_is_1=True):
49 | """
50 | Calculates the location on a equirectangular plane of a vector,
51 | Will work with numpy's 2D arrays of points
52 |
53 | :param vector: 3d tuple of the point the vector
54 | :param source_width: width and
55 | :param source_height: height of the equirectangular image
56 | :param r_is_1: boolean, denoting if vectors are normalized to 1 (default=True)
57 | :return: 3D tuple of the coordinates of the vector on the equirectangular plane
58 | """
59 |
60 | middle = source_width / 2
61 |
62 | x = vector[0]
63 | y = vector[1]
64 | z = vector[2]
65 |
66 | # Vectors are defined by (r, theta, phi) and is given in Cartesian coordinates by:
67 | r = 1 if r_is_1 else sqrt(square(x) + square(y) + square(z))
68 | theta = arccos(z / r)
69 | phi = arctan2(y, x)
70 |
71 | x1 = mod(middle + middle * phi / pi, source_width - 1)
72 | y1 = source_height * theta / pi
73 |
74 | return x1, y1
75 |
--------------------------------------------------------------------------------
/stage_1/src/extract_texture.py:
--------------------------------------------------------------------------------
1 | """
2 | Previous work by the City of Amsterdam:
3 | https://github.com/Amsterdam/panorama-textures/
4 | """
5 |
6 | from math import atan2, pi
7 | from PIL import Image
8 | from numpy import linspace, float64, meshgrid, full, int32
9 | from src.array_math import get_vector, cartesian2cylindrical, vector, vector_length, get_midpoint
10 | from src.array_image import get_as_rgb_array, sample_rgb_array_image_as_array
11 |
12 | # helper constants for readability
13 | X, Y = 0, 1
14 |
15 | # We use the "panorama_4000" images, with the following dimensions
16 | SOURCE_WIDTH = 4000 # pixels
17 | PANO_HEIGHT = 2000 # pixels
18 |
19 | def project_facade(facade, observer, source_file, img_height, resolution, force=False):
20 | nx = int(round(facade["length"] * resolution))
21 | if nx > 0:
22 | # Gets the distances to facades with observer as middlepoint
23 | if not facade["forward_facing"] or (not 0.7 * pi > facade["viewing_angle"] > 0.3 * pi and not force):
24 | imarray = full((img_height, nx, 3), 128, dtype=int32)
25 | else:
26 | # 3D tuple of the vector
27 | vector_x, vector_y, vector_z = get_vector((facade["x-mesh"], facade["y-mesh"], facade["z-mesh"]), observer)
28 | # 3D tuple of the coordinates of the vector on the panoramic image (equirectangular plane)
29 | image_x, image_y = cartesian2cylindrical((vector_y, vector_x, vector_z), source_width=SOURCE_WIDTH,
30 | source_height=PANO_HEIGHT, r_is_1=False)
31 | # Load the source panoramic image, return numpy image array (an array of three color channels)
32 | source_rgb_array = get_as_rgb_array(source_file)
33 | # The sampled target image as a scipy rgb array representation
34 | imarray = sample_rgb_array_image_as_array((image_x, image_y), source_rgb_array)
35 | else:
36 | imarray = None
37 | return imarray
38 |
39 | def create_plane(hoogte, img_height, resolution, observer, vertices):
40 | # Create dict elements for later
41 | line = {
42 | "from": vertices[0],
43 | "to": vertices[1],
44 | "vector": vector(vertices[0], vertices[1])
45 | }
46 | # Get the width of the facade
47 | line["length"] = vector_length(line["vector"])
48 |
49 | # Get midpoint of the facade and the distance from this point to the observer
50 | midpoint = get_midpoint(vertices)
51 | to_midpoint = vector(observer, midpoint)
52 |
53 | # Calculate viewing angle from observer to facade
54 | if line["length"] == 0 or vector_length(to_midpoint) == 0:
55 | line["viewing_angle"] = 0
56 | else:
57 | dot = line["vector"][X]*to_midpoint[X] + line["vector"][Y]*to_midpoint[Y] # dot product
58 | det = line["vector"][X]*to_midpoint[Y] - line["vector"][Y]*to_midpoint[X] # determinant
59 | line["viewing_angle"] = atan2(det, dot)
60 |
61 | # Forward_facing is true when we have a viewing angle
62 | line["forward_facing"] = line["viewing_angle"] > 0
63 |
64 | # numpy: Create sequences of evenly spaced values within a defined interval
65 | nx = int(round(line["length"] * resolution))
66 | x = linspace(line["from"][X], line["to"][X], nx, dtype=float64)
67 | y = linspace(line["from"][Y], line["to"][Y], nx, dtype=float64)
68 | z = linspace(hoogte, 0, img_height, dtype=float64)
69 |
70 | # numpy: Return coordinate matrices from coordinate vectors
71 | gevel_x, _ = meshgrid(x, z)
72 | gevel_y, gevel_z = meshgrid(y, z)
73 | line["x-mesh"] = gevel_x
74 | line["y-mesh"] = gevel_y
75 | line["z-mesh"] = gevel_z
76 |
77 | # You can plot the grid. It will show the visible facade borders (2D top view)
78 | # from matplotlib import pyplot as plt
79 | # plt.plot(gevel_x, gevel_y, marker=".", color="k", linestyle="none")
80 |
81 | return line
82 |
83 | def export_line_to_texture(visible_points, resolution, image_height_irl, camera_height, source_image, pano_rd):
84 | observer = (pano_rd[0], pano_rd[1], camera_height)
85 |
86 | img_height = int(round(image_height_irl * resolution))
87 | plane = create_plane(image_height_irl, img_height, resolution, observer, visible_points)
88 | facade = project_facade(plane, observer, source_image, img_height, resolution, force=True)
89 |
90 | return Image.fromarray(facade.astype("uint8"), "RGB")
91 |
--------------------------------------------------------------------------------
/stage_1/src/furthest_pair.py:
--------------------------------------------------------------------------------
1 | """
2 | Code to determine the horizontal line segment of each facade, represented
3 | by bottom-left and bottom-right Rijksdriehoek corner points.
4 | """
5 |
6 | def get_furthest_pair(visible_points, observer):
7 | """
8 | We assume that the list of polygon points of a building is arranged
9 | in counter-clockwise order. The order is important to determine the
10 | left-to-right order used to extract a texture from a panoramic image.
11 |
12 | In this function, we get the furthest in the list while keeping the order
13 | of the list. However, in some lists the start and end value are the same
14 | and we have to perform an extra calculation.
15 |
16 | If there are two visible_points we directly return.
17 | """
18 | if len(visible_points) > 2:
19 | # Build a dict mapping values to indices
20 | list_order = {tuple(v):i for i, v in enumerate(visible_points)}
21 |
22 | # Are the start and end values the same
23 | if visible_points[0] == visible_points[-1]:
24 | # Determine the direction of the observer from the line segment
25 | # Lies the observer to the Right of Line Segment or to the Left of Line Segment.
26 | cross_product = direction_of_observer(visible_points[:-1], observer)
27 |
28 | # Search for two points with the largest distance in the list of visible polygon points
29 | furthest_pair = diameter(visible_points[:-1])
30 |
31 | # Sort list according to list in function direction_of_observer(...)
32 | visible_points = sorted(furthest_pair, key=lambda k: [k[1], k[0]])
33 |
34 | # Observer is on the right of line segment if cross product is positive
35 | if cross_product > 0:
36 | # Reverse the two points
37 | return [visible_points[-1], visible_points[0]]
38 | else:
39 | # Search for two points with the largest distance in the list of visible polygon points
40 | furthest_pair = diameter(visible_points)
41 |
42 | # Sort list according to original list, with uneven length
43 | visible_points = sorted(furthest_pair, key=lambda v: list_order[tuple(v)])
44 |
45 | return visible_points
46 |
47 | def direction_of_observer(visible_points, observer):
48 | """
49 | Determine direction of point from line segment
50 |
51 | Code is inspired by geeksforgeeks.org/direction-point-line-segment/
52 | """
53 |
54 | # A at the left side and B at the right, sort list on y-axis.
55 | visible_points = sorted(visible_points , key=lambda k: [k[1], k[0]])
56 |
57 | # Select two points from the sorted list
58 | aX = visible_points[0][0]
59 | aY = visible_points[0][1]
60 | bX = visible_points[-1][0]
61 | bY = visible_points[-1][1]
62 |
63 | # Subtracting co-ordinates of point A from B and P, to make A as origin
64 | bX = bX - aX
65 | bY = bY - aY
66 | pX = observer[0] - aX
67 | pY = observer[1] - aY
68 |
69 | # Determine the cross product
70 | cross_product = (bX * pY) - (bY * pX)
71 |
72 | return cross_product
73 |
74 | def orientation(p, q, r):
75 | """ Return positive if p-q-r are clockwise, neg if ccw, zero if colinear """
76 | return (q[1] - p[1]) * (r[0] - p[0]) - (q[0] - p[0]) * (r[1] - p[1])
77 |
78 | def hulls(points):
79 | """ Graham scan to find upper & lower convex hulls of a set of 2d points """
80 | U = []
81 | L = []
82 | points.sort()
83 | for p in points:
84 | while len(U) > 1 and orientation(U[-2], U[-1], p) <= 0:
85 | U.pop()
86 | while len(L) > 1 and orientation(L[-2], L[-1], p) >= 0:
87 | L.pop()
88 | U.append(p)
89 | L.append(p)
90 | return U, L
91 |
92 | def rotating_calipers(points):
93 | """
94 | Find all ways of sandwiching between parallel lines.
95 | Given a list of 2d points, finds all ways of sandwiching the points
96 | between two parallel lines that touch one point each, and
97 | yields the sequence of pairs of points touched by each pair of lines.
98 | """
99 | U, L = hulls(points)
100 | i = 0
101 | j = len(L) - 1
102 | while i < len(U) - 1 or j > 0:
103 | yield U[i], L[j]
104 |
105 | # if all the way through one side of hull, advance the other side
106 | if i == len(U) - 1:
107 | j -= 1
108 | elif j == 0:
109 | i += 1
110 | # still points left on both lists, compare slopes of next hull edges
111 | # being careful to avoid divide-by-zero in slope calculation
112 | elif (U[i + 1][1] - U[i][1]) * (L[j][0] - L[j - 1][0]) > \
113 | (L[j][1] - L[j - 1][1]) * (U[i + 1][0] - U[i][0]):
114 | i += 1
115 | else:
116 | j -= 1
117 |
118 | def diameter(points):
119 | """ Given a list of 2d points, returns the pair that's furthest apart """
120 | _, pair = max([((p[0] - q[0])**2 + (p[1] - q[1])**2, [p, q])
121 | for p, q in rotating_calipers(points)])
122 | return pair
123 |
--------------------------------------------------------------------------------
/stage_1/src/visible_view.py:
--------------------------------------------------------------------------------
1 | from skgeom import *
2 |
3 | def generate_arrangement(observer, building_polygons):
4 | """ Create a 2D arrangement using skgeom """
5 | arr = arrangement.Arrangement()
6 |
7 | set_range = 60
8 | left_x = observer[0] - set_range
9 | left_y = observer[1] - set_range
10 | right_x = observer[0] + set_range
11 | right_y = observer[1] + set_range
12 |
13 | walls = [
14 | Segment2(Point2(left_x, left_y), Point2(left_x, right_y)),
15 | Segment2(Point2(left_x, right_y), Point2(right_x, right_y)),
16 | Segment2(Point2(right_x, right_y), Point2(right_x, left_y)),
17 | Segment2(Point2(right_x, left_y), Point2(left_x, left_y))
18 | ]
19 |
20 | for s in walls:
21 | arr.insert(s)
22 |
23 | for poly in building_polygons:
24 | building_edges = points_2_edges(poly)
25 |
26 | for s in building_edges:
27 | arr.insert(s)
28 |
29 | return arr
30 |
31 | def points_2_edges(pts):
32 | """ Make edges """
33 | edges = []
34 | for i in range(1,len(pts)):
35 | e = Segment2(Point2(pts[i-1][0], pts[i-1][1]),
36 | Point2(pts[i][0], pts[i][1]))
37 | edges.append(e)
38 | return edges
39 |
40 | def get_visibility_polygon(arr, observer):
41 | """
42 | Compute the visibility from a specific point inside
43 | the arrangement
44 | """
45 | vs = TriangularExpansionVisibility(arr)
46 | q = Point2(observer[0], observer[1])
47 | face = arr.find(q)
48 | vx = vs.compute_visibility(q, face)
49 |
50 | ############### Draw Arrangement ###############
51 | # draw_arrangement(arr, vx, q)
52 |
53 | # Get all edges of Visibility Polygon
54 | allEdges = [v.point() for v in vx.vertices]
55 |
56 | return Polygon(allEdges)
57 |
58 | def draw_arrangement(arr, vx, q, save_file=False):
59 | """
60 | Draw 2D arrangement with buildings and initial
61 | panoramic image location
62 | """
63 | from matplotlib import pyplot as plt
64 |
65 | plt.figure(figsize=(10, 10))
66 | plt.xlabel("X Position")
67 | plt.ylabel("Y Position")
68 |
69 | # Draw walls and buildings
70 | for he in arr.halfedges:
71 | plt.plot([he.curve().source().x(), he.curve().target().x()],
72 | [he.curve().source().y(), he.curve().target().y()], "b")
73 |
74 | # Draw Visibility Polygon
75 | for he in vx.halfedges:
76 | plt.plot([he.curve().source().x(), he.curve().target().x()],
77 | [he.curve().source().y(), he.curve().target().y()], "r:")
78 |
79 | plt.scatter(q.x(), q.y(), color="b")
80 | if save_file:
81 | plt.savefig("vispol.eps", format="eps")
82 | else:
83 | plt.show()
84 |
85 | def point_in_visibility_polygon(building_poly, visibility_polygon):
86 | """ Check wether a given point is inside the visibility polygon """
87 | visible_points = []
88 |
89 | for x,y in building_poly:
90 | position = visibility_polygon.oriented_side(Point2(x, y))
91 | if position == Sign.ZERO or position == Sign.POSITIVE:
92 | visible_points.append([x, y])
93 |
94 | return visible_points
95 |
--------------------------------------------------------------------------------
/stage_2/test.py:
--------------------------------------------------------------------------------
1 | # Some basic setup
2 | # import some common libraries
3 | from collections import defaultdict
4 | import zipfile
5 | import os
6 | import numpy as np
7 | import cv2
8 | from PIL import Image
9 | import pandas as pd
10 | import matplotlib.pyplot as plt
11 | import matplotlib as mpl
12 |
13 | # Setup detectron2 logger
14 | import detectron2
15 | from detectron2.utils.logger import setup_logger
16 | setup_logger()
17 | # import some common detectron2 utilities
18 | from detectron2.config import get_cfg
19 | from detectron2.engine import DefaultPredictor
20 |
21 | OUTPUT_NAME = "output_stage2"
22 | DRAW_PREDICTIONS = False
23 |
24 | def draw_bbox(myfile, bboxes, filename):
25 | """
26 | Plot bbox in original image
27 | """
28 | # Create figure and axes
29 | fig,ax = plt.subplots(figsize=(10, 10))
30 | plt.axis("off")
31 |
32 | for box in bboxes:
33 | # Create a Rectangle patch
34 | x0, y0, x1, y1 = box
35 | width = x1 - x0
36 | height = y1 - y0
37 |
38 | rect = mpl.patches.Rectangle((x0, y0), width, height, linewidth=1,
39 | edgecolor="r", facecolor="none")
40 |
41 | # Add the patch to the Axes
42 | ax.add_patch(rect)
43 |
44 | # Read image in grayscale mode
45 | original_img = np.array(Image.fromarray(myfile))
46 | # Display the image
47 | ax.imshow(original_img, cmap = plt.cm.gray)
48 |
49 | fig.savefig(f"output_images/{filename}.png", dpi=200, bbox_inches="tight", pad_inches=0)
50 |
51 | def non_max_suppression(boxes, probs=None, overlap_thresh=0.15):
52 | """
53 | This is a Python version used to implement the Soft NMS algorithm.
54 | Original Paper:Soft-NMS--Improving Object Detection With One Line of Code
55 | """
56 | # If there are no boxes, return an empty list
57 | if len(boxes) == 0:
58 | return []
59 |
60 | # If the bounding boxes are integers, convert them to floats -- this
61 | # Is important since we"ll be doing a bunch of divisions
62 | if boxes.dtype.kind == "i":
63 | boxes = boxes.astype("float")
64 |
65 | # Initialize the list of picked indexes
66 | pick = []
67 |
68 | # grab the coordinates of the bounding boxes
69 | x1 = boxes[:, 0]
70 | y1 = boxes[:, 1]
71 | x2 = boxes[:, 2]
72 | y2 = boxes[:, 3]
73 |
74 | # Compute the area of the bounding boxes and grab the indexes to sort
75 | # (in the case that no probabilities are provided, simply sort on the
76 | # bottom-left y-coordinate)
77 | area = (x2 - x1 + 1) * (y2 - y1 + 1)
78 | idxs = y2
79 |
80 | # If probabilities are provided, sort on them instead
81 | if probs is not None:
82 | idxs = probs
83 |
84 | # Sort the indexes
85 | idxs = np.argsort(idxs)
86 |
87 | # Keep looping while some indexes still remain in the indexes list
88 | while len(idxs) > 0:
89 | # grab the last index in the indexes list and add the index value
90 | # to the list of picked indexes
91 | last = len(idxs) - 1
92 | i = idxs[last]
93 | pick.append(i)
94 |
95 | # find the largest (x, y) coordinates for the start of the bounding
96 | # box and the smallest (x, y) coordinates for the end of the bounding
97 | # box
98 | xx1 = np.maximum(x1[i], x1[idxs[:last]])
99 | yy1 = np.maximum(y1[i], y1[idxs[:last]])
100 | xx2 = np.minimum(x2[i], x2[idxs[:last]])
101 | yy2 = np.minimum(y2[i], y2[idxs[:last]])
102 |
103 | # compute the width and height of the bounding box
104 | w = np.maximum(0, xx2 - xx1 + 1)
105 | h = np.maximum(0, yy2 - yy1 + 1)
106 |
107 | # compute the ratio of overlap
108 | overlap = (w * h) / area[idxs[:last]]
109 |
110 | # delete all indexes from the index list that have overlap greater
111 | # than the provided overlap threshold
112 | idxs = np.delete(idxs, np.concatenate(([last],
113 | np.where(overlap > overlap_thresh)[0])))
114 |
115 | # return only the bounding boxes that were picked
116 | return boxes[pick].astype("float")
117 |
118 | def instances_to_dict(all_instances, filename, class_names):
119 | """
120 | Save the predicted bounding boxes to a dictionary
121 | """
122 | num_instances = len(all_instances)
123 | if num_instances == 0:
124 | return None
125 |
126 | classes = all_instances.pred_classes
127 | labels = [class_names[x] for x in classes]
128 | boxes = all_instances.pred_boxes.tensor.numpy()
129 | scores = all_instances.scores.numpy()
130 |
131 | predictions = defaultdict(list)
132 | predictions_temp = defaultdict(list)
133 |
134 | predictions["texture_filename"] = filename
135 |
136 | for i in range(num_instances):
137 | if labels[i] == "window":
138 | predictions_temp["bboxes_window"].append(boxes[i])
139 | predictions_temp["scores_window"].append(scores[i])
140 | elif labels[i] == "door":
141 | predictions_temp["bboxes_door"].append(boxes[i])
142 | predictions_temp["scores_door"].append(scores[i])
143 |
144 | # Non max suppression
145 | bboxes_window = non_max_suppression(np.array(predictions_temp["bboxes_window"]),
146 | predictions_temp["scores_window"])
147 | bboxes_door = non_max_suppression(np.array(predictions_temp["bboxes_door"]),
148 | predictions_temp["scores_door"])
149 |
150 | # bboxes rounded to 1 decimal
151 | predictions["bboxes_window"] = [[np.round(float(i), 1) for i in nested] for nested in bboxes_window]
152 | predictions["bboxes_door"] = [[np.round(float(i), 1) for i in nested] for nested in bboxes_door]
153 |
154 | return predictions
155 |
156 | def main():
157 | """
158 | An example script on how to iterate over the images in a zip file
159 | and get predictions from Mask R-CNN.
160 | """
161 | class_names = ["sky", "window", "door"]
162 | cfg = get_cfg()
163 | cfg.merge_from_file(
164 | "detectron2/configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml"
165 | ) # Faster and BBOX only, train with: detectron2/configs/COCO-Detection/faster_rcnn_R_50_FPN_3x.yaml
166 | cfg.OUTPUT_DIR = "model_output"
167 | cfg.MODEL.WEIGHTS = os.path.join(cfg.OUTPUT_DIR, "model.pth")
168 | cfg.MODEL.ROI_HEADS.NUM_CLASSES = len(class_names)
169 | cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.7
170 | predictor = DefaultPredictor(cfg)
171 |
172 | # An example on how to use zipfile
173 | zip_file = zipfile.ZipFile("datasets/test/images.zip")
174 |
175 | rows_list = []
176 | for name in zip_file.namelist():
177 | if name.endswith(".jpeg"):
178 | filename = name.split("/")[-1].split(".jpeg")[0]
179 |
180 | # Open the images with the openCV reader because BGR order is used in Detectron2
181 | pic = zip_file.read(name)
182 | im = cv2.imdecode(np.frombuffer(pic, np.uint8), 1)
183 |
184 | if im is not None:
185 | outputs = predictor(im)
186 |
187 | all_instances = outputs["instances"].to("cpu")
188 |
189 | # Save the predicted bounding boxes to a dict
190 | predictions = instances_to_dict(all_instances, filename, class_names)
191 |
192 | if predictions is not None:
193 | # Draw predictions
194 | if DRAW_PREDICTIONS:
195 | draw_bbox(im, predictions["bboxes_window"] + predictions["bboxes_door"], filename)
196 |
197 | # Save the data to the list
198 | rows_list.append(predictions)
199 |
200 | # Save this file
201 | df_output = pd.DataFrame(rows_list)
202 | compression_opts = dict(method="zip", archive_name = OUTPUT_NAME + ".csv")
203 | df_output.to_csv(OUTPUT_NAME + ".zip", index=False, compression=compression_opts)
204 |
205 | if __name__ == "__main__":
206 | main()
207 |
--------------------------------------------------------------------------------
/stage_3/CSV/output_stage1.csv:
--------------------------------------------------------------------------------
1 | pand_id,visible_point_one,visible_point_two,texture_filename
2 | 0363100012159183,"(120757.85, 485137.872)","(120752.833, 485136.497)",0363100012159183_8.463423
3 | 0363100012152551,"(120752.833, 485136.497)","(120747.69, 485135.087)",0363100012152551_8.426128
4 | 0363100012152951,"(120747.69, 485135.087)","(120742.78, 485133.741)",0363100012152951_8.338701
5 | 0363100012166458,"(120739.117, 485148.297)","(120744.082, 485149.661)",0363100012166458_6.476083
6 | 0363100012157182,"(120744.082, 485149.661)","(120749.263, 485151.085)",0363100012157182_6.40601
7 | 0363100012165513,"(120749.263, 485151.085)","(120754.332, 485152.478)",0363100012165513_6.381795
8 |
--------------------------------------------------------------------------------
/stage_3/CSV/output_stage2.csv:
--------------------------------------------------------------------------------
1 | texture_filename,bboxes_window,bboxes_door
2 | 0363100012159183_8.463423,"[[15.9, 637.9, 48.8, 698.0], [105.8, 557.2, 139.1, 615.4], [105.9, 638.4, 139.3, 698.4], [107.0, 720.0, 139.8, 781.2], [59.7, 557.9, 94.8, 615.6], [16.3, 719.8, 48.9, 780.5], [60.9, 719.2, 94.2, 781.4], [17.9, 556.0, 47.0, 615.4], [61.1, 638.0, 94.1, 697.6], [116.3, 814.5, 138.7, 834.0], [46.1, 814.2, 102.3, 873.1], [11.3, 812.2, 32.7, 833.2], [63.2, 481.3, 90.0, 511.5]]","[[13.3, 834.8, 32.5, 892.5], [117.3, 834.0, 139.6, 894.8]]"
3 | 0363100012152551_8.426128,"[[106.0, 558.6, 138.6, 616.3], [15.7, 720.4, 47.7, 780.6], [105.7, 639.5, 138.7, 698.8], [17.2, 805.1, 48.9, 871.1], [15.0, 558.0, 48.0, 616.2], [106.2, 721.1, 138.1, 780.9], [15.3, 639.3, 47.7, 699.6], [61.8, 804.8, 93.9, 870.0], [60.2, 559.2, 93.1, 626.8], [60.1, 639.7, 93.5, 706.6], [60.4, 721.9, 93.9, 791.5], [61.4, 477.6, 91.3, 512.3], [106.6, 803.7, 138.6, 830.4]]","[[122.8, 830.7, 139.0, 886.8], [106.2, 830.9, 120.6, 887.1]]"
4 | 0363100012152951_8.338701,"[[105.1, 805.4, 136.4, 869.4], [13.9, 639.9, 46.2, 700.1], [104.7, 720.9, 137.3, 782.2], [13.9, 560.4, 46.2, 618.1], [104.6, 561.1, 135.8, 617.9], [58.7, 559.9, 91.5, 626.6], [104.7, 640.9, 136.6, 699.7], [15.0, 720.8, 47.3, 781.2], [58.8, 641.0, 91.4, 708.9], [61.0, 806.7, 91.9, 875.7], [60.3, 722.5, 92.3, 790.9], [59.2, 483.9, 87.4, 516.3], [15.7, 807.8, 32.0, 830.0]]","[[15.2, 830.0, 34.4, 874.7]]"
5 | 0363100012166458_6.476083,"[[111.4, 709.7, 146.3, 769.8], [13.8, 535.9, 50.0, 598.3], [109.7, 538.1, 146.2, 598.7], [111.3, 624.5, 145.7, 684.1], [16.6, 624.8, 51.1, 685.1], [62.5, 536.9, 97.6, 608.7], [63.2, 625.4, 98.5, 693.0], [16.4, 707.7, 52.0, 771.2], [63.7, 709.9, 98.8, 782.9], [66.6, 447.8, 95.6, 476.5], [50.6, 800.9, 114.0, 880.0], [15.9, 796.5, 30.8, 824.2], [128.5, 798.9, 150.5, 821.2]]","[[128.5, 822.4, 151.9, 894.5], [17.8, 822.8, 37.9, 891.7]]"
6 | 0363100012157182_6.40601,"[[21.2, 708.8, 57.3, 770.4], [117.7, 534.5, 154.2, 597.4], [21.7, 622.2, 57.6, 684.6], [21.3, 533.7, 56.6, 595.4], [70.6, 624.1, 105.6, 693.5], [119.8, 709.8, 154.5, 771.6], [119.3, 623.9, 154.4, 684.6], [68.4, 533.7, 105.5, 607.2], [71.2, 708.9, 105.8, 780.2], [72.9, 446.1, 102.9, 474.1], [23.2, 813.2, 57.9, 860.7], [72.1, 815.1, 105.4, 891.5], [130.5, 802.0, 152.8, 824.3]]","[[137.3, 827.0, 154.3, 888.6]]"
7 | 0363100012165513_6.381795,"[[15.3, 536.1, 52.3, 596.5], [111.5, 534.1, 149.5, 595.6], [113.6, 622.9, 148.9, 683.3], [64.4, 623.0, 100.0, 693.1], [112.8, 708.5, 148.6, 769.5], [63.0, 533.0, 99.7, 605.9], [15.8, 622.8, 51.3, 684.7], [114.5, 812.3, 148.2, 877.8], [15.1, 709.6, 51.5, 773.1], [64.6, 708.4, 99.8, 781.2], [65.4, 811.9, 99.8, 881.0], [66.6, 443.8, 97.7, 473.2], [24.2, 803.0, 42.5, 823.8]]","[[22.6, 827.0, 44.3, 885.4]]"
8 |
--------------------------------------------------------------------------------
/stage_3/CityGML/LOD2_120700-485100.gml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | 119991.992 484983.813 -3.699
6 | 121028.016 486009.906 48.769
7 |
8 |
9 |
10 |
11 | 0363100012159183
12 |
13 |
14 | 120752.8359375 485124.875 0.325658679008484
15 | 120761.5078125 485137.59375 15.497091293335
16 |
17 |
18 | 2020-02-09
19 |
20 | 120000.0 485000.0 121000.0 486000.0
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 | plat dak
44 | 2020-02-09
45 |
46 |
47 |
48 |
49 |
50 |
51 | 120756.367 485124.875 15.219 120761.125 485127.375 15.121 120752.867 485136.344 15.365 120756.367 485124.875 15.219
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 | 120756.328 485124.875 15.218 120752.867 485136.344 15.365 120752.836 485136.344 15.363 120756.328 485124.875 15.218
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 | 120756.367 485124.875 15.219 120752.867 485136.344 15.365 120756.328 485124.875 15.218 120756.367 485124.875 15.219
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 | 120752.867 485136.344 15.365 120761.125 485127.375 15.121 120757.883 485137.594 15.497 120752.867 485136.344 15.365
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 | 120756.367 485124.875 15.219 120761.477 485126.531 15.358 120761.125 485127.375 15.121 120756.367 485124.875 15.219
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 | gevel
99 | 2020-02-09
100 |
101 |
102 |
103 |
104 |
105 |
106 | 120761.125 485127.375 15.121 120761.477 485126.531 15.358 120761.508 485126.094 0.341 120761.125 485127.375 0.652 120757.883 485137.594 0.326 120757.883 485137.594 15.497 120761.125 485127.375 15.121
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 | 120752.844 485136.781 0.587 120756.328 485124.875 0.748 120756.328 485124.875 15.218 120752.836 485136.344 15.363 120752.844 485136.781 0.587
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 | 120756.328 485124.875 0.748 120756.367 485124.875 0.75 120756.367 485124.875 15.219 120756.328 485124.875 15.218 120756.328 485124.875 0.748
125 |
126 |
127 |
128 |
129 |
130 |
131 |
132 |
133 | 120752.836 485136.344 15.363 120752.867 485136.344 15.365 120752.875 485136.781 0.589 120752.844 485136.781 0.587 120752.836 485136.344 15.363
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 | 120756.367 485124.875 0.75 120761.508 485126.094 0.341 120761.477 485126.531 15.358 120756.367 485124.875 15.219 120756.367 485124.875 0.75
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 |
151 | 120757.883 485137.594 0.326 120752.875 485136.781 0.589 120752.867 485136.344 15.365 120757.883 485137.594 15.497 120757.883 485137.594 0.326
152 |
153 |
154 |
155 |
156 |
157 |
158 |
159 |
160 |
161 |
162 |
163 |
164 | 0363100012152551
165 |
166 |
167 | 120747.7265625 485123.625 0.527597308158875
168 | 120756.3671875 485136.78125 15.6199321746826
169 |
170 |
171 | 2020-02-09
172 |
173 | 120000.0 485000.0 121000.0 486000.0
174 |
175 |
176 |
177 |
178 |
179 |
180 |
181 |
182 |
183 |
184 |
185 |
186 |
187 |
188 |
189 |
190 |
191 |
192 |
193 |
194 | plat dak
195 | 2020-02-09
196 |
197 |
198 |
199 |
200 |
201 |
202 | 120750.398 485126.188 15.149 120752.836 485136.344 15.363 120747.727 485135.125 15.62 120750.398 485126.188 15.149
203 |
204 |
205 |
206 |
207 |
208 |
209 |
210 |
211 | 120751.125 485123.625 15.228 120756.367 485124.875 15.219 120750.398 485126.188 15.149 120751.125 485123.625 15.228
212 |
213 |
214 |
215 |
216 |
217 |
218 |
219 |
220 | 120756.367 485124.875 15.219 120752.836 485136.344 15.363 120752.836 485136.344 15.363 120756.367 485124.875 15.219
221 |
222 |
223 |
224 |
225 |
226 |
227 |
228 |
229 | 120752.836 485136.344 15.363 120752.836 485136.344 15.363 120747.727 485135.125 15.62 120752.836 485136.344 15.363
230 |
231 |
232 |
233 |
234 |
235 |
236 |
237 |
238 | 120756.367 485124.875 15.219 120752.836 485136.344 15.363 120750.398 485126.188 15.149 120756.367 485124.875 15.219
239 |
240 |
241 |
242 |
243 |
244 |
245 |
246 |
247 |
248 |
249 | gevel
250 | 2020-02-09
251 |
252 |
253 |
254 |
255 |
256 |
257 | 120752.844 485136.781 0.587 120747.727 485135.125 0.601 120747.727 485135.125 15.62 120752.836 485136.344 15.363 120752.844 485136.781 0.587
258 |
259 |
260 |
261 |
262 |
263 |
264 |
265 |
266 | 120751.125 485123.625 15.228 120750.398 485126.188 15.149 120747.727 485135.125 15.62 120747.727 485135.125 0.601 120750.398 485126.188 0.528 120751.125 485123.625 0.604 120751.125 485123.625 15.228
267 |
268 |
269 |
270 |
271 |
272 |
273 |
274 |
275 | 120751.125 485123.625 0.604 120756.328 485124.875 0.748 120756.367 485124.875 15.219 120751.125 485123.625 15.228 120751.125 485123.625 0.604
276 |
277 |
278 |
279 |
280 |
281 |
282 |
283 |
284 | 120756.328 485124.875 0.748 120752.844 485136.781 0.587 120752.836 485136.344 15.363 120756.367 485124.875 15.219 120756.328 485124.875 0.748
285 |
286 |
287 |
288 |
289 |
290 |
291 |
292 |
293 |
294 |
295 |
296 |
297 | 0363100012152951
298 |
299 |
300 | 120742.78125 485121.96875 0.471437335014343
301 | 120751.125 485135.125 15.6199321746826
302 |
303 |
304 | 2020-02-09
305 |
306 | 120000.0 485000.0 121000.0 486000.0
307 |
308 |
309 |
310 |
311 |
312 |
313 |
314 |
315 |
316 |
317 |
318 |
319 |
320 |
321 |
322 |
323 |
324 | plat dak
325 | 2020-02-09
326 |
327 |
328 |
329 |
330 |
331 |
332 | 120746.109 485121.969 15.094 120751.125 485123.625 15.228 120747.727 485135.125 15.62 120746.109 485121.969 15.094
333 |
334 |
335 |
336 |
337 |
338 |
339 |
340 |
341 | 120742.781 485133.875 15.491 120746.109 485121.969 15.094 120747.727 485135.125 15.62 120742.781 485133.875 15.491
342 |
343 |
344 |
345 |
346 |
347 |
348 |
349 |
350 |
351 |
352 | gevel
353 | 2020-02-09
354 |
355 |
356 |
357 |
358 |
359 |
360 | 120742.781 485133.438 0.471 120746.141 485121.969 0.472 120746.109 485121.969 15.094 120742.781 485133.875 15.491 120742.781 485133.438 0.471
361 |
362 |
363 |
364 |
365 |
366 |
367 |
368 |
369 | 120747.727 485135.125 0.601 120742.781 485133.438 0.471 120742.781 485133.875 15.491 120747.727 485135.125 15.62 120747.727 485135.125 0.601
370 |
371 |
372 |
373 |
374 |
375 |
376 |
377 |
378 | 120751.125 485123.625 15.228 120746.109 485121.969 15.094 120746.141 485121.969 0.472 120751.125 485123.625 0.604 120751.125 485123.625 15.228
379 |
380 |
381 |
382 |
383 |
384 |
385 |
386 |
387 | 120751.125 485123.625 0.604 120747.727 485135.125 0.601 120747.727 485135.125 15.62 120751.125 485123.625 15.228 120751.125 485123.625 0.604
388 |
389 |
390 |
391 |
392 |
393 |
394 |
395 |
396 |
397 |
398 |
399 |
400 | 0363100012166458
401 |
402 |
403 | 120735.9375 485148.34375 0.363241076469421
404 | 120744.125 485161.0625 16.9060039520264
405 |
406 |
407 | 2020-02-09
408 |
409 | 120000.0 485000.0 121000.0 486000.0
410 |
411 |
412 |
413 |
414 |
415 |
416 |
417 |
418 |
419 |
420 |
421 |
422 |
423 |
424 |
425 |
426 |
427 |
428 |
429 |
430 |
431 |
432 |
433 |
434 |
435 |
436 |
437 |
438 |
439 |
440 |
441 |
442 |
443 |
444 |
445 | plat dak
446 | 2020-02-09
447 |
448 |
449 |
450 |
451 |
452 |
453 | 120738.508 485154.281 16.906 120744.125 485149.563 16.511 120742.438 485155.094 16.741 120738.508 485154.281 16.906
454 |
455 |
456 |
457 |
458 |
459 |
460 |
461 |
462 | 120737.367 485154.719 16.388 120742.445 485155.531 16.435 120741.047 485160.188 16.041 120737.367 485154.719 16.388
463 |
464 |
465 |
466 |
467 |
468 |
469 |
470 |
471 | 120738.469 485153.844 16.356 120742.438 485155.094 16.191 120742.445 485155.531 16.435 120738.469 485153.844 16.356
472 |
473 |
474 |
475 |
476 |
477 |
478 |
479 |
480 | 120739.148 485148.344 16.776 120739.148 485148.344 16.776 120744.125 485149.563 16.511 120739.148 485148.344 16.776
481 |
482 |
483 |
484 |
485 |
486 |
487 |
488 |
489 | 120739.148 485148.344 16.776 120738.508 485154.281 16.906 120737.367 485154.719 16.54 120739.148 485148.344 16.776
490 |
491 |
492 |
493 |
494 |
495 |
496 |
497 |
498 | 120737.367 485154.719 16.388 120738.469 485153.844 16.356 120742.445 485155.531 16.435 120737.367 485154.719 16.388
499 |
500 |
501 |
502 |
503 |
504 |
505 |
506 |
507 | 120737.367 485154.719 16.388 120741.047 485160.188 16.041 120735.977 485159.813 16.39 120737.367 485154.719 16.388
508 |
509 |
510 |
511 |
512 |
513 |
514 |
515 |
516 | 120739.148 485148.344 16.776 120744.125 485149.563 16.511 120738.508 485154.281 16.906 120739.148 485148.344 16.776
517 |
518 |
519 |
520 |
521 |
522 |
523 |
524 |
525 | 120735.977 485159.813 16.39 120741.047 485160.188 16.041 120740.18 485161.063 16.084 120735.977 485159.813 16.39
526 |
527 |
528 |
529 |
530 |
531 |
532 |
533 |
534 | 120740.18 485161.063 16.084 120741.047 485160.188 16.041 120740.852 485160.625 16.12 120740.18 485161.063 16.084
535 |
536 |
537 |
538 |
539 |
540 |
541 |
542 |
543 | 120742.438 485155.094 16.741 120744.125 485149.563 16.511 120742.438 485155.094 16.587 120742.438 485155.094 16.741
544 |
545 |
546 |
547 |
548 |
549 |
550 |
551 |
552 |
553 |
554 | gevel
555 | 2020-02-09
556 |
557 |
558 |
559 |
560 |
561 |
562 | 120741.047 485160.188 0.716 120740.859 485161.063 0.795 120740.852 485160.625 16.12 120741.047 485160.188 16.041 120742.445 485155.531 16.435 120742.445 485155.531 0.714 120741.047 485160.188 0.716
563 |
564 |
565 |
566 |
567 |
568 |
569 |
570 |
571 | 120737.336 485154.719 0.665 120739.148 485148.344 0.506 120739.148 485148.344 16.776 120737.367 485154.719 16.54 120737.336 485154.719 0.665
572 |
573 |
574 |
575 |
576 |
577 |
578 |
579 |
580 | 120744.125 485149.563 16.511 120739.148 485148.344 16.776 120739.148 485148.344 0.506 120744.094 485149.563 0.637 120744.125 485149.563 16.511
581 |
582 |
583 |
584 |
585 |
586 |
587 |
588 |
589 | 120744.094 485149.563 0.637 120742.445 485155.531 0.714 120742.438 485155.094 16.587 120744.125 485149.563 16.511 120744.094 485149.563 0.637
590 |
591 |
592 |
593 |
594 |
595 |
596 |
597 |
598 | 120740.172 485160.625 0.363 120735.938 485159.375 0.667 120735.977 485159.813 16.39 120740.18 485161.063 16.084 120740.172 485160.625 0.363
599 |
600 |
601 |
602 |
603 |
604 |
605 |
606 |
607 | 120738.469 485153.844 16.356 120737.367 485154.719 16.388 120737.367 485154.719 16.54 120738.469 485153.844 16.356
608 |
609 |
610 |
611 |
612 |
613 |
614 |
615 |
616 | 120737.367 485154.719 16.54 120738.508 485154.281 16.906 120738.469 485153.844 16.356 120737.367 485154.719 16.54
617 |
618 |
619 |
620 |
621 |
622 |
623 |
624 |
625 | 120740.859 485161.063 0.795 120740.172 485160.625 0.363 120740.852 485160.625 16.12 120740.859 485161.063 0.795
626 |
627 |
628 |
629 |
630 |
631 |
632 |
633 |
634 | 120740.18 485161.063 16.084 120740.852 485160.625 16.12 120740.172 485160.625 0.363 120740.18 485161.063 16.084
635 |
636 |
637 |
638 |
639 |
640 |
641 |
642 |
643 | 120737.367 485154.719 16.388 120735.977 485159.813 16.39 120735.938 485159.375 0.667 120737.336 485154.719 0.665 120737.367 485154.719 16.388
644 |
645 |
646 |
647 |
648 |
649 |
650 |
651 |
652 | 120738.508 485154.281 16.906 120742.438 485155.094 16.741 120742.438 485155.094 16.191 120738.469 485153.844 16.356 120738.508 485154.281 16.906
653 |
654 |
655 |
656 |
657 |
658 |
659 |
660 |
661 | 120742.445 485155.531 16.435 120742.438 485155.094 16.191 120742.438 485155.094 16.741 120742.445 485155.531 16.435
662 |
663 |
664 |
665 |
666 |
667 |
668 |
669 |
670 | 120742.438 485155.094 16.741 120742.438 485155.094 16.587 120742.445 485155.531 16.435 120742.438 485155.094 16.741
671 |
672 |
673 |
674 |
675 |
676 |
677 |
678 |
679 |
680 |
681 |
682 |
683 | 0363100012157182
684 |
685 |
686 | 120741.046875 485149.5625 0.456102252006531
687 | 120749.265625 485161.875 16.6519565582275
688 |
689 |
690 | 2020-02-09
691 |
692 | 120000.0 485000.0 121000.0 486000.0
693 |
694 |
695 |
696 |
697 |
698 |
699 |
700 |
701 |
702 |
703 |
704 |
705 |
706 |
707 |
708 |
709 |
710 |
711 |
712 |
713 |
714 |
715 | plat dak
716 | 2020-02-09
717 |
718 |
719 |
720 |
721 |
722 |
723 | 120749.266 485151.219 16.652 120746.125 485161.875 16.025 120742.352 485160.625 16.198 120749.266 485151.219 16.652
724 |
725 |
726 |
727 |
728 |
729 |
730 |
731 |
732 | 120744.125 485149.563 16.511 120742.352 485160.625 16.198 120741.047 485160.188 16.041 120744.125 485149.563 16.511
733 |
734 |
735 |
736 |
737 |
738 |
739 |
740 |
741 | 120749.266 485151.219 16.652 120742.352 485160.625 16.198 120744.125 485149.563 16.511 120749.266 485151.219 16.652
742 |
743 |
744 |
745 |
746 |
747 |
748 |
749 |
750 | 120742.352 485160.625 16.198 120746.125 485161.875 16.025 120741.047 485160.188 16.041 120742.352 485160.625 16.198
751 |
752 |
753 |
754 |
755 |
756 |
757 |
758 |
759 | 120744.125 485149.563 16.511 120749.266 485151.219 16.652 120744.125 485149.563 16.511 120744.125 485149.563 16.511
760 |
761 |
762 |
763 |
764 |
765 |
766 |
767 |
768 | 120741.047 485160.188 16.041 120744.125 485149.563 16.511 120744.125 485149.563 16.511 120741.047 485160.188 16.041
769 |
770 |
771 |
772 |
773 |
774 |
775 |
776 |
777 |
778 |
779 | gevel
780 | 2020-02-09
781 |
782 |
783 |
784 |
785 |
786 |
787 | 120746.125 485161.875 16.025 120749.266 485151.219 16.652 120749.266 485151.219 0.779 120746.125 485161.438 0.456 120746.125 485161.875 16.025
788 |
789 |
790 |
791 |
792 |
793 |
794 |
795 |
796 | 120744.094 485149.563 0.637 120749.266 485151.219 0.779 120749.266 485151.219 16.652 120744.125 485149.563 16.511 120744.094 485149.563 0.637
797 |
798 |
799 |
800 |
801 |
802 |
803 |
804 |
805 | 120744.125 485149.563 16.511 120741.047 485160.188 16.041 120741.047 485160.188 0.716 120744.094 485149.563 0.637 120744.125 485149.563 16.511
806 |
807 |
808 |
809 |
810 |
811 |
812 |
813 |
814 | 120741.047 485160.188 16.041 120742.352 485160.625 16.198 120746.125 485161.875 16.025 120742.352 485160.625 0.477 120741.047 485160.188 0.716 120741.047 485160.188 16.041
815 |
816 |
817 |
818 |
819 |
820 |
821 |
822 |
823 | 120746.125 485161.438 0.456 120742.352 485160.625 0.477 120746.125 485161.875 16.025 120746.125 485161.438 0.456
824 |
825 |
826 |
827 |
828 |
829 |
830 |
831 |
832 |
833 |
834 |
835 |
836 | 0363100012165513
837 |
838 |
839 | 120746.125 485151.21875 0.366395831108093
840 | 120754.375 485163.09375 16.6519565582275
841 |
842 |
843 | 2020-02-09
844 |
845 | 120000.0 485000.0 121000.0 486000.0
846 |
847 |
848 |
849 |
850 |
851 |
852 |
853 |
854 |
855 |
856 |
857 |
858 |
859 |
860 |
861 |
862 |
863 |
864 |
865 | plat dak
866 | 2020-02-09
867 |
868 |
869 |
870 |
871 |
872 |
873 | 120754.375 485152.469 16.637 120751.109 485163.094 16.156 120754.344 485152.469 16.636 120754.375 485152.469 16.637
874 |
875 |
876 |
877 |
878 |
879 |
880 |
881 |
882 | 120751.109 485163.094 16.156 120746.125 485161.875 16.025 120749.266 485151.219 16.652 120751.109 485163.094 16.156
883 |
884 |
885 |
886 |
887 |
888 |
889 |
890 |
891 | 120751.109 485163.094 16.156 120749.266 485151.219 16.652 120754.344 485152.469 16.636 120751.109 485163.094 16.156
892 |
893 |
894 |
895 |
896 |
897 |
898 |
899 |
900 |
901 |
902 | gevel
903 | 2020-02-09
904 |
905 |
906 |
907 |
908 |
909 |
910 | 120754.375 485152.469 16.637 120754.344 485152.469 16.636 120754.344 485152.469 0.366 120754.375 485152.469 16.637
911 |
912 |
913 |
914 |
915 |
916 |
917 |
918 |
919 | 120751.109 485163.094 16.156 120754.375 485152.469 16.637 120754.344 485152.469 0.366 120751.07 485162.688 0.587 120751.109 485163.094 16.156
920 |
921 |
922 |
923 |
924 |
925 |
926 |
927 |
928 | 120754.344 485152.469 16.636 120749.266 485151.219 16.652 120749.266 485151.219 0.779 120754.344 485152.469 0.366 120754.344 485152.469 16.636
929 |
930 |
931 |
932 |
933 |
934 |
935 |
936 |
937 | 120749.266 485151.219 16.652 120746.125 485161.875 16.025 120746.125 485161.438 0.456 120749.266 485151.219 0.779 120749.266 485151.219 16.652
938 |
939 |
940 |
941 |
942 |
943 |
944 |
945 |
946 | 120751.07 485162.688 0.587 120746.125 485161.438 0.456 120746.125 485161.875 16.025 120751.109 485163.094 16.156 120751.07 485162.688 0.587
947 |
948 |
949 |
950 |
951 |
952 |
953 |
954 |
955 |
956 |
957 |
--------------------------------------------------------------------------------
/stage_3/images/0363100012152551_8.426128.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chrise96/3D_building_reconstruction/86539cd14689109ca9bc41b6fc7e21231623bc77/stage_3/images/0363100012152551_8.426128.jpeg
--------------------------------------------------------------------------------
/stage_3/images/0363100012152951_8.338701.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chrise96/3D_building_reconstruction/86539cd14689109ca9bc41b6fc7e21231623bc77/stage_3/images/0363100012152951_8.338701.jpeg
--------------------------------------------------------------------------------
/stage_3/images/0363100012157182_6.40601.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chrise96/3D_building_reconstruction/86539cd14689109ca9bc41b6fc7e21231623bc77/stage_3/images/0363100012157182_6.40601.jpeg
--------------------------------------------------------------------------------
/stage_3/images/0363100012159183_8.463423.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chrise96/3D_building_reconstruction/86539cd14689109ca9bc41b6fc7e21231623bc77/stage_3/images/0363100012159183_8.463423.jpeg
--------------------------------------------------------------------------------
/stage_3/images/0363100012165513_6.381795.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chrise96/3D_building_reconstruction/86539cd14689109ca9bc41b6fc7e21231623bc77/stage_3/images/0363100012165513_6.381795.jpeg
--------------------------------------------------------------------------------
/stage_3/images/0363100012166458_6.476083.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chrise96/3D_building_reconstruction/86539cd14689109ca9bc41b6fc7e21231623bc77/stage_3/images/0363100012166458_6.476083.jpeg
--------------------------------------------------------------------------------
/stage_3/insert_bboxes.py:
--------------------------------------------------------------------------------
1 | """
2 | The detected rectangles in a two-dimensional image are given via four pixel values:
3 | xleft, xright, ytop, ybottom. These values are transformed to three-dimensional
4 | coordinates in order to integrate them in a building in the 3D model.
5 | """
6 |
7 | import pandas as pd
8 | import time
9 | import os
10 | from lxml import etree as ET
11 | from PIL import Image
12 | import collections
13 |
14 | from src.geometry import *
15 | from src.furthest_pair import *
16 |
17 | CITYGML_PATH = "CityGML/LOD2_120700-485100_filtered.gml"
18 | CITYGML_OUTPUT_PATH = "CityGML/LOD3_120700-485100.gml"
19 | CSV_PATH = "CSV/output_stage3.csv"
20 | CROPPED_IMAGES_PATH = "texture_cropped/"
21 | IMAGES_PATH = "images/"
22 |
23 | # Namespaces of XML file
24 | NS_CITYGML = "http://www.opengis.net/citygml/2.0"
25 | NS_GML = "http://www.opengis.net/gml"
26 | NS_BLDG = "http://www.opengis.net/citygml/building/2.0"
27 |
28 | NSMAP = {
29 | "city": NS_CITYGML,
30 | "gml": NS_GML,
31 | "bldg": NS_BLDG
32 | }
33 |
34 | # Extracted images are set to 30 meter as height, equal to 900 pixel height
35 | IMAGE_HEIGHT_IRL = 30 # Defined in stage 1
36 |
37 | DEBUG = False
38 |
39 | def coordinate_transformation(bboxes_pixel, visible_point_left, visible_point_right, low_z, high_z, filename):
40 | """
41 | Transform the 2D bbox coordinates to 3D bbox coordinates.
42 | """
43 |
44 | # Get image info from original images
45 | im = Image.open(os.path.join(IMAGES_PATH, filename + ".jpeg"))
46 | image_width, image_height = im.size # Height is always 900 pixels
47 |
48 | # Calculate slope
49 | x_dist = visible_point_right[0] - visible_point_left[0]
50 | y_dist = visible_point_right[1] - visible_point_left[1]
51 |
52 | bboxes_real = []
53 | for bbox in bboxes_pixel:
54 | x0, y0, x1, y1 = bbox
55 |
56 | # Coordinate transformation
57 | fraction_of_total = x0 / image_width
58 |
59 | X0 = visible_point_left[0] + x_dist * fraction_of_total
60 | Y0 = visible_point_left[1] + y_dist * fraction_of_total
61 |
62 | fraction_of_total = x1 / image_width
63 |
64 | X1 = visible_point_left[0] + x_dist * fraction_of_total
65 | Y1 = visible_point_left[1] + y_dist * fraction_of_total
66 |
67 | Z0 = round(((image_height - y0) / image_height * IMAGE_HEIGHT_IRL) + low_z, 2)
68 | Z1 = round(((image_height - y1) / image_height * IMAGE_HEIGHT_IRL) + low_z, 2)
69 |
70 | # Validate height of bbox above facade (Better to do this in get_wall_to_insert())
71 | if Z0 < (low_z + high_z):
72 | bboxes_real.append([X0, X1, Y0, Y1, Z0, Z1])
73 |
74 | return bboxes_real
75 |
76 | def get_outer_poslist_points(surface_element):
77 | """
78 | Get outer x-axis points of a wall surface polygon.
79 | """
80 | # Save the outer poslist points of the buildings
81 | outer_poslist_points = {}
82 |
83 | for polygon in surface_element.findall(".//gml:Polygon", NSMAP):
84 | # Get the unique id for a Polygon
85 | attribute_id = polygon.attrib["{%s}id" % NS_GML]
86 |
87 | # Get the coordinates of the Polygon
88 | poslist_string = polygon.find(".//gml:posList", NSMAP).text
89 |
90 | # Split the string that is seperated with a space to float list
91 | poslist_float = [float(x) for x in poslist_string.split()]
92 |
93 | # Create a nested list out of split_posList
94 | xyz_list = [poslist_float[x:x+3] for x in range(0, len(poslist_float),3)]
95 |
96 | # Search for two points with the largest distance in the list of visible polygon points
97 | furthest_pair = diameter(xyz_list[:-1])
98 |
99 | outer_poslist_points[attribute_id] = furthest_pair
100 |
101 | return outer_poslist_points
102 |
103 | def get_wall_to_insert(outer_poslist_points, bboxes_window, wall_points):
104 | """
105 | For each bbox (window or door), we search for the wall
106 | candidate that best fits to it.
107 | """
108 | bbox_wall_match = collections.defaultdict(list)
109 |
110 | for bbox in bboxes_window:
111 | # Left below bbox coordinates
112 | random_bbox_point = [bbox[0], bbox[3]]
113 | # Initialize variables
114 | shortest_distance = float("inf")
115 | wall_id = 0
116 |
117 | for key, value in outer_poslist_points.items():
118 | angle_between_lines = calculate_angle(value, wall_points)
119 | # The angle between the wall and the bbox must be below 15 degrees.
120 | if angle_between_lines < 15:
121 | distance = distance_point_line(random_bbox_point[0], random_bbox_point[1],
122 | value[0][0], value[0][1], value[1][0], value[1][1])
123 |
124 | # Get the shortest distance from point to wall
125 | if distance < shortest_distance:
126 | shortest_distance = distance
127 | wall_id = key
128 |
129 | # Add key and bbox to dict or append bbox to existing key
130 | bbox_wall_match[wall_id].append(bbox)
131 |
132 | return bbox_wall_match
133 |
134 | def get_poslist_order(bbox):
135 | """
136 | Create list of the bbox in posList order and convert it
137 | into a string with spaces (gml posList format)
138 | """
139 | poslist_order = [bbox[0], bbox[2], bbox[4], # Bottom left
140 | bbox[1], bbox[3], bbox[4], # Bottom right
141 | bbox[1], bbox[3], bbox[5], # Top right
142 | bbox[0], bbox[2], bbox[5], # Top left
143 | bbox[0], bbox[2], bbox[4]]
144 |
145 | # Convert list of floats into a string with spaces (gml posList format)
146 | return " ".join(str(item) for item in poslist_order)
147 |
148 | def get_poslist_order_reversed(bbox):
149 | """
150 | Create list of the bbox in reversed posList order and
151 | convert it into a string with spaces (gml posList format)
152 | """
153 | poslist_order_reversed = [bbox[0], bbox[2], bbox[4], # Bottom left
154 | bbox[0], bbox[2], bbox[5], # Top left
155 | bbox[1], bbox[3], bbox[5], # Top right
156 | bbox[1], bbox[3], bbox[4], # Bottom right
157 | bbox[0], bbox[2], bbox[4]]
158 |
159 | return " ".join(str(item) for item in poslist_order_reversed)
160 |
161 | def add_interior(bbox_list, polygon):
162 | """ Insert window or door bbox as interior polygon """
163 | for bbox in bbox_list:
164 | poslist_bbox = get_poslist_order(bbox)
165 |
166 | # Insert interior polygon of window or door
167 | a = ET.SubElement(polygon, "{%s}interior" % NS_GML)
168 | b = ET.SubElement(a, "{%s}LinearRing" % NS_GML)
169 | c = ET.SubElement(b, "{%s}posList" % NS_GML)
170 | c.attrib["srsDimension"] = "3"
171 | c.text = poslist_bbox
172 |
173 | def add_opening(bbox_list, surface_element, facade_detail):
174 | """ Insert window or door bbox as Opening """
175 | for bbox in bbox_list:
176 | poslist_bbox_reversed = get_poslist_order_reversed(bbox)
177 |
178 | # Insert interior polygon of window or door
179 | a = ET.SubElement(surface_element, "{%s}opening" % NS_BLDG)
180 | b = ET.SubElement(a, "{%s}%s" % (NS_BLDG, facade_detail))
181 | c = ET.SubElement(b, "{%s}lod3MultiSurface" % NS_BLDG)
182 | d = ET.SubElement(c, "{%s}MultiSurface" % NS_GML)
183 | e = ET.SubElement(d, "{%s}surfaceMember" % NS_GML)
184 | f = ET.SubElement(e, "{%s}Polygon" % NS_GML)
185 | g = ET.SubElement(f, "{%s}exterior" % NS_GML)
186 | h = ET.SubElement(g, "{%s}LinearRing" % NS_GML)
187 | i = ET.SubElement(h, "{%s}posList" % NS_GML)
188 | i.text = poslist_bbox_reversed
189 |
190 | def main():
191 | # Check if input files can be found
192 | if not os.path.isfile(CITYGML_PATH):
193 | print("Input CityGML file not found. Aborting.")
194 | return
195 |
196 | if not os.path.isfile(CSV_PATH):
197 | print("Input csv files not found. Aborting.")
198 | return
199 |
200 | print("--- Start ---")
201 |
202 | # Start timer
203 | start_time = time.time()
204 |
205 | # Get dataframe
206 | df = pd.read_csv(CSV_PATH, dtype={"pand_id": object})
207 |
208 | # Set the DEBUG variable to true if you manually validated the cropped images
209 | if DEBUG:
210 | files = []
211 | for filename in os.listdir(CROPPED_IMAGES_PATH):
212 | file = os.path.splitext(filename)[0]
213 | if filename.endswith(".jpeg"):
214 | files.append(file)
215 |
216 | df = df[df["texture_filename"].isin(files)].reset_index(drop=True)
217 |
218 | print("Step 5: Transform the 2D bbox coordinates to 3D bbox coordinates.")
219 | bbox_real_data = []
220 | for _, row in df.iterrows():
221 | new_data = {}
222 | new_data["texture_filename"] = row["texture_filename"]
223 |
224 | for keyword in ["bboxes_window", "bboxes_door"]:
225 | new_data[keyword + "_real"] = coordinate_transformation(eval(row[keyword]), eval(row["visible_point_one"]),
226 | eval(row["visible_point_two"]), row["low_z"],
227 | row["high_z"], new_data["texture_filename"])
228 |
229 | bbox_real_data.append(new_data)
230 |
231 | # Merge dataframes
232 | df_bbox_real = pd.DataFrame(bbox_real_data)
233 | df_output = df_bbox_real.merge(df) # TODO Reuse df and keep only specific columns
234 |
235 | # Get the CityGML file
236 | # All objects are passed by reference.
237 | # And since "tree" is an object, you're only passing the reference.
238 | parser = ET.XMLParser(remove_blank_text = True) # Remove spaces etc.
239 | tree = ET.parse(CITYGML_PATH, parser)
240 | root = tree.getroot()
241 |
242 | print("Step 6: Insert the windows and doors in the 3D buildings.")
243 | # TODO move to function, too long
244 | for building_element in root.findall(".//city:cityObjectMember", NSMAP):
245 | # Get pand_id in current element of XML
246 | pand_id = building_element.find(".//bldg:Building/gml:name", NSMAP)
247 | if pand_id is not None:
248 | # Check if the pand_id is inside the dataframe
249 | df_row = df_output.loc[pand_id.text == df_output['pand_id']]
250 | if not df_row.empty:
251 | # Left and right Rijksdriehoek coordinates found for the facade in the image
252 | wall_points = [eval(df_row["visible_point_one"].values[0]), eval(df_row["visible_point_two"].values[0])] # TODO Dont use eval
253 |
254 | for surface_element in building_element.findall(".//bldg:WallSurface", NSMAP):
255 | # Loop polygon 1: Get outer x-axis points of a wall surface polygon
256 | outer_poslist_points = get_outer_poslist_points(surface_element)
257 |
258 | bboxes_window = df_row["bboxes_window_real"].values[0]
259 | bboxes_door = df_row["bboxes_door_real"].values[0]
260 | bboxes_merged = bboxes_window + bboxes_door
261 |
262 | # Get wall id on where to insert window or door bbox
263 | bbox_wall_match = get_wall_to_insert(outer_poslist_points, bboxes_merged, wall_points)
264 |
265 | # Loop polygon 2: Insert window or door bbox as interior polygon
266 | for polygon in surface_element.findall(".//gml:Polygon", NSMAP):
267 |
268 | # Because multiple bboxes can occur for one UUID, we iterate over these values
269 | for wall_id, bbox_list in bbox_wall_match.items():
270 | if polygon.get("{%s}id" % NS_GML) == wall_id:
271 | add_interior(bbox_list, polygon)
272 |
273 | # Insert window or door bbox as Opening
274 | add_opening(bboxes_window, surface_element, "Window")
275 | add_opening(bboxes_door, surface_element, "Door")
276 |
277 | print("Step 7: Write final GML file with LOD3 buildings.")
278 | tree.write(CITYGML_OUTPUT_PATH, pretty_print = True, xml_declaration = True, encoding='UTF-8')
279 |
280 | print("--- %s seconds ---" % (time.time() - start_time))
281 |
282 | if __name__ == "__main__":
283 | main()
284 |
--------------------------------------------------------------------------------
/stage_3/prepare_lod3.py:
--------------------------------------------------------------------------------
1 | """
2 | The geospatial location of a façade image is obtained during the first stage of the
3 | proposed pipeline. In addition, the real height of a building façade is calculated
4 | in this stage; this information is not provided by Key register Addresses and
5 | Buildings (BAG). Note that the height of each extracted image is hard-coded and
6 | corresponds to an actual height value of 30 meters. Each building in 3D Amsterdam
7 | city model contains a building id identical to BAG. We use this given to match an
8 | extracted façade image to the corresponding building in the 3D city model.
9 | """
10 |
11 | import pandas as pd
12 | import time
13 | import os
14 | from lxml import etree as ET
15 | import math
16 |
17 | from src.optional import *
18 |
19 | # Paths
20 | CITYGML_PATH = "CityGML/LOD2_120700-485100.gml"
21 | CITYGML_OUTPUT_PATH = "CityGML/LOD2_120700-485100_filtered.gml"
22 | CSV_PATH = "CSV/output_stage1.csv"
23 | CSV_BBOX_PATH = "CSV/output_stage2.csv"
24 | CSV_OUTPUT_PATH = "CSV/output_stage3.csv"
25 | IMAGES_PATH = "images/"
26 | CROPPED_IMAGES_PATH = "texture_cropped/"
27 |
28 | # Namespaces of XML file
29 | NSMAP = {
30 | "bldg": "http://www.opengis.net/citygml/building/2.0",
31 | "gml": "http://www.opengis.net/gml",
32 | "city": "http://www.opengis.net/citygml/2.0"
33 | }
34 |
35 | IMAGE_HEIGHT_IRL = 30 # Defined in stage 1
36 | MIN_NAP = -5
37 |
38 | DEBUG = False
39 |
40 | def get_facade_height(root, df):
41 | """
42 | Get the "best" 3D wall surface candidate for a 2D texture image
43 | and calculate the lowest and highest point of the wall surface.
44 |
45 | The variable low_z is important for the bbox coordinate
46 | transformation step later.
47 | """
48 | height_data = []
49 | for buildingElement in root.findall(".//city:cityObjectMember", NSMAP):
50 | # Initialze variables
51 | low_z = None
52 | high_z = None
53 | shortest_distance = float("inf")
54 | height_dict = {}
55 |
56 | # Get pand_id in current element of XML
57 | pand_id = buildingElement.find(".//bldg:Building/gml:name", namespaces=NSMAP)
58 | if pand_id is not None:
59 | # Check if the pand_id is inside the dataframe
60 | df_row = df.loc[pand_id.text == df["pand_id"]]
61 | if not df_row.empty:
62 | # Take this point from the facade texture to compare with the 3D model later
63 | visible_point_one = eval(df_row["visible_point_one"].values[0]) # TODO dont use eval
64 |
65 | for surfaceElement in buildingElement.findall(".//bldg:WallSurface", NSMAP):
66 | for polygon in surfaceElement.findall(".//gml:posList", NSMAP):
67 | # Create a nested list of [x,y,z] out of the poslist content
68 | poslist = [float(x) for x in polygon.text.split()]
69 | xyz_poslist = [poslist[x:x+3] for x in range(0, len(poslist),3)]
70 |
71 | # Sort on z axis
72 | xyz_poslist.sort(key=lambda x: x[2])
73 |
74 | # Get random point of a wall (lowest z value)
75 | random_wall_point = xyz_poslist[0]
76 |
77 | # Determine distance 2D texture image to a wallSurface of 3D model
78 | distance_2d_3d = math.sqrt(((visible_point_one[0] - random_wall_point[0])**2) +
79 | ((visible_point_one[1] - random_wall_point[1])**2))
80 |
81 | # A wall candidate must be 5 meter or higher
82 | # And should not be located 5 meter above NAP
83 | if((xyz_poslist[-1][2] - xyz_poslist[0][2]) > 5) and (xyz_poslist[0][2] < 5):
84 | # Save the shortest distance, this our wall candidate for the facade texture
85 | if distance_2d_3d < shortest_distance:
86 | # Get the lowest and highest z value for this wall
87 | low_z = round(xyz_poslist[0][2], 2)
88 | high_z = round(xyz_poslist[-1][2], 2)
89 |
90 | shortest_distance = distance_2d_3d
91 |
92 | # Check if high_z (or low_z) have new values
93 | if high_z is not None:
94 | # Validating the max height of the facade possible on image
95 | # And outlier removal
96 | if high_z <= IMAGE_HEIGHT_IRL and low_z > MIN_NAP:
97 | # Save the info
98 | height_dict["high_z"] = high_z
99 | height_dict["low_z"] = low_z
100 | height_dict["texture_filename"] = df_row["texture_filename"].values[0]
101 |
102 | height_data.append(height_dict)
103 | return height_data
104 |
105 | def main():
106 | # Check if input files can be found
107 | if not os.path.isfile(CITYGML_PATH):
108 | print("Input CityGML file not found. Aborting.")
109 | return
110 |
111 | if not os.path.isfile(CSV_PATH) or not os.path.isfile(CSV_BBOX_PATH):
112 | print("Input csv files not found. Aborting.")
113 | return
114 |
115 | print("--- Start ---")
116 |
117 | # Start timer
118 | start_time = time.time()
119 |
120 | # Get the CityGML file
121 | parser = ET.XMLParser(remove_blank_text = True) # Remove spaces etc.
122 | tree = ET.parse(CITYGML_PATH, parser)
123 | root = tree.getroot()
124 |
125 | # Get the CSV file
126 | df = pd.read_csv(CSV_PATH, dtype={"pand_id": object})
127 | pand_ids = df["pand_id"].astype(str).values.tolist()
128 |
129 | # Optional step to remove duplicate pand ids from invalid CityGML file
130 | duplicate_pand_ids, unique_buildings = get_duplicate_buildings(root, NSMAP)
131 |
132 | print("Step 1: Remove buildings where windows and doors are not predicted in the previous stage")
133 | for pand_id in root.findall(".//bldg:Building/gml:name", namespaces=NSMAP):
134 | if pand_id.text not in pand_ids:
135 | # Remove not predicted buildings
136 | actual_element = pand_id.getparent().getparent()
137 | actual_element.getparent().remove(actual_element)
138 | elif pand_id.text in duplicate_pand_ids:
139 | building_uuid = pand_id.getparent().attrib["{http://www.opengis.net/gml}id"]
140 | if building_uuid != unique_buildings[pand_id.text]["building_uuid"]:
141 | # Remove duplicate buildings
142 | actual_element = pand_id.getparent().getparent()
143 | actual_element.getparent().remove(actual_element)
144 |
145 | print("Step 2: Get height of facade using CityGML file")
146 | height_data = get_facade_height(root, df)
147 |
148 | # Set the DEBUG variable to true if you want to save cropped images
149 | if DEBUG:
150 | if not os.path.exists(CROPPED_IMAGES_PATH):
151 | os.makedirs(CROPPED_IMAGES_PATH)
152 | else:
153 | print("The 'texture_cropped' folder already exists.")
154 |
155 | print("Optional Step: Crop texture image to height value of facade")
156 | crop_to_facade(height_data, IMAGES_PATH, CROPPED_IMAGES_PATH, IMAGE_HEIGHT_IRL)
157 | print("Manually validate and remove the invalid cropped images in path.")
158 |
159 | print("Step 3: LOD2 to LOD3 syntax in the CityGML file")
160 | tag_lod2_multisurface = tree.findall(".//bldg:lod2MultiSurface", namespaces=NSMAP)
161 | for tags in tag_lod2_multisurface:
162 | tags.tag = "{http://www.opengis.net/citygml/building/2.0}lod3MultiSurface"
163 | tag_lod2_solid = tree.findall(".//bldg:lod2Solid", namespaces=NSMAP)
164 | for tags in tag_lod2_solid:
165 | tags.tag = "{http://www.opengis.net/citygml/building/2.0}lod3Solid"
166 |
167 | print("Step 4: Save the new CityGML and CSV file")
168 | # GML save
169 | tree.write(CITYGML_OUTPUT_PATH, pretty_print = True, xml_declaration = True, encoding="UTF-8")
170 | # CSV merge and save
171 | df_bbox = pd.read_csv(CSV_BBOX_PATH, dtype={"pand_id": object})
172 | df_height = pd.DataFrame(height_data)
173 | df_output = df_height.merge(df_bbox, on="texture_filename").merge(df, on="texture_filename")
174 | df_output.to_csv(CSV_OUTPUT_PATH, index=False)
175 |
176 | print("--- %s seconds ---" % (time.time() - start_time))
177 |
178 | if __name__ == "__main__":
179 | main()
--------------------------------------------------------------------------------
/stage_3/src/furthest_pair.py:
--------------------------------------------------------------------------------
1 | def orientation(p, q, r):
2 | """Return positive if p-q-r are clockwise, neg if ccw, zero if colinear."""
3 | return (q[1] - p[1]) * (r[0] - p[0]) - (q[0] - p[0]) * (r[1] - p[1])
4 |
5 |
6 | def hulls(points):
7 | """Graham scan to find upper & lower convex hulls of a set of 2d points."""
8 | U = []
9 | L = []
10 | points.sort()
11 | for p in points:
12 | while len(U) > 1 and orientation(U[-2], U[-1], p) <= 0:
13 | U.pop()
14 | while len(L) > 1 and orientation(L[-2], L[-1], p) >= 0:
15 | L.pop()
16 | U.append(p)
17 | L.append(p)
18 | return U, L
19 |
20 |
21 | def rotating_calipers(points):
22 | """Find all ways of sandwiching between parallel lines.
23 | Given a list of 2d points, finds all ways of sandwiching the points
24 | between two parallel lines that touch one point each, and
25 | yields the sequence of pairs of points touched by each pair of lines.
26 | """
27 | U, L = hulls(points)
28 | i = 0
29 | j = len(L) - 1
30 | while i < len(U) - 1 or j > 0:
31 | yield U[i], L[j]
32 |
33 | # if all the way through one side of hull, advance the other side
34 | if i == len(U) - 1:
35 | j -= 1
36 | elif j == 0:
37 | i += 1
38 | # still points left on both lists, compare slopes of next hull edges
39 | # being careful to avoid divide-by-zero in slope calculation
40 | elif (U[i + 1][1] - U[i][1]) * (L[j][0] - L[j - 1][0]) > \
41 | (L[j][1] - L[j - 1][1]) * (U[i + 1][0] - U[i][0]):
42 | i += 1
43 | else:
44 | j -= 1
45 |
46 |
47 | def diameter(points):
48 | """Given a list of 2d points, returns the pair that's farthest apart."""
49 | diam, pair = max([((p[0] - q[0])**2 + (p[1] - q[1])**2, [p, q])
50 | for p, q in rotating_calipers(points)])
51 | return pair
52 |
--------------------------------------------------------------------------------
/stage_3/src/geometry.py:
--------------------------------------------------------------------------------
1 | import math
2 |
3 | def line_magnitude(x1, y1, x2, y2):
4 | magnitude = math.sqrt(math.pow((x2 - x1), 2)+ math.pow((y2 - y1), 2))
5 | return magnitude
6 |
7 | def distance_point_line(px, py, x1, y1, x2, y2):
8 | """
9 | Calculate the minimum distance from a point and a line segment
10 | (i.e. consecutive vertices in a polyline).
11 |
12 | Source: http://local.wasp.uwa.edu.au/~pbourke/geometry/pointline/source.vba
13 |
14 | """
15 | LineMag = line_magnitude(x1, y1, x2, y2)
16 |
17 | if LineMag < 0.00000001:
18 | distance = 9999
19 | return distance
20 |
21 | u1 = (((px - x1) * (x2 - x1)) + ((py - y1) * (y2 - y1)))
22 | u = u1 / (LineMag * LineMag)
23 |
24 | if (u < 0.00001) or (u > 1):
25 | # Closest point does not fall within the line segment,
26 | # take the shorter distance to an endpoint.
27 | ix = line_magnitude(px, py, x1, y1)
28 | iy = line_magnitude(px, py, x2, y2)
29 | if ix > iy:
30 | distance = iy
31 | else:
32 | distance = ix
33 | else:
34 | # Intersecting point is on the line, use the formula
35 | ix = x1 + u * (x2 - x1)
36 | iy = y1 + u * (y2 - y1)
37 | distance = line_magnitude(px, py, ix, iy)
38 |
39 | return distance
40 |
41 | def calculate_angle(line1, line2):
42 | """
43 | Calculate the angle (in degrees) between two linear lines
44 | when lines are not joined.
45 | """
46 | # Use 1e-10 to prevent zero division error
47 | slope1 = (line1[1][1] - line1[0][1]) / (line1[1][0] - line1[0][0] + 1e-10)
48 | slope2 = (line2[1][1] - line2[0][1]) / (line2[1][0] - line2[0][0] + 1e-10)
49 |
50 | return abs(math.degrees(math.atan((slope2 - slope1) / (1 + (slope2 * slope1)))))
51 |
52 | def euclidean_distance(x_1, y_1, x_2, y_2):
53 | """
54 | Calculate the Euclidean distance between two vectors
55 | """
56 | return math.sqrt(((x_1 - x_2)**2) + ((y_1 - y_2)**2))
57 |
--------------------------------------------------------------------------------
/stage_3/src/optional.py:
--------------------------------------------------------------------------------
1 | """
2 | The use of the functions in this python file are optional and can help
3 | with generating a better LOD3 model.
4 | """
5 | import os
6 | from PIL import Image
7 |
8 | from src.geometry import euclidean_distance
9 |
10 | def get_duplicate_buildings(root, nsmap):
11 | """
12 | The provided CityGML files often have duplicate buildings. We perform
13 | an extra step to remove duplicates. The duplicates are most of the time
14 | parts of a complete building. Therefore, we filter for the largest area
15 | size and keep that building in the CityGML file.
16 |
17 | This is an optional step.
18 | """
19 | # Get all pand ids in CityGML file
20 | building_citygml = []
21 | for pand_id in root.findall(".//bldg:Building/gml:name", namespaces=nsmap):
22 | building_citygml.append(pand_id.text)
23 |
24 | # Get all duplicate pand ids in CityGML file
25 | building_duplicates = set([x for x in building_citygml if building_citygml.count(x) > 1])
26 |
27 | # Get building with biggest area length
28 | unique_buildings = {}
29 | if building_duplicates is not None:
30 | for building in root.findall(".//bldg:Building", namespaces=nsmap):
31 | pand_id = building.find(".//gml:name", namespaces=nsmap)
32 | if pand_id.text in building_duplicates:
33 | # Get lowerCorner and upperCorner of a building
34 | lower_corner = building.find(".//gml:lowerCorner", namespaces=nsmap).text.split()
35 | upper_corner = building.find(".//gml:upperCorner", namespaces=nsmap).text.split()
36 |
37 | # Get building area length
38 | building_length = euclidean_distance(float(lower_corner[0]), float(lower_corner[1]),
39 | float(upper_corner[0]), float(upper_corner[1]))
40 |
41 | building_uuid = building.attrib["{http://www.opengis.net/gml}id"]
42 |
43 | # Save the building uuid with the largest area length
44 | if pand_id.text not in unique_buildings:
45 | # Add new pand_id
46 | unique_buildings[pand_id.text] = {"building_uuid": building_uuid, "building_length": building_length}
47 | else:
48 | # Update pand_id with larger area length and corresponding uuid
49 | if building_length > unique_buildings[pand_id.text]["building_length"]:
50 | unique_buildings[pand_id.text] = {"building_uuid": building_uuid, "building_length": building_length}
51 |
52 | # Return duplicate buildings
53 | return building_duplicates, unique_buildings
54 |
55 | def crop_to_facade(height_data, images_path, cropped_images_path, image_height_irl):
56 | """
57 | Based on the previously calculated height of the facades in meter,
58 | we crop the texture images.
59 |
60 | This is an optional step to manually validate the quality of
61 | the height calculation and the resulting cropped images.
62 | """
63 | for row in height_data:
64 | filename = row["texture_filename"]
65 |
66 | facade_texture = os.path.join(images_path, filename + ".jpeg")
67 |
68 | # Check if file exists
69 | if os.path.isfile(facade_texture):
70 | # Get image info
71 | im = Image.open(facade_texture)
72 | image_width, image_height = im.size # Height is always the same value (900 px)
73 |
74 | facade_height = row["high_z"] - row["low_z"]
75 |
76 | # Get height of facade in pixels
77 | pixel_facade_height = int(image_height - (image_height / image_height_irl * facade_height))
78 |
79 | # Save the cropped image with settings (left, top, right, bottom)
80 | cropped = im.crop((0, pixel_facade_height, image_width, image_height))
81 | cropped.save(os.path.join(cropped_images_path, filename + ".jpeg"))
82 |
--------------------------------------------------------------------------------
/system-overview.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chrise96/3D_building_reconstruction/86539cd14689109ca9bc41b6fc7e21231623bc77/system-overview.png
--------------------------------------------------------------------------------