├── CHANGELOG.md ├── CMakeLists.txt ├── LICENSE ├── LICENSE-MIT.txt ├── README.md ├── images ├── JP1_final_seg.jpg ├── JP1_final_seg.png ├── JP1_init_seg.jpg ├── JP1_init_seg.png ├── JP1_interim_seg.jpg ├── JP1_interim_seg.png └── forest.png ├── include ├── CMakeLists.txt ├── TreeIso.h ├── TreeIsoHelper.hpp ├── block.hpp ├── ccTreeIsoDlg.h ├── cp_d0_dist.hpp ├── cut_pursuit.hpp ├── cut_pursuit_d0.hpp ├── knncpp.h ├── maxflow.hpp ├── qTreeIso.h └── qTreeIsoCommands.h ├── info.json ├── license.txt ├── qTreeIso.qrc ├── src ├── CMakeLists.txt ├── TreeIso.cpp ├── ccTreeIsoDlg.cpp ├── cp_d0_dist.cpp ├── cut_pursuit.cpp ├── cut_pursuit_d0.cpp ├── maxflow.cpp └── qTreeIso.cpp └── ui ├── CMakeLists.txt └── TreeIsoDlg.ui /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [this branch](https://github.com/truebelief/cc-treeiso-plugin/tree/revert-7-optimize_treeiso_speed). 6 | 7 | 8 | ## - 2023-05-13 9 | ### Cleanup 10 | - Adjust the Boost and Eigen library dependency on CMake 11 | 12 | ## - 2023-05-20 13 | ### Cleanup 14 | - Major cleanup to integrate into CloudCompare 15 | 16 | ## - 2023-01-15 17 | ### Added 18 | - Icon added and better progress dialog management 19 | 20 | ## - 2023-06-18 21 | ### Cleanup 22 | - Remove two useless pragma once 23 | - Use standard uint64 type 24 | - Fix case of a file name in CMakeLists.txt 25 | 26 | ## - 2023-06-30 27 | ### Cleanup 28 | - Fixes after a scan of the CloudCompare project by Coverity. 29 | 30 | ## - 2025-02-01 31 | ### Cleanup 32 | - Removed the Boost dependency by adopting a newer cut-pursuit version (boosting speed by 5–15×). 33 | - Fixed an issue with the nearest neighbor search caused by an incorrect 2D array order in knn_cpp. 34 | - Enabled thread count customization for knn-cpp (minor speed boost). 35 | - Optimized array calculations with improved use of STL algorithms. 36 | 37 | ## - 2025-02-10 38 | ### Tested 39 | - Tested on several TLS plots 40 | 41 | ## - 2025-02-11 42 | ### Added 43 | - Improved progress bar increment 44 | - Added rapid detection of ground points based on quantile distribution 45 | - Added warning of ground points before continuing initial segmentation 46 | 47 | ## - 2025-02-16 48 | ### Added 49 | - Avoided crashes by adding error handling once the maximum component limit is reached 50 | - Improved the speed of unique and get_subset functions 51 | ======= 52 | \ 53 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required( VERSION 3.10 ) 2 | 3 | option( PLUGIN_STANDARD_QTREEISO "Install qTreeIso plugin" OFF ) 4 | 5 | if( PLUGIN_STANDARD_QTREEISO ) 6 | 7 | project( QTREEISO_PLUGIN ) 8 | 9 | AddPlugin( NAME ${PROJECT_NAME} ) 10 | 11 | find_package(Eigen3 QUIET) 12 | if(NOT Eigen3_FOUND) 13 | set( EIGEN_ROOT_DIR "" CACHE PATH "Eigen root (contains the Eigen directory)" ) 14 | if ( NOT EIGEN_ROOT_DIR ) 15 | message( SEND_ERROR "No Eigen root directory specified (EIGEN_ROOT_DIR)" ) 16 | endif() 17 | include_directories(${EIGEN_ROOT_DIR}) 18 | else() 19 | target_link_libraries(${PROJECT_NAME} Eigen3::Eigen) 20 | endif() 21 | 22 | add_subdirectory( include ) 23 | add_subdirectory( src ) 24 | add_subdirectory( ui ) 25 | 26 | endif() 27 | -------------------------------------------------------------------------------- /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 | . 675 | -------------------------------------------------------------------------------- /LICENSE-MIT.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of 4 | this software and associated documentation files (the "Software"), to deal in 5 | the Software without restriction, including without limitation the rights to 6 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 7 | of the Software, and to permit persons to whom the Software is furnished to do 8 | so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | THE SOFTWARE. 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | TreeIso (plugin) 2 | ============ 3 | 4 | Individual-tree isolation (treeiso) from terrestrial laser scanning 5 | ----------------------------------------------------------------- 6 | 7 | Zhouxin Xi, Chris Hopkinson (Department of Geography & Environment, University of Lethbridge, Canada) 8 | 9 | TreeIso can be utilized to separate individual trees from terrestrial laser scanning point clouds, assigning tree IDs as supplementary scalar fields. 10 | 11 | Please cite the following paper if you find this tool helpful: 12 | 13 | Xi, Z.; Hopkinson, C. 3D Graph-Based Individual-Tree Isolation (Treeiso) from Terrestrial Laser Scanning Point Clouds. Remote Sens. 2022, 14, 6116. https://doi.org/10.3390/rs14236116 14 | 15 | This tool relies on the cut-pursuit algorithm, please also consider citing: 16 | Landrieu, L.; Obozinski, G. Cut Pursuit: Fast Algorithms to Learn Piecewise Constant Functions on General Weighted Graphs. SIAM J. Imaging Sci. 2017, 10, 1724–1766. hal link 17 | Raguet, H.; Landrieu, L. Cut-pursuit algorithm for regularizing nonsmooth functionals with graph total variation. In Proceedings of the International Conference on Machine Learning, Stockholm, Sweden, 10–15 July 2018; Volume 80, pp. 4247–4256. 18 | 19 | The cut-pursuit files are licensed under the **MIT** license - see the [LICENSE-MIT](LICENSE-MIT.txt) file for details. 20 | 21 | A Matlab version shared via: 22 | https://github.com/truebelief/artemis_treeiso 23 | 24 | The development of the treeiso plugin was inspired by the CSF plugin originating from: 25 | Zhang W, Qi J, Wan P, Wang H, Xie D, Wang X, Yan G. An Easy-to-Use Airborne LiDAR Data Filtering Method Based on Cloth Simulation. Remote Sensing. 2016; 8(6):501 26 | 27 | 28 | Command line mode 29 | ----------------- 30 | Command line is supported. The plugin consists of three stages of segmentation. In the command line mode, please configure the segmentation parameters for each stage to activate the corresponding stage. If no parameters are provided for a specific stage, the segmentation for that stage will not be executed. 31 | 32 | Available options 33 | ----------------- 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 56 | 57 |
CommandDescription
-TREEISO 42 | Runs the TREEISO plugin 43 |

Optional settings are:

44 |
    45 |
  • -LAMBDA1 [value]: Regularization strength for initial segmentation (default: 1.0)
  • 46 |
  • -K1 [value]: Nearest neighbors to search for initial segmentation(default: 5, minimum>3)
  • 47 |
  • -DECIMATE_RESOLUTION1 [value]: Decimated point resolution (in m) for initial segmentation (default: 0.05)
  • 48 |
  • -LAMBDA2 [value]: Regularization strength for intermediate segmentation (default: 20)
  • 49 |
  • -K2 [value]: Nearest neighbors to search for intermediate segmentation (default: 20)
  • 50 |
  • -MAX_GAP [value]: Maximum point gap (in m) for intermediate segmentation (default: 2.0)
  • 51 |
  • -DECIMATE_RESOLUTION2 [value]: Decimated point resolution (in m) for intermediate segmentation (default: 0.1)
  • 52 |
  • -RHO [value]: Relative height to length ratio (used to detect non-stems for final segmentation) (default: 0.5)
  • 53 |
  • -VERTICAL_OVERLAP_WEIGHT [value]: Vertical overlapping ratio weight for final segmentation (default: 0.5)
  • 54 |
55 |
58 | 59 | ![treeiso_demo](https://user-images.githubusercontent.com/8785889/236364374-5d9f69e0-0877-43b3-9927-f923d65262c1.gif) 60 | 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /images/JP1_final_seg.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/truebelief/cc-treeiso-plugin/3556f843a6dcd31ba22c42758fcaff759119a36c/images/JP1_final_seg.jpg -------------------------------------------------------------------------------- /images/JP1_final_seg.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/truebelief/cc-treeiso-plugin/3556f843a6dcd31ba22c42758fcaff759119a36c/images/JP1_final_seg.png -------------------------------------------------------------------------------- /images/JP1_init_seg.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/truebelief/cc-treeiso-plugin/3556f843a6dcd31ba22c42758fcaff759119a36c/images/JP1_init_seg.jpg -------------------------------------------------------------------------------- /images/JP1_init_seg.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/truebelief/cc-treeiso-plugin/3556f843a6dcd31ba22c42758fcaff759119a36c/images/JP1_init_seg.png -------------------------------------------------------------------------------- /images/JP1_interim_seg.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/truebelief/cc-treeiso-plugin/3556f843a6dcd31ba22c42758fcaff759119a36c/images/JP1_interim_seg.jpg -------------------------------------------------------------------------------- /images/JP1_interim_seg.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/truebelief/cc-treeiso-plugin/3556f843a6dcd31ba22c42758fcaff759119a36c/images/JP1_interim_seg.png -------------------------------------------------------------------------------- /images/forest.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/truebelief/cc-treeiso-plugin/3556f843a6dcd31ba22c42758fcaff759119a36c/images/forest.png -------------------------------------------------------------------------------- /include/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | 2 | target_sources( ${PROJECT_NAME} 3 | PRIVATE 4 | ${CMAKE_CURRENT_LIST_DIR}/ccTreeIsoDlg.h 5 | ${CMAKE_CURRENT_LIST_DIR}/block.hpp 6 | ${CMAKE_CURRENT_LIST_DIR}/maxflow.hpp 7 | ${CMAKE_CURRENT_LIST_DIR}/cp_d0_dist.hpp 8 | ${CMAKE_CURRENT_LIST_DIR}/cut_pursuit_d0.hpp 9 | ${CMAKE_CURRENT_LIST_DIR}/cut_pursuit.hpp 10 | ${CMAKE_CURRENT_LIST_DIR}/knncpp.h 11 | ${CMAKE_CURRENT_LIST_DIR}/qTreeIso.h 12 | ${CMAKE_CURRENT_LIST_DIR}/qTreeIsoCommands.h 13 | ${CMAKE_CURRENT_LIST_DIR}/TreeIso.h 14 | ${CMAKE_CURRENT_LIST_DIR}/TreeIsoHelper.hpp 15 | ) 16 | 17 | target_include_directories( ${PROJECT_NAME} 18 | PRIVATE 19 | ${CMAKE_CURRENT_SOURCE_DIR} 20 | ) 21 | -------------------------------------------------------------------------------- /include/TreeIso.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | //####################################################################################### 4 | //# # 5 | //# CLOUDCOMPARE PLUGIN: qTreeIso # 6 | //# # 7 | //# This program is free software; you can redistribute it and/or modify # 8 | //# it under the terms of the GNU General Public License as published by # 9 | //# the Free Software Foundation; version 2 or later of the License. # 10 | //# # 11 | //# This program is distributed in the hope that it will be useful, # 12 | //# but WITHOUT ANY WARRANTY; without even the implied warranty of # 13 | //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # 14 | //# GNU General Public License for more details. # 15 | //# # 16 | //# Please cite the following paper if you find this tool helpful # 17 | //# # 18 | //# Xi, Z.; Hopkinson, C. 3D Graph-Based Individual-Tree Isolation (Treeiso) # 19 | //# from Terrestrial Laser Scanning Point Clouds. Remote Sens. 2022, 14, 6116. # 20 | //# https://doi.org/10.3390/rs14236116 # 21 | //# # 22 | //# Our work relies on the cut-pursuit algorithm, please also consider citing: # 23 | //# Landrieu, L.; Obozinski, G. Cut Pursuit: Fast Algorithms to Learn Piecewise # 24 | //# Constant Functions on General Weighted Graphs. SIAM J. Imaging Sci. # 25 | //# 2017, 10, 1724–1766. # 26 | //# # 27 | //# Copyright © # 28 | //# Artemis Lab, Department of Geography & Environment # 29 | //# University of Lethbridge, Canada # 30 | //# # 31 | //# # 32 | //# Zhouxin Xi and Chris Hopkinson; # 33 | //# truebelief2010@gmail.com; c.hopkinson@uleth.ca # 34 | //# # 35 | //####################################################################################### 36 | 37 | // Matlab and python versions shared via: 38 | // https://github.com/truebelief/artemis_treeiso 39 | 40 | class ccMainAppInterface; 41 | class ccPointCloud; 42 | class QProgressDialog; 43 | 44 | class TreeIso 45 | { 46 | public: 47 | 48 | static bool Init_seg(const unsigned PR_MIN_NN1,const float PR_REG_STRENGTH1,const float PR_DECIMATE_RES1,const unsigned PR_THREADS1,ccMainAppInterface* app, std::function progressCallBack); 49 | static bool Intermediate_seg(const unsigned PR_MIN_NN2, const float PR_REG_STRENGTH2, const float PR_DECIMATE_RES2, const float PR_MAX_GAP, const unsigned PR_THREADS2, ccMainAppInterface* app, std::function progressCallBack); 50 | static bool Final_seg(const unsigned PR_MIN_NN3, const float PR_REL_HEIGHT_LENGTH_RATIO, const float PR_VERTICAL_WEIGHT, ccMainAppInterface* app, std::function progressCallBack); 51 | 52 | static bool Init_seg_pcd(ccPointCloud* pc, const unsigned PR_MIN_NN1, const float PR_REG_STRENGTH1, const float PR_DECIMATE_RES1, const unsigned PR_THREADS1, std::function progressCallback); 53 | static bool Intermediate_seg_pcd(ccPointCloud* pc, const unsigned PR_MIN_NN2, const float PR_REG_STRENGTH2, const float PR_DECIMATE_RES2, const float PR_MAX_GAP, const unsigned PR_THREADS2, std::function progressCallback); 54 | static bool Final_seg_pcd(ccPointCloud* pc, const unsigned PR_MIN_NN3, const float PR_REL_HEIGHT_LENGTH_RATIO, const float PR_VERTICAL_WEIGHT, std::function progressCallback); 55 | }; 56 | -------------------------------------------------------------------------------- /include/TreeIsoHelper.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | //####################################################################################### 4 | //# # 5 | //# CLOUDCOMPARE PLUGIN: qTreeIso # 6 | //# # 7 | //# This program is free software; you can redistribute it and/or modify # 8 | //# it under the terms of the GNU General Public License as published by # 9 | //# the Free Software Foundation; version 2 or later of the License. # 10 | //# # 11 | //# This program is distributed in the hope that it will be useful, # 12 | //# but WITHOUT ANY WARRANTY; without even the implied warranty of # 13 | //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # 14 | //# GNU General Public License for more details. # 15 | //# # 16 | //# Please cite the following paper if you find this tool helpful # 17 | //# # 18 | //# Xi, Z.; Hopkinson, C. 3D Graph-Based Individual-Tree Isolation (Treeiso) # 19 | //# from Terrestrial Laser Scanning Point Clouds. Remote Sens. 2022, 14, 6116. # 20 | //# https://doi.org/10.3390/rs14236116 # 21 | //# # 22 | //# Our work relies on the cut-pursuit algorithm, please also consider citing: # 23 | //# Landrieu, L.; Obozinski, G. Cut Pursuit: Fast Algorithms to Learn Piecewise # 24 | //# Constant Functions on General Weighted Graphs. SIAM J. Imaging Sci. # 25 | //# 2017, 10, 1724–1766. # 26 | //# # 27 | //# Copyright © # 28 | //# Artemis Lab, Department of Geography & Environment # 29 | //# University of Lethbridge, Canada # 30 | //# # 31 | //# # 32 | //# Zhouxin Xi and Chris Hopkinson; # 33 | //# truebelief2010@gmail.com; c.hopkinson@uleth.ca # 34 | //# # 35 | //####################################################################################### 36 | 37 | // Matlab and python versions shared via: 38 | // https://github.com/truebelief/artemis_treeiso 39 | 40 | //Local 41 | #include "knncpp.h" 42 | #include "cp_d0_dist.hpp" 43 | 44 | //Eigen 45 | #include 46 | 47 | //STL 48 | #include 49 | #include 50 | #include 51 | #include 52 | 53 | using namespace std; 54 | 55 | 56 | class ccPointCloud; 57 | typedef std::vector Vec3d; 58 | 59 | typedef uint32_t index_t; // For vertex and edge indices 60 | typedef uint16_t comp_t; // For component indices 61 | 62 | 63 | void knn_cpp_build(knncpp::KDTreeMinkowskiX>& kdtree, unsigned n_thread = 0); 64 | void knn_cpp_query(knncpp::KDTreeMinkowskiX>& kdtree, Eigen::MatrixXf& query_points, size_t k, std::vector >& res_idx, std::vector >& res_dists); 65 | float knn_cpp_query_min_d(knncpp::KDTreeMinkowskiX>& kdtree, Eigen::MatrixXf& query_points, size_t k); 66 | void build_knn_graph(const std::vector& points, size_t k, std::vector& first_edge, std::vector& adj_vertices, std::vector& edge_weights, float regStrength1 = 1.0, unsigned n_thread = 8); 67 | void knn_cpp_nearest_neighbors(const std::vector& dataset, size_t k, std::vector>& res_idx, std::vector& res_dists, unsigned n_thread); 68 | 69 | bool detectGroundByQuantile(const std::vector>& points, std::function progressCallBack, float groundThresholdFraction = 0.1f, float ratioThreshold = 0.1f); 70 | 71 | void load_initseg_points(const std::string& filename, std::vector& points, std::vector& in_component); 72 | bool perform_cut_pursuit(const unsigned K, size_t D, const float regStrength, const std::vector& pc_vec, std::vector& edge_weights, std::vector& Eu, std::vector& Ev, std::vector& in_component, const unsigned threads, std::function progressCallback); 73 | 74 | 75 | template 76 | size_t arg_min_col(const std::vector& arr) { 77 | return std::distance(arr.begin(), std::min_element(arr.begin(), arr.end())); 78 | } 79 | 80 | template 81 | size_t arg_max_col(const std::vector& arr) { 82 | return std::distance(arr.begin(), std::max_element(arr.begin(), arr.end())); 83 | } 84 | 85 | template 86 | void min_col(const std::vector>& arr, std::vector& min_vals) { 87 | if (arr.empty()) { 88 | min_vals.clear(); 89 | return; 90 | } 91 | 92 | min_vals = arr[0]; 93 | for (const auto& row : arr) { 94 | std::transform(min_vals.begin(), min_vals.end(), row.begin(), 95 | min_vals.begin(), [](const T& a, const T& b) { return std::min(a, b); }); 96 | } 97 | } 98 | 99 | template 100 | T min_col(const std::vector& arr) { 101 | return arr.empty() ? std::numeric_limits::quiet_NaN() 102 | : *std::min_element(arr.begin(), arr.end()); 103 | } 104 | 105 | template 106 | T mean_col(const std::vector& arr) { 107 | if (arr.empty()) return std::numeric_limits::quiet_NaN(); 108 | return static_cast(std::accumulate(arr.begin(), arr.end(), 0.0) / arr.size()); 109 | } 110 | 111 | template 112 | T median_col(std::vector& arr) { 113 | if (arr.empty()) return std::numeric_limits::quiet_NaN(); 114 | 115 | const size_t n = arr.size(); 116 | const size_t mid = n / 2; 117 | std::nth_element(arr.begin(), arr.begin() + mid, arr.end()); 118 | 119 | if (n % 2 == 0) { 120 | const T right = arr[mid]; 121 | std::nth_element(arr.begin(), arr.begin() + mid - 1, arr.end()); 122 | return (arr[mid - 1] + right) / 2; 123 | } 124 | return arr[mid]; 125 | } 126 | 127 | template 128 | T mode_col(const std::vector& arr) { 129 | if (arr.empty()) return std::numeric_limits::quiet_NaN(); 130 | 131 | std::unordered_map freq; 132 | for (const auto& val : arr) ++freq[val]; 133 | return std::max_element(freq.begin(), freq.end(), 134 | [](const auto& a, const auto& b) { return a.second < b.second; })->first; 135 | } 136 | 137 | template 138 | void max_col(const std::vector>& arr, std::vector& max_vals) { 139 | if (arr.empty()) { 140 | max_vals.clear(); 141 | return; 142 | } 143 | 144 | max_vals = arr[0]; 145 | for (const auto& row : arr) { 146 | std::transform(max_vals.begin(), max_vals.end(), row.begin(), 147 | max_vals.begin(), [](const T& a, const T& b) { return std::max(a, b); }); 148 | } 149 | } 150 | 151 | template 152 | void mean_col(const std::vector>& arr, std::vector& mean_vals) { 153 | if (arr.empty()) { 154 | mean_vals.clear(); 155 | return; 156 | } 157 | 158 | const size_t cols = arr[0].size(); 159 | mean_vals.resize(cols); 160 | std::fill(mean_vals.begin(), mean_vals.end(), T{}); 161 | 162 | for (const auto& row : arr) { 163 | std::transform(mean_vals.begin(), mean_vals.end(), row.begin(), 164 | mean_vals.begin(), std::plus()); 165 | } 166 | 167 | const T size = static_cast(arr.size()); 168 | std::transform(mean_vals.begin(), mean_vals.end(), mean_vals.begin(), 169 | [size](T val) { return val / size; }); 170 | } 171 | 172 | template 173 | void decimate_vec(const std::vector>& arr, T res, std::vector>& vec_dec) { 174 | if (arr.empty() || res <= T{}) { 175 | vec_dec.clear(); 176 | return; 177 | } 178 | 179 | std::vector arr_min; 180 | min_col(arr, arr_min); 181 | 182 | vec_dec.resize(arr.size(), std::vector(arr[0].size())); 183 | for (size_t i = 0; i < arr.size(); ++i) { 184 | std::transform(arr[i].begin(), arr[i].end(), arr_min.begin(), 185 | vec_dec[i].begin(), 186 | [res](T val, T min) { return std::floor((val - min) / res) + T{ 1 }; }); 187 | } 188 | } 189 | 190 | 191 | template 192 | void sort_indexes_by_row(const std::vector>& v, std::vector& idx, 193 | std::vector>& v_sorted) { 194 | if (v.empty()) { 195 | idx.clear(); 196 | v_sorted.clear(); 197 | return; 198 | } 199 | 200 | const size_t rows = v.size(); 201 | const size_t cols = v[0].size(); 202 | 203 | idx.resize(rows); 204 | std::iota(idx.begin(), idx.end(), 0); 205 | 206 | std::stable_sort(idx.begin(), idx.end(), [&v](size_t i1, size_t i2) { 207 | return std::lexicographical_compare(v[i1].begin(), v[i1].end(), 208 | v[i2].begin(), v[i2].end()); 209 | }); 210 | 211 | v_sorted.resize(rows); 212 | for (size_t i = 0; i < rows; ++i) { 213 | v_sorted[i] = v[idx[i]]; 214 | } 215 | } 216 | 217 | template 218 | void sort_indexes(const std::vector& v, std::vector& idx, 219 | std::vector& v_sorted) { 220 | if (v.empty()) { 221 | idx.clear(); 222 | v_sorted.clear(); 223 | return; 224 | } 225 | 226 | idx.resize(v.size()); 227 | std::iota(idx.begin(), idx.end(), 0); 228 | 229 | std::stable_sort(idx.begin(), idx.end(), 230 | [&v](IndexType i1, IndexType i2) { return v[i1] < v[i2]; }); 231 | 232 | v_sorted.resize(v.size()); 233 | std::transform(idx.begin(), idx.end(), v_sorted.begin(), 234 | [&v](IndexType i) { return v[i]; }); 235 | } 236 | 237 | 238 | template 239 | struct VectorHash { 240 | std::size_t operator()(const std::vector& vec) const { 241 | std::size_t seed = vec.size(); 242 | for (const auto& elem : vec) { 243 | seed ^= std::hash{}(elem)+0x9e3779b97f4a7c15ULL + (seed << 6) + (seed >> 2); 244 | } 245 | return seed; 246 | } 247 | }; 248 | template 249 | void unique_index_by_rows(const std::vector>& arr, 250 | std::vector& ia, 251 | std::vector& ic) { 252 | 253 | ia.clear(); 254 | ic.resize(arr.size()); 255 | // Map each unique row to its unique group index. 256 | std::unordered_map, size_t, VectorHash> row_to_group; 257 | 258 | size_t unique_counter = 0; 259 | for (size_t i = 0; i < arr.size(); ++i) { 260 | auto it = row_to_group.find(arr[i]); 261 | if (it == row_to_group.end()) { 262 | // First occurrence of this unique row. 263 | row_to_group[arr[i]] = unique_counter; 264 | ia.push_back(i); 265 | ic[i] = unique_counter; 266 | ++unique_counter; 267 | } 268 | else { 269 | ic[i] = it->second; 270 | } 271 | } 272 | } 273 | 274 | template 275 | void to_translated_vector(const ccPointCloud* pc, std::vector>& y) { 276 | if (!pc || pc->size() == 0) { 277 | y.clear(); 278 | return; 279 | } 280 | 281 | const unsigned pointCount = pc->size(); 282 | y.resize(pointCount, std::vector(3)); 283 | 284 | std::vector y_mean(3, 0); 285 | for (unsigned i = 0; i < pointCount; ++i) { 286 | const CCVector3* pv = pc->getPoint(i); 287 | y[i] = { static_cast(pv->x), static_cast(pv->y), static_cast(pv->z) }; 288 | std::transform(y_mean.begin(), y_mean.end(), y[i].begin(), y_mean.begin(), std::plus()); 289 | } 290 | 291 | std::transform(y_mean.begin(), y_mean.end(), y_mean.begin(), 292 | [pointCount](T val) { return val / pointCount; }); 293 | 294 | for (auto& point : y) { 295 | std::transform(point.begin(), point.end(), y_mean.begin(), point.begin(), std::minus()); 296 | } 297 | } 298 | 299 | 300 | template 301 | void unique_group(const std::vector& arr, std::vector>& u_group, 302 | std::vector& arr_unq, std::vector& ui) { 303 | if (arr.empty()) { 304 | arr_unq.clear(); 305 | ui.clear(); 306 | u_group.clear(); 307 | return; 308 | } 309 | 310 | std::vector arr_sorted_idx; 311 | std::vector arr_sorted; 312 | sort_indexes(arr, arr_sorted_idx, arr_sorted); 313 | 314 | arr_unq.clear(); 315 | ui.clear(); 316 | u_group.clear(); 317 | 318 | ui.push_back(arr_sorted_idx[0]); 319 | std::vector current_group = { arr_sorted_idx[0] }; 320 | 321 | for (size_t i = 1; i < arr.size(); ++i) { 322 | if (arr_sorted[i] != arr_sorted[i - 1]) { 323 | ui.push_back(arr_sorted_idx[i]); 324 | arr_unq.push_back(arr_sorted[i - 1]); 325 | u_group.push_back(std::move(current_group)); 326 | current_group = { arr_sorted_idx[i] }; 327 | } 328 | else { 329 | current_group.push_back(arr_sorted_idx[i]); 330 | } 331 | } 332 | 333 | arr_unq.push_back(arr_sorted.back()); 334 | u_group.push_back(std::move(current_group)); 335 | } 336 | 337 | // Overloaded versions with fewer return parameters 338 | template 339 | void unique_group(const std::vector& arr, std::vector>& u_group, 340 | std::vector& arr_unq) { 341 | std::vector ui; 342 | unique_group(arr, u_group, arr_unq, ui); 343 | } 344 | 345 | template 346 | void unique_group(const std::vector& arr, std::vector>& u_group) { 347 | std::vector arr_unq, ui; 348 | unique_group(arr, u_group, arr_unq, ui); 349 | } 350 | 351 | template 352 | void get_subset(const std::vector& arr,const std::vector& indices,std::vector& arr_sub) { 353 | arr_sub.resize(indices.size()); 354 | for (size_t i = 0; i < indices.size(); ++i) { 355 | arr_sub[i] = arr[indices[i]]; 356 | } 357 | } 358 | 359 | template 360 | void get_subset(const std::vector>& arr, const std::vector& indices, Eigen::MatrixXf& arr_sub) 361 | { 362 | arr_sub.setZero(); 363 | 364 | if (arr.empty()) 365 | { 366 | assert(false); 367 | return; 368 | } 369 | 370 | arr_sub.resize(arr[0].size(), indices.size()); 371 | 372 | for (size_t i = 0; i < indices.size(); ++i) 373 | { 374 | for (size_t j = 0; j < arr[0].size(); ++j) 375 | { 376 | arr_sub(j, i) = arr[indices[i]][j]; 377 | } 378 | } 379 | } 380 | 381 | template 382 | void get_subset(const std::vector>& arr, const std::vector& indices, std::vector>& arr_sub) 383 | { 384 | arr_sub.clear(); 385 | 386 | if (arr.empty() || indices.empty()) 387 | { 388 | return; 389 | } 390 | 391 | arr_sub.resize(indices.size()); 392 | for (size_t i = 0; i < indices.size(); ++i) 393 | { 394 | arr_sub[i] = arr[indices[i]]; 395 | } 396 | } 397 | 398 | template 399 | bool get_subset(ccPointCloud* pcd, std::vector& indices, std::vector>& arr_sub) 400 | { 401 | arr_sub.clear(); 402 | arr_sub.resize(indices.size(), std::vector(3)); 403 | for (size_t i = 0; i < indices.size(); ++i) 404 | { 405 | const CCVector3* vec = pcd->getPoint(indices[i]); 406 | arr_sub[i][0] = vec->x; 407 | arr_sub[i][1] = vec->y; 408 | arr_sub[i][2] = vec->z; 409 | } 410 | return true; 411 | } 412 | -------------------------------------------------------------------------------- /include/block.hpp: -------------------------------------------------------------------------------- 1 | /* block.hpp */ 2 | /* Vladimir Kolmogorov vnk@ist.ac.at */ 3 | /* Version slightly modified by Hugo Raguet 2016 (different error handling: no 4 | * error function, message handed to standard error) */ 5 | /* 6 | Template classes Block and DBlock 7 | Implement adding and deleting items of the same type in blocks. 8 | 9 | If there there are many items then using Block or DBlock 10 | is more efficient than using 'new' and 'delete' both in terms 11 | of memory and time since 12 | (1) On some systems there is some minimum amount of memory 13 | that 'new' can allocate (e.g., 64), so if items are 14 | small that a lot of memory is wasted. 15 | (2) 'new' and 'delete' are designed for items of varying size. 16 | If all items has the same size, then an algorithm for 17 | adding and deleting can be made more efficient. 18 | (3) All Block and DBlock functions are inline, so there are 19 | no extra function calls. 20 | 21 | Differences between Block and DBlock: 22 | (1) DBlock allows both adding and deleting items, 23 | whereas Block allows only adding items. 24 | (2) Block has an additional operation of scanning 25 | items added so far (in the order in which they were added). 26 | (3) Block allows to allocate several consecutive 27 | items at a time, whereas DBlock can add only a single item. 28 | 29 | Note that no constructors or destructors are called for items. 30 | 31 | Example usage for items of type 'MyType': 32 | 33 | /////////////////////////////////////////////////// 34 | #include "block.h" 35 | #define BLOCK_SIZE 1024 36 | typedef struct { int a, b; } MyType; 37 | MyType *ptr, *array[10000]; 38 | 39 | ... 40 | 41 | Block *block = new Block(BLOCK_SIZE); 42 | 43 | // adding items 44 | for (int i=0; i New(); 47 | ptr -> a = ptr -> b = rand(); 48 | } 49 | 50 | // reading items 51 | for (ptr=block->ScanFirst(); ptr; ptr=block->ScanNext()) 52 | { 53 | printf("%d %d\n", ptr->a, ptr->b); 54 | } 55 | 56 | delete block; 57 | 58 | ... 59 | 60 | DBlock *dblock = new DBlock(BLOCK_SIZE); 61 | 62 | // adding items 63 | for (int i=0; i New(); 66 | } 67 | 68 | // deleting items 69 | for (int i=0; i Delete(array[i]); 72 | } 73 | 74 | // adding items 75 | for (int i=0; i New(); 78 | } 79 | 80 | delete dblock; 81 | 82 | /////////////////////////////////////////////////// 83 | 84 | Note that DBlock deletes items by marking them as 85 | empty (i.e., by adding them to the list of free items), 86 | so that this memory could be used for subsequently 87 | added items. Thus, at each moment the memory allocated 88 | is determined by the maximum number of items allocated 89 | simultaneously at earlier moments. All memory is 90 | deallocated only when the destructor is called. 91 | */ 92 | 93 | #pragma once 94 | #include 95 | 96 | /***********************************************************************/ 97 | /***********************************************************************/ 98 | /***********************************************************************/ 99 | 100 | template class Block 101 | { 102 | public: 103 | /* Constructor. Arguments are the block size */ 104 | Block(int size) { first = last = nullptr; block_size = size; } 105 | 106 | /* Destructor. Deallocates all items added so far */ 107 | ~Block() { while (first) { block *next = first -> next; delete[] ((char*)first); first = next; } } 108 | 109 | /* Allocates 'num' consecutive items; returns pointer 110 | to the first item. 'num' cannot be greater than the 111 | block size since items must fit in one block */ 112 | Type *New(int num = 1) 113 | { 114 | Type *t; 115 | 116 | if (!last || last->current + num > last->last) 117 | { 118 | if (last && last->next) last = last -> next; 119 | else 120 | { 121 | block *next = (block *) new char [sizeof(block) + (block_size-1)*sizeof(Type)]; 122 | if (!next) { 123 | std::cerr << "Block: not enough memory." << std::endl; 124 | exit(EXIT_FAILURE); 125 | } 126 | if (last) last -> next = next; 127 | else first = next; 128 | last = next; 129 | last -> current = & ( last -> data[0] ); 130 | last -> last = last -> current + block_size; 131 | last -> next = nullptr; 132 | } 133 | } 134 | 135 | t = last -> current; 136 | last -> current += num; 137 | return t; 138 | } 139 | 140 | /* Returns the first item (or nullptr, if no items were added) */ 141 | Type *ScanFirst() 142 | { 143 | for (scan_current_block=first; scan_current_block; scan_current_block = scan_current_block->next) 144 | { 145 | scan_current_data = & ( scan_current_block -> data[0] ); 146 | if (scan_current_data < scan_current_block -> current) return scan_current_data ++; 147 | } 148 | return nullptr; 149 | } 150 | 151 | /* Returns the next item (or nullptr, if all items have been read) 152 | Can be called only if previous ScanFirst() or ScanNext() 153 | call returned not nullptr. */ 154 | Type *ScanNext() 155 | { 156 | while (scan_current_data >= scan_current_block -> current) 157 | { 158 | scan_current_block = scan_current_block -> next; 159 | if (!scan_current_block) return nullptr; 160 | scan_current_data = & ( scan_current_block -> data[0] ); 161 | } 162 | return scan_current_data ++; 163 | } 164 | 165 | struct iterator; // for overlapping scans 166 | Type *ScanFirst(iterator& i) 167 | { 168 | for (i.scan_current_block=first; i.scan_current_block; i.scan_current_block = i.scan_current_block->next) 169 | { 170 | i.scan_current_data = & ( i.scan_current_block -> data[0] ); 171 | if (i.scan_current_data < i.scan_current_block -> current) return i.scan_current_data ++; 172 | } 173 | return nullptr; 174 | } 175 | Type *ScanNext(iterator& i) 176 | { 177 | while (i.scan_current_data >= i.scan_current_block -> current) 178 | { 179 | i.scan_current_block = i.scan_current_block -> next; 180 | if (!i.scan_current_block) return nullptr; 181 | i.scan_current_data = & ( i.scan_current_block -> data[0] ); 182 | } 183 | return i.scan_current_data ++; 184 | } 185 | 186 | /* Marks all elements as empty */ 187 | void Reset() 188 | { 189 | block *b; 190 | if (!first) return; 191 | for (b=first; ; b=b->next) 192 | { 193 | b -> current = & ( b -> data[0] ); 194 | if (b == last) break; 195 | } 196 | last = first; 197 | } 198 | 199 | /***********************************************************************/ 200 | 201 | private: 202 | 203 | typedef struct block_st 204 | { 205 | Type *current, *last; 206 | struct block_st *next; 207 | Type data[1]; 208 | } block; 209 | 210 | int block_size; 211 | block *first; 212 | block *last; 213 | public: 214 | struct iterator 215 | { 216 | block *scan_current_block; 217 | Type *scan_current_data; 218 | }; 219 | private: 220 | block *scan_current_block; 221 | Type *scan_current_data; 222 | }; 223 | 224 | /***********************************************************************/ 225 | /***********************************************************************/ 226 | /***********************************************************************/ 227 | 228 | template class DBlock 229 | { 230 | public: 231 | /* Constructor. Arguments are the block size and 232 | (optionally) the pointer to the function which 233 | will be called if allocation failed; the message 234 | passed to this function is "Not enough memory!" */ 235 | DBlock(int size){ first = nullptr; first_free = nullptr; block_size = size; } 236 | 237 | /* Destructor. Deallocates all items added so far */ 238 | ~DBlock() { while (first) { block *next = first -> next; delete[] ((char*)first); first = next; } } 239 | 240 | /* Allocates one item */ 241 | Type *New() 242 | { 243 | block_item *item; 244 | 245 | if (!first_free) 246 | { 247 | block *next = first; 248 | first = (block *) new char [sizeof(block) + (block_size-1)*sizeof(block_item)]; 249 | if (!first) { 250 | std::cerr << "Block: not enough memory." << std::endl; 251 | exit(EXIT_FAILURE); 252 | } 253 | first_free = & (first -> data[0] ); 254 | for (item=first_free; item next_free = item + 1; 256 | item -> next_free = nullptr; 257 | first -> next = next; 258 | } 259 | 260 | item = first_free; 261 | first_free = item -> next_free; 262 | return (Type *) item; 263 | } 264 | 265 | /* Deletes an item allocated previously */ 266 | void Delete(Type *t) 267 | { 268 | ((block_item *) t) -> next_free = first_free; 269 | first_free = (block_item *) t; 270 | } 271 | 272 | /***********************************************************************/ 273 | 274 | private: 275 | 276 | typedef union block_item_st 277 | { 278 | Type t; 279 | block_item_st *next_free; 280 | } block_item; 281 | 282 | typedef struct block_st 283 | { 284 | struct block_st *next; 285 | block_item data[1]; 286 | } block; 287 | 288 | int block_size; 289 | block *first; 290 | block_item *first_free; 291 | }; 292 | -------------------------------------------------------------------------------- /include/ccTreeIsoDlg.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | //####################################################################################### 4 | //# # 5 | //# CLOUDCOMPARE PLUGIN: qTreeIso # 6 | //# # 7 | //# This program is free software; you can redistribute it and/or modify # 8 | //# it under the terms of the GNU General Public License as published by # 9 | //# the Free Software Foundation; version 2 or later of the License. # 10 | //# # 11 | //# This program is distributed in the hope that it will be useful, # 12 | //# but WITHOUT ANY WARRANTY; without even the implied warranty of # 13 | //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # 14 | //# GNU General Public License for more details. # 15 | //# # 16 | //# Please cite the following paper if you find this tool helpful # 17 | //# # 18 | //# Xi, Z.; Hopkinson, C. 3D Graph-Based Individual-Tree Isolation (Treeiso) # 19 | //# from Terrestrial Laser Scanning Point Clouds. Remote Sens. 2022, 14, 6116. # 20 | //# https://doi.org/10.3390/rs14236116 # 21 | //# # 22 | //# Our work relies on the cut-pursuit algorithm, please also consider citing: # 23 | //# Landrieu, L.; Obozinski, G. Cut Pursuit: Fast Algorithms to Learn Piecewise # 24 | //# Constant Functions on General Weighted Graphs. SIAM J. Imaging Sci. # 25 | //# 2017, 10, 1724–1766. # 26 | //# # 27 | //# Copyright © # 28 | //# Artemis Lab, Department of Geography & Environment # 29 | //# University of Lethbridge, Canada # 30 | //# # 31 | //# # 32 | //# Zhouxin Xi and Chris Hopkinson; # 33 | //# truebelief2010@gmail.com; c.hopkinson@uleth.ca # 34 | //# # 35 | //####################################################################################### 36 | 37 | // Matlab and python versions shared via: 38 | // https://github.com/truebelief/artemis_treeiso 39 | 40 | #ifndef CC_TREEISO_DLG_HEADER 41 | #define CC_TREEISO_DLG_HEADER 42 | 43 | #include "ui_TreeIsoDlg.h" 44 | 45 | //! Dialog for qTreeIso plugin 46 | class ccTreeIsoDlg : public QDialog, public Ui::TreeIsoDialog 47 | { 48 | Q_OBJECT 49 | 50 | public: 51 | //! Default constructor 52 | explicit ccTreeIsoDlg(QWidget* parent = nullptr); 53 | protected: 54 | }; 55 | 56 | #endif 57 | -------------------------------------------------------------------------------- /include/cp_d0_dist.hpp: -------------------------------------------------------------------------------- 1 | /*============================================================================= 2 | * Derived class for cut-pursuit algorithm with d0 (weighted contour length) 3 | * penalization, with a loss akin to a distance: 4 | * 5 | * minimize functional over a graph G = (V, E) 6 | * 7 | * F(x) = sum_v loss(y_v, x_v) + ||x||_d0 8 | * 9 | * where for each vertex, y_v and x_v are D-dimensional vectors, the loss is 10 | * a mix of the sum of square differences and a Kullback-Leibler divergence 11 | * (equivalent to cross-entropy in this formulation); see the 'loss' attribute, 12 | * and ||x||_d0 = sum_{uv in E : xu != xv} w_d0_uv , 13 | * 14 | * using greedy cut-pursuit approach with splitting initialized with k-means++. 15 | * 16 | * Parallel implementation with OpenMP API. 17 | * 18 | * L. Landrieu and G. Obozinski, Cut Pursuit: fast algorithms to learn 19 | * piecewise constant functions on general weighted graphs, SIAM Journal on 20 | * Imaging Science, 10(4):1724-1766, 2017 21 | * 22 | * L. Landrieu et al., A structured regularization framework for spatially 23 | * smoothing semantic labelings of 3D point clouds, ISPRS Journal of 24 | * Photogrammetry and Remote Sensing, 132:102-118, 2017 25 | * 26 | * Hugo Raguet 2019, 2022, 2023 27 | *===========================================================================*/ 28 | #pragma once 29 | #include 30 | #include "cut_pursuit_d0.hpp" 31 | 32 | /* real_t is the real numeric type, used for the base field and for the 33 | * objective functional computation; 34 | * index_t must be able to represent the number of vertices and of (undirected) 35 | * edges in the main graph; 36 | * comp_t must be able to represent the number of constant connected components 37 | * in the reduced graph */ 38 | template 39 | class Cp_d0_dist : public Cp_d0 40 | { 41 | public: 42 | /** constructor, destructor **/ 43 | 44 | /* only creates BK graph structure and assign Y, D */ 45 | Cp_d0_dist(index_t V, index_t E, const index_t* first_edge, 46 | const index_t* adj_vertices, const real_t* Y, size_t D = 1); 47 | 48 | /* the destructor does not free pointers which are supposed to be provided 49 | * by the user (forward-star graph structure given at construction, 50 | * monitoring arrays, observation arrays); IT DOES FREE THE REST 51 | * (components assignment and reduced problem elements, etc.), but this can 52 | * be prevented by getting the corresponding pointer member and setting it 53 | * to null beforehand */ 54 | ~Cp_d0_dist(); 55 | 56 | /** methods for manipulating parameters **/ 57 | 58 | /* parameters of d0 penalization (w_d0_uv) can be set using base class Cp 59 | * method set_edge_weights() */ 60 | 61 | /* specific loss */ 62 | real_t quadratic_loss() const { return D; } 63 | 64 | /* Y is changed only if the corresponding argument is not null */ 65 | void set_loss(real_t loss, const real_t* Y = nullptr, 66 | const real_t* vert_weights = nullptr, 67 | const real_t* coor_weights = nullptr); 68 | 69 | /* overload for changing only loss weights */ 70 | void set_loss(const real_t* vert_weights = nullptr, 71 | const real_t* coor_weights = nullptr) 72 | { set_loss(loss, nullptr, vert_weights, coor_weights); } 73 | 74 | /* overload base method for higher init and iter num */ 75 | void set_split_param(index_t max_split_size, comp_t K = 2, 76 | int split_iter_num = 1, real_t split_damp_ratio = 1.0, 77 | int split_values_init_num = 3, int split_values_iter_num = 3); 78 | 79 | void set_min_comp_weight(real_t min_comp_weight = 1.0); 80 | 81 | private: 82 | /** separable loss term: weighted square l2 or smoothed KL **/ 83 | const real_t* Y; // observations, D-by-V array, column major format 84 | 85 | /* D (or public method quadratic_loss()) for quadratic 86 | * f(x) = 1/2 ||y - x||_{l2,W}^2 , 87 | * where W is a diagonal metric (separable product along ℝ^V and ℝ^D), 88 | * that is ||y - x||_{l2,W}^2 = sum_{v in V} w_v ||x_v - y_v||_{l2,M}^2 89 | * = sum_{v in V} w_v sum_d m_d (x_vd - y_vd)^2. 90 | * 91 | * 0 < loss < 1 for smoothed Kullback-Leibler divergence (equivalent to 92 | * cross-entropy) on the probability simplex 93 | * f(x) = sum_v w_v KLs_m(x_v, y_v), 94 | * with KLs(y_v, x_v) = KL(s u + (1 - s) y_v , s u + (1 - s) x_v), where 95 | * KL is the regular Kullback-Leibler divergence, 96 | * u is the uniform discrete distribution over {1,...,D}, and 97 | * s = loss is the smoothing parameter 98 | * it yields 99 | * KLs(y_v, x_v) = - H(s u + (1 - s) y_v) 100 | * - sum_d (s/D + (1 - s) y_{v,d}) log(s/D + (1 - s) x_{v,d}) , 101 | * where H_m is the entropy, that is H(s u + (1 - s) y_v) 102 | * = - sum_d (s/D + (1 - s) y_{v,d}) log(s/D + (1 - s) y_{v,d}) ; 103 | * note that the choosen order of the arguments in the Kullback-Leibler 104 | * does not favor the entropy of x (H(s u + (1 - s) y_v) is a constant), 105 | * hence this loss is actually equivalent to cross-entropy; 106 | * 107 | * 1 <= loss < D for both: quadratic on coordinates from 1 to loss, and 108 | * Kullback-Leibler divergence on coordinates from loss + 1 to D; 109 | * 110 | * the weights w_v are set in vert_weights and m_d are set in coor_weights; 111 | * set corresponding pointer to null for no weight; note that coordinate 112 | * weights makes no sense for Kullback-Leibler divergence alone, but should 113 | * be used for weighting quadratic and KL when mixing both, in which case 114 | * coor_weights should be of length loss + 1 */ 115 | real_t loss; 116 | const real_t *vert_weights, *coor_weights; 117 | 118 | /* minimum weight allowed for a component */ 119 | real_t min_comp_weight; 120 | 121 | /* compute the functional f at a single vertex */ 122 | /* NOTA: not actually a metric, in spite of its name */ 123 | real_t distance(const real_t* Xv, const real_t* Yv) const; 124 | real_t fv(index_t v, const real_t* Xv) const override; 125 | /* override for storing values (used for iterate evolution) */ 126 | real_t compute_f() const override; 127 | real_t fXY; // dist(X, Y), reinitialized when freeing rX 128 | real_t fYY; // dist(Y, Y), reinitialized when modifying the loss 129 | 130 | /** reduced problem **/ 131 | real_t* comp_weights; 132 | 133 | /* allocate and compute reduced values; 134 | * do nothing if the array of reduced values is not null */ 135 | void solve_reduced_problem() override; 136 | 137 | /** greedy splitting **/ 138 | 139 | /* override for setting observation Yv */ 140 | using typename Cp::Split_info; 141 | void set_split_value(Split_info& split_info, comp_t k, index_t v) const 142 | override; 143 | /* override for average of observations Y */ 144 | void update_split_info(Split_info& split_info) const override; 145 | 146 | /** merging components **/ 147 | 148 | /* compute merge information of the given reduced edge; 149 | * populate member arrays merge_gains and merge_values; allocate value with 150 | * malloc; negative gain values might still get accepted, inacceptable 151 | * merge candidate must be deleted */ 152 | void compute_merge_candidate(index_t re) override; 153 | 154 | /* override for transfering component weights to root component */ 155 | comp_t accept_merge_candidate(index_t re) override; 156 | 157 | /* rough estimate of the number of operations for computing merge info of a 158 | * reduced edge; useful for estimating the number of parallel threads */ 159 | size_t merge_info_complexity() const override; 160 | 161 | index_t merge() override; // override for freeing comp_weights 162 | 163 | /** monitoring evolution **/ 164 | 165 | /* iterate evolution in terms of distance relative to distance to Y */ 166 | real_t compute_evolution() const override; 167 | 168 | /** type resolution for base template class members 169 | * https://isocpp.org/wiki/faq/templates#nondependent-name-lookup-members 170 | **/ 171 | using Cp_d0::delete_merge_candidate; 172 | using Cp_d0::merge_gains; 173 | using Cp_d0::merge_values; 174 | using Cp::set_split_param; 175 | using Cp::saturated_vert; 176 | using Cp::last_comp_assign; 177 | using Cp::eps; 178 | using Cp::D; 179 | using Cp::V; 180 | using Cp::rV; 181 | using Cp::rE; 182 | using Cp::rX; 183 | using Cp::last_rX; 184 | using Cp::monitor_evolution; 185 | using Cp::comp_assign; 186 | using Cp::label_assign; 187 | using Cp::comp_list; 188 | using Cp::first_vertex; 189 | using Cp::reduced_edges_u; 190 | using Cp::reduced_edges_v; 191 | using Cp::reduced_edge_weights; 192 | using Cp::is_saturated; 193 | using Cp::malloc_check; 194 | using Cp::real_inf; 195 | }; 196 | -------------------------------------------------------------------------------- /include/cut_pursuit.hpp: -------------------------------------------------------------------------------- 1 | /*============================================================================= 2 | * Base class for cut-pursuit algorithm 3 | * 4 | * L. Landrieu and G. Obozinski, Cut Pursuit: Fast Algorithms to Learn 5 | * Piecewise Constant Functions on General Weighted Graphs, SIAM Journal on 6 | * Imaging Sciences, 2017, 10, 1724-1766 7 | * 8 | * Hugo Raguet 2018, 2020, 2022 9 | * 10 | * This program is free software: you can redistribute it and/or modify 11 | * it under the terms of the GNU General Public License as published by 12 | * the Free Software Foundation, either version 3 of the License, or 13 | * (at your option) any later version. 14 | * 15 | * This program is distributed in the hope that it will be useful, 16 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | * GNU General Public License for more details. 19 | * 20 | * You should have received a copy of the GNU General Public License 21 | * along with this program. If not, see . 22 | *===========================================================================*/ 23 | #pragma once 24 | #include // for uintmax_t, requires C++11 25 | #include // for size_t, malloc, exit 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include "maxflow.hpp" 31 | 32 | /* real_t is the real numeric type, used for objective functional computation 33 | * and thus for edge weights and flow graph capacities; 34 | * index_t is an integer type able to hold the number of vertices and of edges 35 | * in the main graph; 36 | * comp_t is an integer type able to hold the maximum number of constant 37 | * connected components in the reduced graph; 38 | * value_t is the type associated to the space to which the values belong, it 39 | * is usually real_t, and if multidimensional, this must be specified in the 40 | * parameter D (e.g. for R^3, specify value_t = real_t and D = 3) */ 41 | template 43 | class Cp 44 | { 45 | public: 46 | /** constructor, destructor **/ 47 | 48 | Cp(index_t V, index_t E, const index_t* first_edge, 49 | const index_t* adj_vertices, size_t D = 1); 50 | 51 | /* the destructor does not free pointers which are supposed to be provided 52 | * by the user (forward-star graph structure given at construction, 53 | * monitoring arrays, etc.); IT DOES FREE THE REST (components assignment 54 | * and reduced problem elements, etc.), but this can be prevented by 55 | * getting the corresponding pointer member and setting it to null 56 | * beforehand */ 57 | virtual ~Cp(); 58 | 59 | /** methods for manipulating parameters **/ 60 | 61 | void reset_edges(); // bind all edges 62 | 63 | /* if 'edge_weights' is null, homogeneously equal to 'homo_edge_weight' */ 64 | void set_edge_weights(const real_t* edge_weights = nullptr, 65 | real_t homo_edge_weight = 1.0); 66 | 67 | void set_monitoring_arrays(real_t* objective_values = nullptr, 68 | double* elapsed_time = nullptr, real_t* iterate_evolution = nullptr); 69 | 70 | /* if rV is zero or unity, comp_assign will be automatically initialized; 71 | * if rV is zero, arbitrary components will be assigned at initialization, 72 | * in an attempt to optimize parallelization along components; 73 | * if rV is greater than one, comp_assign must be given and initialized; 74 | * comp_assign is free()'d by destructor, unless set to null beforehand */ 75 | void set_components(comp_t rV = 0, comp_t* comp_assign = nullptr); 76 | 77 | void set_cp_param(real_t dif_tol, int it_max, int verbose, real_t eps); 78 | /* overload for default eps parameter */ 79 | void set_cp_param(real_t dif_tol = 0.0, int it_max = 10, 80 | int verbose = 1000) 81 | { 82 | set_cp_param(dif_tol, it_max, verbose, 83 | std::numeric_limits::epsilon()); 84 | } 85 | 86 | /* tune split parameters; set max_split_size to V for no max */ 87 | void set_split_param(index_t max_split_size, comp_t K = 2, 88 | int split_iter_num = 1, real_t split_damp_ratio = 1.0, 89 | int split_values_init_num = 1, int split_values_iter_num = 1); 90 | 91 | //void set_parallel_param(int max_num_threads, 92 | // bool balance_parallel_split = true); 93 | ///* overload for default max_num_threads parameter */ 94 | //void set_parallel_param(bool balance_parallel_split) 95 | //{ 96 | // set_parallel_param(omp_get_max_threads(), balance_parallel_split); 97 | //} 98 | 99 | /* the 'get' methods takes pointers to pointers as arguments; a null means 100 | * that the user is not interested by the corresponding pointer; NOTA: 101 | * 1) if not explicitely set by the user, memory pointed by these members 102 | * is allocated using malloc(), and thus should be deleted with free() 103 | * 2) they are free()'d by destructor, unless set to null beforehand */ 104 | 105 | comp_t get_components(const comp_t** comp_assign = nullptr, 106 | const index_t** first_vertex = nullptr, 107 | const index_t** comp_list = nullptr) const; 108 | 109 | /* return the number of reduced edges */ 110 | index_t get_reduced_graph(const comp_t** reduced_edges = nullptr, 111 | const real_t** reduced_edge_weights = nullptr); 112 | 113 | /* retrieve the reduced iterate (values of the components); 114 | * WARNING: reduced values are free()'d by destructor */ 115 | const value_t* get_reduced_values() const; 116 | 117 | /* set the reduced iterate (values of the components); 118 | * WARNING: if not set to null before deletion of the main cp object, 119 | * this will be deleted by free() so the given pointer must have been 120 | * allocated with malloc() and the likes */ 121 | void set_reduced_values(value_t* rX); 122 | 123 | /* solve the main problem */ 124 | int cut_pursuit(bool init, std::function progressCallback); 125 | 126 | protected: 127 | /** main graph **/ 128 | 129 | const index_t V, E; // number of vertices, of edges 130 | 131 | /** forward-star graph representation **/ 132 | /* - edges are numeroted so that all edges originating from a same vertex 133 | * are consecutive; 134 | * - for each vertex, 'first_edge' indicates the first edge starting 135 | * from the vertex (or, if there are none, starting from the next vertex); 136 | * array of length V + 1, the first value is always zero and the last 137 | * value is always the total number of edges E 138 | * - for each edge, 'adj_vertices' indicates its ending vertex */ 139 | const index_t *first_edge, *adj_vertices; 140 | 141 | const real_t *edge_weights; // array of length E, weights of edges 142 | real_t homo_edge_weight; // homogeneous weights, set edge_weights to null 143 | 144 | /* dimension of the data; total size signal is V*D */ 145 | const size_t D; 146 | 147 | /** reduced graph **/ 148 | 149 | /* last_* are used to identify saturated components and to compute 150 | * iterate evolution */ 151 | comp_t rV, last_rV; // number of components (reduced vertices) 152 | value_t *rX, *last_rX; // reduced iterate (values of the components) 153 | index_t rE; // number of reduced edges 154 | /* assignment of each vertex to a component */ 155 | comp_t* comp_assign, *last_comp_assign; 156 | /* list the vertices of each components: 157 | * - vertices are gathered in 'comp_list' so that all vertices belonging 158 | * to a same components are consecutive 159 | * - for each component, 'first_vertex' indicates the index of its first 160 | * vertex in 'comp_list' */ 161 | index_t *comp_list, *first_vertex; 162 | /* reverse mapping of comp list: index of a given vertex within its 163 | * components (useful for working within components in parallel) */ 164 | index_t *index_in_comp; 165 | /* components saturation */ 166 | bool* is_saturated; 167 | comp_t saturated_comp; // number of saturated components 168 | index_t saturated_vert; // number of vertices within saturated components 169 | 170 | /* reduced connectivity 171 | * reduced edges represented with edges list (array of size twice the 172 | * number of reduced edges, consecutive indices are linked components) 173 | * guarantees: 174 | * 1) starting component identifiers are smaller than ending components 175 | * 2) increasing order of starting and ending components identifiers 176 | * (this eases some routines, like conversion to forward-star) 177 | * 3) each edge appears only once 178 | * 4) isolated components (not linked to any other component) are linked 179 | * to themselves with epsilon reduced weight */ 180 | comp_t* reduced_edges; 181 | 182 | /* easy accessors for reduced_edges */ 183 | const comp_t& reduced_edges_u(index_t re) const 184 | { return reduced_edges[((size_t) 2)*re]; } 185 | const comp_t& reduced_edges_v(index_t re) const 186 | { return reduced_edges[((size_t) 2)*re + 1]; } 187 | comp_t& reduced_edges_u(index_t re) 188 | { return reduced_edges[((size_t) 2)*re]; } 189 | comp_t& reduced_edges_v(index_t re) 190 | { return reduced_edges[((size_t) 2)*re + 1]; } 191 | 192 | real_t* reduced_edge_weights; 193 | 194 | /** parameters **/ 195 | 196 | real_t dif_tol, eps; // eps gives a characteristic precision 197 | /* with nonzero verbose information on the process will be printed; 198 | * for convex methods, this will be passed on to the reduced problem 199 | * subroutine, controlling the number of subiterations between prints */ 200 | int verbose; 201 | 202 | /** split components with graph cuts **/ 203 | struct Split_info { 204 | comp_t rv; // component to split 205 | comp_t K; // number of alternative values in the component's split 206 | /* first alternative to compete, useful to avoid competing with a value 207 | * already assigned to all vertices, or for single cut with K = 2 */ 208 | comp_t first_k; 209 | value_t* sX; // D-by-K array with alternative values in the split 210 | Split_info(comp_t rv); 211 | ~Split_info(); 212 | }; 213 | comp_t K; // maximum number of alternative values in any component's split 214 | int split_iter_num; // number of partition-and-update iterations 215 | real_t split_damp_ratio; // split damping along iterations 216 | /* number of repetitions in case of stochastic split values computation */ 217 | int split_values_init_num; 218 | int split_values_iter_num; 219 | 220 | virtual index_t split(); 221 | 222 | virtual void split_component(comp_t rv, Maxflow* maxflow); 223 | 224 | /* initialize candidate split values, schedule and assignments; 225 | * base class version implements a kmeans++, with distances replaced by 226 | * split costs, and centroids assignments and updates made purely virtual 227 | * for specializing data and computations */ 228 | virtual Split_info initialize_split_info(comp_t rv); 229 | /* make split value k that would optimaly fit vertex v */ 230 | virtual void set_split_value(Split_info& split_info, comp_t k, index_t v) 231 | const = 0; 232 | /* usually some kind of averaging; must remove alternative values which are 233 | * no longer interesting (e.g. associated to no vertex) */ 234 | virtual void update_split_info(Split_info& split_info) const = 0; 235 | /* rough estimate of the number of operations for initializing the split 236 | * values and all subsequent updates */ 237 | virtual uintmax_t split_values_complexity() const; 238 | /* compute unary cost of split value k at vertex v in component rv; 239 | * can be +infinity, not -infinity */ 240 | virtual real_t vert_split_cost(const Split_info& split_info, index_t v, 241 | comp_t k) const = 0; 242 | /* overload for possibly saving computations for the difference when 243 | * choosing alternative k against alternative l */ 244 | virtual real_t vert_split_cost(const Split_info& split_info, index_t v, 245 | comp_t k, comp_t l) const; 246 | /* compute binary cost of choosing alternatives lu and lv at edge e */ 247 | virtual real_t edge_split_cost(const Split_info& split_info, index_t e, 248 | comp_t lu, comp_t lv) const = 0; 249 | 250 | /* methods for setting and checking edge status */ 251 | bool is_cut(index_t e) const // check if edge e is cut (active) 252 | { return edge_status[e] == CUT; } 253 | bool is_bind(index_t e) const // check if edge e is binding (inactive) 254 | { return edge_status[e] == BIND; } 255 | bool is_separation(index_t e) const // check if edge is a separation 256 | { return edge_status[e] == SEPARATION; } 257 | void cut(index_t e) // flag a cut (active) edge 258 | { edge_status[e] = CUT; } 259 | void bind(index_t e) // flag a binding (inactive) edge 260 | { edge_status[e] = BIND; } 261 | void separate(index_t e) // flag a balancing separation edge 262 | { edge_status[e] = SEPARATION; } 263 | 264 | /* split large components for balancing split, either for parallelism or 265 | * for preventing bad maxflow performance on huge components; 266 | * new components are computed by breadth-first search, restarting when a 267 | * maximum size is reached; 268 | * reorder comp_list and populate first vertex accordingly; 269 | * rV_new is the number of components resulting from such split; 270 | * rV_big is the number of large original components split this way; 271 | * first_vertex_big holds the first vertices of components split this way; 272 | * returns the number of useful parallel threads */ 273 | int balance_split(comp_t& rV_new, comp_t& rV_big, 274 | index_t*& first_vertex_big); 275 | 276 | /* after splitting, separation edges must be removed or activated; 277 | * when called, first_vertex contains additional components due to large 278 | * components being split by balance_split(); 279 | * NOTA: currently, separation edges must be either removed or activated 280 | * at this step; this cannot wait for a future split step, because 281 | * components list of vertex must be kept consecutive for parallel 282 | * treatment of the resulting connected components, and removing parallel 283 | * separation edges in a later step might connect components whose list of 284 | * vertices are not consecutive */ 285 | virtual index_t remove_balance_separations(comp_t rV_new); 286 | 287 | /* revert the above process; 288 | * no change to comp_list, only suppress elements from first_vertex */ 289 | void revert_balance_split(comp_t rV_new, comp_t rV_big, 290 | index_t* first_vertex_big); 291 | 292 | /* rough estimate of the number of operations for split step; 293 | * useful for estimating the number of parallel threads */ 294 | uintmax_t maxflow_complexity() const 295 | { return (uintmax_t) 2*E + V; } // just for a graph cut; heuristic 296 | virtual uintmax_t split_complexity() const; 297 | 298 | /* prefered alternative value for each vertex */ 299 | comp_t*& label_assign = comp_assign; // reuse the same storage 300 | 301 | /** compute reduced values **/ 302 | 303 | virtual void solve_reduced_problem() = 0; 304 | 305 | /** merging components when deemed useful **/ 306 | 307 | /* during the merging step, merged components are stored as chains, 308 | * represented by arrays of length rV 'merge_chains_root', '_next' and 309 | * '_leaf'; merge chain involving component rv follows the scheme 310 | * root[rv] -> ... -> rv -> next[rv] -> ... -> leaf[rv] ; 311 | * NOTA: CHAIN_END is a special values, and: 312 | * - only next[rv] is always up-to-date; 313 | * - root[rv] is always a strictly preceding component in its chain, or 314 | * CHAIN_END if rv is a root; 315 | * - leaf[rv] is up-to-date if rv is a root; 316 | * - rv is the leaf of its chain if, and only if next[rv] == CHAIN_END; 317 | * an additional requirement is that the root of each chain should be the 318 | * component in the chain with lowest index */ 319 | comp_t get_merge_chain_root(comp_t rv) const; 320 | 321 | /* merge the merge chains of the two given roots; 322 | * the root of the resulting chain will be the component in the chains 323 | * with lowest index, which is returned by the function */ 324 | comp_t merge_components(comp_t ru, comp_t rv); 325 | 326 | /* compute the merge chains and return the number of effective merges */ 327 | virtual comp_t compute_merge_chains() = 0; 328 | 329 | /* main routine using the above to perform the merge step; 330 | * NOTA: reduced edges must guarantee 1-4), see member declaration */ 331 | virtual index_t merge(); 332 | 333 | /** monitoring evolution **/ 334 | 335 | /* test if computation of evolution is required */ 336 | virtual bool monitor_evolution() const 337 | { return dif_tol > (real_t) 0.0 || iterate_evolution; } 338 | 339 | /* compute relative iterate evolution */ 340 | virtual real_t compute_evolution() const = 0; 341 | 342 | /* compute objective functional, often on the reduced problem objects */ 343 | virtual real_t compute_objective() const = 0; 344 | 345 | /* allocate memory and fail with error message if not successful */ 346 | static void* malloc_check(size_t size) 347 | { 348 | void *ptr = malloc(size); 349 | if (!ptr){ 350 | std::cerr << "Cut-pursuit: not enough memory." << std::endl; 351 | exit(EXIT_FAILURE); 352 | } 353 | return ptr; 354 | } 355 | 356 | /* simply free if size is zero */ 357 | static void* realloc_check(void* ptr, size_t size) 358 | { 359 | if (!size){ 360 | free(ptr); 361 | return nullptr; 362 | } 363 | ptr = realloc(ptr, size); 364 | if (!ptr){ 365 | std::cerr << "Cut-pursuit: not enough memory." << std::endl; 366 | exit(EXIT_FAILURE); 367 | } 368 | return ptr; 369 | } 370 | 371 | ///** control parallelization **/ 372 | //int max_num_threads; // maximum number of parallel threads 373 | ///* take into account max_num_threads attribute */ 374 | //int compute_num_threads(uintmax_t num_ops, uintmax_t max_threads) const 375 | //{ 376 | // int num_threads = ::compute_num_threads(num_ops, max_threads); 377 | // return num_threads < max_num_threads ? num_threads : max_num_threads; 378 | //} 379 | ///* overload for max_threads defaulting to num_ops */ 380 | //int compute_num_threads(uintmax_t num_ops) const 381 | //{ return compute_num_threads(num_ops, num_ops); } 382 | 383 | /* representing infinite values (has_infinity checked by constructor) */ 384 | static real_t real_inf(){ return std::numeric_limits::infinity(); } 385 | 386 | private: 387 | enum Edge_status : char // requires C++11 to ensure 1 byte 388 | {BIND, CUT, SEPARATION}; 389 | Edge_status* edge_status; // edge activation 390 | 391 | /* parameters */ 392 | int it_max; // maximum number of cut-pursuit iterations 393 | //bool balance_parallel_split; // switch parallel split balancing 394 | index_t max_split_size; // ensure maxflow not working on components too big 395 | 396 | /* monitoring */ 397 | real_t* objective_values; 398 | double* elapsed_time; 399 | real_t* iterate_evolution; 400 | 401 | /* during the merging step, merged components are stored as chains */ 402 | comp_t *merge_chains_root, *merge_chains_next, *merge_chains_leaf; 403 | 404 | double monitor_time(std::chrono::steady_clock::time_point start) const; 405 | 406 | void print_progress(int it, real_t dif, double t) const; 407 | 408 | /* set components assignment and values (and allocate them if needed); 409 | * assumes that no edge of the graph are cut when it is called */ 410 | void initialize(); 411 | 412 | /* initialize with components specified in 'comp_assign' */ 413 | void assign_connected_components(); 414 | 415 | /* initialize with only one component and reduced graph accordingly */ 416 | void single_connected_component(); 417 | 418 | /* compute binding reverse edge forward star graph structure */ 419 | void get_bind_reverse_edges(comp_t rv, index_t*& first_edge_r, 420 | index_t*& adj_vertices_r); 421 | 422 | /* update connected components and count saturated ones */ 423 | bool compute_connected_components(); 424 | 425 | 426 | /* allocate and compute reduced graph structure; 427 | * NOTA: reduced edges must guarantee 1-4), see member declaration */ 428 | void compute_reduced_graph(); 429 | }; 430 | -------------------------------------------------------------------------------- /include/cut_pursuit_d0.hpp: -------------------------------------------------------------------------------- 1 | /*============================================================================= 2 | * Derived class for cut-pursuit algorithm with d0 (weighted contour length) 3 | * penalization, with a separable loss term over a given space: 4 | * 5 | * minimize functional over a graph G = (V, E) 6 | * 7 | * F(x) = f(x) + ||x||_d0 8 | * 9 | * where for each vertex, x_v belongs in a possibly multidimensional space Ω, 10 | * f(x) = sum_{v in V} f_v(x_v) is separable along V with f_v : Ω → ℝ 11 | * and ||x||_d0 = sum_{uv in E : xu != xv} w_d0_uv , 12 | * 13 | * using greedy cut-pursuit approach. 14 | * 15 | * Parallel implementation with OpenMP API. 16 | * 17 | * References: 18 | * 19 | * L. Landrieu and G. Obozinski, Cut Pursuit: fast algorithms to learn 20 | * piecewise constant functions on general weighted graphs, SIAM Journal on 21 | * Imaging Science, 10(4):1724-1766, 2017 22 | * 23 | * L. Landrieu et al., A structured regularization framework for spatially 24 | * smoothing semantic labelings of 3D point clouds, ISPRS Journal of 25 | * Photogrammetry and Remote Sensing, 132:102-118, 2017 26 | * 27 | * Hugo Raguet 2019, 2020 28 | *===========================================================================*/ 29 | #pragma once 30 | #include "cut_pursuit.hpp" 31 | 32 | /* real_t is the real numeric type, used for objective functional computation; 33 | * index_t must be able to represent the number of vertices and of (undirected) 34 | * edges in the main graph; 35 | * comp_t must be able to represent the number of constant connected components 36 | * in the reduced graph; 37 | * value_t is the type associated to the space to which the values belong, it 38 | * is usually real_t, and if multidimensional, this must be specified in the 39 | * parameter D (e.g. for R^3, specify value_t = real_t and D = 3) */ 40 | template 42 | class Cp_d0 : public Cp 43 | { 44 | public: 45 | Cp_d0(index_t V, index_t E, const index_t* first_edge, 46 | const index_t* adj_vertices, size_t D = 1); 47 | 48 | protected: 49 | /* compute the functional f at a single vertex */ 50 | virtual real_t fv(index_t v, const value_t* Xv) const = 0; 51 | 52 | /* compute graph contour length; use reduced edges and reduced weights */ 53 | real_t compute_graph_d0() const; 54 | 55 | /* compute objective functional */ 56 | virtual real_t compute_f() const; 57 | real_t compute_objective() const override; 58 | 59 | /** greedy splitting **/ 60 | 61 | /* compute unary cost of split value k at vertex v in component rv */ 62 | using typename Cp::Split_info; 63 | real_t vert_split_cost(const Split_info& split_info, index_t v, 64 | comp_t k) const override; 65 | /* compute binary cost of choosing alternatives lu and lv at edge e */ 66 | real_t edge_split_cost(const Split_info& split_info, index_t e, 67 | comp_t lu, comp_t lv) const override; 68 | 69 | /** merging components **/ 70 | 71 | /* the strategy is to compute the gain on the functional for the merge of 72 | * each reduced edge, and accept greedily the candidates with greatest 73 | * gain; merge gains and values of neighboring components might be impacted 74 | * by the merge of two components, see implementation for details; override 75 | * the following virtual merge methods for taking additional information 76 | * into account 77 | * NOTA: during the merging step, merged components are stored as chains, 78 | * see header `cut_pursuit.hpp` for details */ 79 | 80 | /* arrays are indexed by reduced edges */ 81 | real_t* merge_gains; // gain on the objective if components are merged 82 | value_t** merge_values; // the value of the components if they are merged 83 | 84 | /* compute merge information of the given reduced edge; 85 | * populate member arrays merge_gains and merge_values; allocate value with 86 | * malloc; negative gain values might still get accepted, inacceptable 87 | * merge candidate must be deleted */ 88 | virtual void compute_merge_candidate(index_t re) = 0; 89 | 90 | /* accept and delete the merge candidate, and return the component root of 91 | * the resulting merge chain; can be overriden to take into account other 92 | * merge effects */ 93 | virtual comp_t accept_merge_candidate(index_t re); 94 | 95 | /* frees the merge value and flag it to null pointer */ 96 | void delete_merge_candidate(index_t re); 97 | 98 | /* rough estimate of the number of operations for computing merge info of a 99 | * reduced edge; useful for estimating the number of parallel threads */ 100 | virtual size_t merge_info_complexity() const = 0; 101 | 102 | 103 | 104 | /** type resolution for base template class members 105 | * https://isocpp.org/wiki/faq/templates#nondependent-name-lookup-members 106 | **/ 107 | using Cp::get_merge_chain_root; 108 | using Cp::K; 109 | using Cp::split_iter_num; 110 | using Cp::split_damp_ratio; 111 | using Cp::split_values_init_num; 112 | using Cp::split_values_iter_num; 113 | using Cp::V; 114 | using Cp::E; 115 | using Cp::D; 116 | using Cp::rV; 117 | using Cp::rE; 118 | using Cp::rX; 119 | using Cp::edge_weights; 120 | using Cp::homo_edge_weight; 121 | using Cp::comp_list; 122 | using Cp::first_vertex; 123 | using Cp::reduced_edges_u; 124 | using Cp::reduced_edges_v; 125 | using Cp::reduced_edge_weights; 126 | using Cp::merge_components; 127 | using Cp::realloc_check; 128 | using Cp::malloc_check; 129 | 130 | private: 131 | /* compute the merge chains and return the number of effective merges */ 132 | comp_t compute_merge_chains() override; 133 | }; 134 | -------------------------------------------------------------------------------- /include/maxflow.hpp: -------------------------------------------------------------------------------- 1 | /* maxflow.hpp */ 2 | /* modified from graph.h by Hugo Raguet 2020, for use with cut-pursuit 3 | * algorithms */ 4 | /* 5 | Copyright Vladimir Kolmogorov and Yuri Boykov 6 | 7 | This file is part of MAXFLOW. 8 | 9 | MAXFLOW is free software: you can redistribute it and/or modify 10 | it under the terms of the GNU General Public License as published by 11 | the Free Software Foundation, either version 3 of the License, or 12 | (at your option) any later version. 13 | 14 | MAXFLOW is distributed in the hope that it will be useful, 15 | but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | GNU General Public License for more details. 18 | 19 | You should have received a copy of the GNU General Public License 20 | along with MAXFLOW. If not, see . 21 | =============================================================================*/ 22 | 23 | #pragma once 24 | #include "block.hpp" 25 | 26 | /* index_t is an integer type able to hold the number of nodes and of edges; 27 | * flow_t is a numeric type for the flow (capacities) */ 28 | template class Maxflow 29 | { 30 | public: 31 | Maxflow(index_t node_num, index_t edge_num); 32 | 33 | ~Maxflow(); 34 | 35 | void add_edge(index_t i, index_t j); 36 | 37 | flow_t& terminal_capacity(index_t i); 38 | 39 | void set_edge_capacities(index_t e, flow_t cap, flow_t rev_cap); 40 | 41 | /* retrieve (signed) flow passing through a given edge 42 | second parameter is the initial capacity */ 43 | flow_t get_edge_flow(index_t e, flow_t cap); 44 | 45 | void maxflow(); 46 | 47 | bool is_sink(index_t i, bool default_side = false); 48 | 49 | private: 50 | struct node; 51 | struct arc; 52 | 53 | // internal variables and functions 54 | 55 | struct node 56 | { 57 | arc *first; // first outcoming arc 58 | arc *parent; // node's parent 59 | node *next; // pointer to the next active node 60 | index_t TS; // timestamp showing when DIST was computed 61 | index_t DIST; // distance to the terminal 62 | bool is_sink : 1; // indicate source or sink tree, if parent not null 63 | /* positive if connected to source, negative if connected to sink */ 64 | flow_t term_res_cap; 65 | }; 66 | 67 | struct arc 68 | { 69 | node* head; // node the arc points to 70 | arc* next; // next arc with the same originating node 71 | arc* sister; // reverse arc 72 | flow_t res_cap; // residual capacity 73 | }; 74 | 75 | struct nodeptr 76 | { 77 | node *ptr; 78 | nodeptr *next; 79 | }; 80 | static const int NODEPTR_BLOCK_SIZE = 128; 81 | 82 | node *nodes, *node_last; 83 | arc *arcs, *arc_last; 84 | 85 | /* special constants for parent arcs */ 86 | arc reserved_terminal_arc; // the parent is an arc to terminal 87 | arc* const terminal; 88 | arc reserved_orphan_arc; // no parent 89 | arc* const orphan; 90 | 91 | DBlock *nodeptr_block; 92 | 93 | node *queue_first[2], *queue_last[2]; // list of active nodes 94 | nodeptr *orphan_first, *orphan_last; // list of pointers to orphans 95 | index_t TIME; // monotonically increasing global counter 96 | 97 | // functions for processing active list 98 | void set_active(node *i); 99 | node *next_active(); 100 | 101 | // functions for processing orphans list 102 | void set_orphan_front(node* i); // add to the beginning of the list 103 | void set_orphan_rear(node* i); // add to the end of the list 104 | 105 | void maxflow_init(); // called if reuse_trees == false 106 | void augment(arc *middle_arc); 107 | void process_source_orphan(node *i); 108 | void process_sink_orphan(node *i); 109 | }; 110 | 111 | #define TPL template 112 | #define MXFL Maxflow 113 | 114 | TPL inline void MXFL::add_edge(index_t _i, index_t _j) 115 | { 116 | arc *a = arc_last++; 117 | arc *a_rev = arc_last++; 118 | 119 | node* i = nodes + _i; 120 | node* j = nodes + _j; 121 | 122 | a->sister = a_rev; 123 | a_rev->sister = a; 124 | a->next = i->first; 125 | i->first = a; 126 | a_rev->next = j->first; 127 | j->first = a_rev; 128 | a->head = j; 129 | a_rev->head = i; 130 | } 131 | 132 | TPL inline flow_t& MXFL::terminal_capacity(index_t i) 133 | { 134 | return nodes[i].term_res_cap; 135 | } 136 | 137 | TPL inline void MXFL::set_edge_capacities(index_t e, flow_t cap, 138 | flow_t rev_cap) 139 | { 140 | arc* a = arcs + (size_t) 2*e; 141 | a->res_cap = cap; 142 | (a + 1)->res_cap = rev_cap; 143 | } 144 | 145 | TPL inline flow_t MXFL::get_edge_flow(index_t e, flow_t cap) 146 | { 147 | arc* a = arcs + (size_t) 2*e; 148 | return cap - a->res_cap; 149 | } 150 | 151 | TPL inline bool MXFL::is_sink(index_t i, bool default_side) 152 | { 153 | return nodes[i].parent ? nodes[i].is_sink : default_side; 154 | } 155 | 156 | #undef TPL 157 | #undef MXFL 158 | -------------------------------------------------------------------------------- /include/qTreeIso.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | //####################################################################################### 4 | //# # 5 | //# CLOUDCOMPARE PLUGIN: qTreeIso # 6 | //# # 7 | //# This program is free software; you can redistribute it and/or modify # 8 | //# it under the terms of the GNU General Public License as published by # 9 | //# the Free Software Foundation; version 2 or later of the License. # 10 | //# # 11 | //# This program is distributed in the hope that it will be useful, # 12 | //# but WITHOUT ANY WARRANTY; without even the implied warranty of # 13 | //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # 14 | //# GNU General Public License for more details. # 15 | //# # 16 | //# Please cite the following paper if you find this tool helpful # 17 | //# # 18 | //# Xi, Z.; Hopkinson, C. 3D Graph-Based Individual-Tree Isolation (Treeiso) # 19 | //# from Terrestrial Laser Scanning Point Clouds. Remote Sens. 2022, 14, 6116. # 20 | //# https://doi.org/10.3390/rs14236116 # 21 | //# # 22 | //# Our work relies on the cut-pursuit algorithm, please also consider citing: # 23 | //# Landrieu, L.; Obozinski, G. Cut Pursuit: Fast Algorithms to Learn Piecewise # 24 | //# Constant Functions on General Weighted Graphs. SIAM J. Imaging Sci. # 25 | //# 2017, 10, 1724–1766. # 26 | //# # 27 | //# Copyright © # 28 | //# Artemis Lab, Department of Geography & Environment # 29 | //# University of Lethbridge, Canada # 30 | //# # 31 | //# # 32 | //# Zhouxin Xi and Chris Hopkinson; # 33 | //# truebelief2010@gmail.com; c.hopkinson@uleth.ca # 34 | //# # 35 | //####################################################################################### 36 | 37 | // Matlab and python versions shared via: 38 | // https://github.com/truebelief/artemis_treeiso 39 | 40 | #include "ccStdPluginInterface.h" 41 | 42 | class ccTreeIsoDlg; 43 | 44 | //! TreeIso plugin 45 | class qTreeIso : public QObject, public ccStdPluginInterface 46 | { 47 | Q_OBJECT 48 | Q_INTERFACES( ccPluginInterface ccStdPluginInterface ) 49 | 50 | Q_PLUGIN_METADATA( IID "cccorp.cloudcompare.plugin.qTreeISO" FILE "../info.json" ) 51 | 52 | public: 53 | 54 | //! Default constructor 55 | explicit qTreeIso(QObject* parent = nullptr); 56 | //! Destructor 57 | virtual ~qTreeIso() = default; 58 | 59 | //inherited from ccStdPluginInterface 60 | void onNewSelection(const ccHObject::Container& selectedEntities) override; 61 | QList getActions() override; 62 | void registerCommands(ccCommandLineInterface* cmd) override; 63 | 64 | //! Parameters 65 | struct Parameters 66 | { 67 | float reg_strength1 = 1.0f; //lambda1 68 | int min_nn1 = 5; //K1:key parameter 69 | float decimate_res1 = 0.05f; 70 | int threads1 = 1; 71 | 72 | int reg_strength2 = 20; //lambda2:key parameter 73 | int min_nn2 = 20; //K2:key parameter 74 | float decimate_res2 = 0.1f; 75 | float max_gap = 2.0f; 76 | int threads2 = 1; 77 | 78 | float rel_height_length_ratio = 0.5f; //rho 79 | float vertical_weight = 0.5; //w:key parameter 80 | }; 81 | 82 | protected: 83 | 84 | //! Slot called when associated ation is triggered 85 | void doAction(); 86 | 87 | void init_segs(const Parameters& parameters, QWidget* parent = nullptr); 88 | void intermediate_segs(const Parameters& parameters, QWidget* parent = nullptr); 89 | void final_segs(const Parameters& parameters, QWidget* parent = nullptr); 90 | 91 | protected: // members 92 | 93 | //! Associated action 94 | QAction* m_action; 95 | }; 96 | -------------------------------------------------------------------------------- /include/qTreeIsoCommands.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | //####################################################################################### 4 | //# # 5 | //# CLOUDCOMPARE PLUGIN: qTreeIso # 6 | //# # 7 | //# This program is free software; you can redistribute it and/or modify # 8 | //# it under the terms of the GNU General Public License as published by # 9 | //# the Free Software Foundation; version 2 or later of the License. # 10 | //# # 11 | //# This program is distributed in the hope that it will be useful, # 12 | //# but WITHOUT ANY WARRANTY; without even the implied warranty of # 13 | //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # 14 | //# GNU General Public License for more details. # 15 | //# # 16 | //# Please cite the following paper if you find this tool helpful # 17 | //# # 18 | //# Xi, Z.; Hopkinson, C. 3D Graph-Based Individual-Tree Isolation (Treeiso) # 19 | //# from Terrestrial Laser Scanning Point Clouds. Remote Sens. 2022, 14, 6116. # 20 | //# https://doi.org/10.3390/rs14236116 # 21 | //# # 22 | //# Our work relies on the cut-pursuit algorithm, please also consider citing: # 23 | //# Landrieu, L.; Obozinski, G. Cut Pursuit: Fast Algorithms to Learn Piecewise # 24 | //# Constant Functions on General Weighted Graphs. SIAM J. Imaging Sci. # 25 | //# 2017, 10, 1724–1766. # 26 | //# # 27 | //# Copyright © # 28 | //# Artemis Lab, Department of Geography & Environment # 29 | //# University of Lethbridge, Canada # 30 | //# # 31 | //# # 32 | //# Zhouxin Xi and Chris Hopkinson; # 33 | //# truebelief2010@gmail.com; c.hopkinson@uleth.ca # 34 | //# # 35 | //####################################################################################### 36 | 37 | // Matlab and python versions shared via: 38 | // https://github.com/truebelief/artemis_treeiso 39 | 40 | //CloudCompare 41 | #include 42 | 43 | //Local 44 | #include "ccTreeIsoDlg.h" 45 | #include "qTreeIso.h" 46 | #include "TreeIso.h" 47 | 48 | static const char COMMAND_TREEISO[] = "TREEISO"; 49 | 50 | static const char COMMAND_LAMBDA1[] = "LAMBDA1"; 51 | static const char COMMAND_K1[] = "K1"; 52 | static const char COMMAND_DECIMATE_RESOLUTION1[] = "DECIMATE_RESOLUTION1"; 53 | 54 | static const char COMMAND_LAMBDA2[] = "LAMBDA2"; 55 | static const char COMMAND_K2[] = "K2"; 56 | static const char COMMAND_MAX_GAP[] = "MAX_GAP"; 57 | static const char COMMAND_DECIMATE_RESOLUTION2[] = "DECIMATE_RESOLUTION2"; 58 | 59 | static const char COMMAND_RHO[] = "RHO"; 60 | static const char COMMAND_VERTICAL_OVERLAP_WEIGHT[] = "VERTICAL_OVERLAP_WEIGHT"; 61 | 62 | //! qTreeIso command line processor 63 | struct CommandTreeIso : public ccCommandLineInterface::Command 64 | { 65 | CommandTreeIso() : ccCommandLineInterface::Command("TREEISO", COMMAND_TREEISO) {} 66 | 67 | bool process(ccCommandLineInterface& cmd) override 68 | { 69 | cmd.print("[TreeIso]"); 70 | 71 | if (cmd.clouds().empty()) 72 | { 73 | cmd.error("No cloud loaded"); 74 | return false; 75 | } 76 | 77 | //initial parameters 78 | qTreeIso::Parameters parameters; 79 | 80 | bool try_init_seg = false; 81 | bool try_intermediate_seg = false; 82 | bool try_final_seg = false; 83 | 84 | while (!cmd.arguments().empty()) 85 | { 86 | const QString& ARGUMENT = cmd.arguments().front(); 87 | if ((ccCommandLineInterface::IsCommand(ARGUMENT, COMMAND_LAMBDA1))) 88 | { 89 | try_init_seg = true; 90 | cmd.arguments().pop_front(); 91 | bool convert = false; 92 | 93 | parameters.reg_strength1 = cmd.arguments().takeFirst().toFloat(&convert); 94 | if ((!convert) & (parameters.reg_strength1 <= 0.0)) 95 | { 96 | return cmd.error(QObject::tr("Invalid parameter: value after \"-%1\"").arg(COMMAND_LAMBDA1)); 97 | } 98 | cmd.print(QString("lambda1 (Regularization strength for initial segmentation) set: %1").arg(parameters.reg_strength1)); 99 | } 100 | else if (ccCommandLineInterface::IsCommand(ARGUMENT, COMMAND_K1)) 101 | { 102 | try_init_seg = true; 103 | cmd.arguments().pop_front(); 104 | bool convert = false; 105 | 106 | parameters.min_nn1 = cmd.arguments().takeFirst().toInt(&convert); 107 | if ((!convert) & (parameters.min_nn1 < 3)) 108 | { 109 | return cmd.error(QObject::tr("Invalid parameter: value after \"-%1\"").arg(COMMAND_K1)); 110 | } 111 | cmd.print(QString("K1 (Nearest neighbors to search for initial segmentation) set: %1").arg(parameters.min_nn1)); 112 | } 113 | else if (ccCommandLineInterface::IsCommand(ARGUMENT, COMMAND_DECIMATE_RESOLUTION1)) 114 | { 115 | try_init_seg = true; 116 | cmd.arguments().pop_front(); 117 | bool convert = false; 118 | 119 | parameters.decimate_res1 = cmd.arguments().takeFirst().toFloat(&convert); 120 | if ((!convert) & (parameters.decimate_res1 < 0.001)) 121 | { 122 | return cmd.error(QObject::tr("Invalid parameter: value after \"-%1\"").arg(COMMAND_DECIMATE_RESOLUTION1)); 123 | } 124 | cmd.print(QString("Decimated resolution (in m) for initial segmentation set: %1").arg(parameters.decimate_res1)); 125 | } 126 | else if (ccCommandLineInterface::IsCommand(ARGUMENT, COMMAND_LAMBDA2)) 127 | { 128 | try_intermediate_seg = true; 129 | cmd.arguments().pop_front(); 130 | bool convert = false; 131 | 132 | parameters.reg_strength2 = cmd.arguments().takeFirst().toFloat(&convert); 133 | if ((!convert) & (parameters.reg_strength2 <= 0.0)) 134 | { 135 | return cmd.error(QObject::tr("Invalid parameter: value after \"-%1\"").arg(COMMAND_LAMBDA2)); 136 | } 137 | cmd.print(QString("lambda2 (Regularization strength for intermediate segmentation) set: %1").arg(parameters.reg_strength2)); 138 | } 139 | else if (ccCommandLineInterface::IsCommand(ARGUMENT, COMMAND_K2)) 140 | { 141 | try_intermediate_seg = true; 142 | cmd.arguments().pop_front(); 143 | bool convert = false; 144 | 145 | parameters.min_nn2 = cmd.arguments().takeFirst().toInt(&convert); 146 | if ((!convert) & (parameters.min_nn2 < 3)) 147 | { 148 | return cmd.error(QObject::tr("Invalid parameter: value after \"-%1\"").arg(COMMAND_K2)); 149 | } 150 | cmd.print(QString("K2 (Nearest neighbors to search for intermediate segmentation) set: %1").arg(parameters.min_nn2)); 151 | } 152 | else if (ccCommandLineInterface::IsCommand(ARGUMENT, COMMAND_MAX_GAP)) 153 | { 154 | try_intermediate_seg = true; 155 | cmd.arguments().pop_front(); 156 | bool convert = false; 157 | 158 | parameters.max_gap = cmd.arguments().takeFirst().toFloat(&convert); 159 | if ((!convert) & (parameters.max_gap <= 0.0001)) 160 | { 161 | return cmd.error(QObject::tr("Invalid parameter: value after \"-%1\"").arg(COMMAND_MAX_GAP)); 162 | } 163 | cmd.print(QString("Maximum point gap (in m) for intermediate segmentation set: %1").arg(parameters.max_gap)); 164 | } 165 | else if (ccCommandLineInterface::IsCommand(ARGUMENT, COMMAND_DECIMATE_RESOLUTION2)) 166 | { 167 | try_intermediate_seg = true; 168 | cmd.arguments().pop_front(); 169 | bool convert = false; 170 | 171 | parameters.decimate_res2 = cmd.arguments().takeFirst().toFloat(&convert); 172 | if ((!convert) & (parameters.decimate_res2 < 0.001)) 173 | { 174 | return cmd.error(QObject::tr("Invalid parameter: value after \"-%1\"").arg(COMMAND_DECIMATE_RESOLUTION2)); 175 | } 176 | cmd.print(QString("Decimated resolution (in m) for intermediate segmentation set: %1").arg(parameters.decimate_res2)); 177 | } 178 | else if (ccCommandLineInterface::IsCommand(ARGUMENT, COMMAND_RHO)) 179 | { 180 | try_final_seg = true; 181 | cmd.arguments().pop_front(); 182 | bool convert = false; 183 | 184 | parameters.rel_height_length_ratio = cmd.arguments().takeFirst().toFloat(&convert); 185 | if ((!convert) & (parameters.rel_height_length_ratio < 0.001)) 186 | { 187 | return cmd.error(QObject::tr("Invalid parameter: value after \"-%1\"").arg(COMMAND_RHO)); 188 | } 189 | cmd.print(QString("Relative height to length ratio (used to detect non-stems for final segmentation) set: %1").arg(parameters.rel_height_length_ratio)); 190 | 191 | } 192 | else if (ccCommandLineInterface::IsCommand(ARGUMENT, COMMAND_VERTICAL_OVERLAP_WEIGHT)) 193 | { 194 | try_final_seg = true; 195 | cmd.arguments().pop_front(); 196 | bool convert = false; 197 | 198 | parameters.vertical_weight = cmd.arguments().takeFirst().toFloat(&convert); 199 | if ((!convert) & (parameters.vertical_weight < 0.001)) 200 | { 201 | return cmd.error(QObject::tr("Invalid parameter: value after \"-%1\"").arg(COMMAND_VERTICAL_OVERLAP_WEIGHT)); 202 | } 203 | cmd.print(QString("Vertical overlapping ratio weight for final segmentation set: %1").arg(parameters.vertical_weight)); 204 | } 205 | else 206 | { 207 | cmd.print("Parameters All Set"); 208 | break; 209 | } 210 | } 211 | 212 | for (CLCloudDesc& desc : cmd.clouds()) 213 | { 214 | //Convert CC point cloud to treeIso type 215 | unsigned count = desc.pc->size(); 216 | if (count == 0) 217 | { 218 | cmd.print(QString("Cloud %1 is empty").arg(desc.pc->getName())); 219 | continue; 220 | } 221 | 222 | if (try_init_seg) 223 | { 224 | if (!TreeIso::Init_seg_pcd(desc.pc, parameters.min_nn1, parameters.reg_strength1, parameters.decimate_res1, parameters.threads1, [](int) {/*No implementation for progress bar*/})) 225 | { 226 | return cmd.error("Failed to finish initial segmentation due to unknown reasons."); 227 | } 228 | } 229 | if (try_intermediate_seg) 230 | { 231 | if (!TreeIso::Intermediate_seg_pcd(desc.pc, parameters.min_nn2, parameters.reg_strength2, parameters.decimate_res2, parameters.max_gap, parameters.threads2, [](int) {/*No implementation for progress bar*/})) 232 | { 233 | return cmd.error("Failed to finish intermediate segmentation due to unknown reasons."); 234 | } 235 | } 236 | if (try_final_seg) 237 | { 238 | if (!TreeIso::Final_seg_pcd(desc.pc, parameters.min_nn2, parameters.rel_height_length_ratio, parameters.vertical_weight, [](int) {/*No implementation for progress bar*/})) 239 | { 240 | return cmd.error("Failed to finish final segmentation due to unknown reasons."); 241 | } 242 | } 243 | } 244 | 245 | return true; 246 | } 247 | }; 248 | 249 | -------------------------------------------------------------------------------- /info.json: -------------------------------------------------------------------------------- 1 | { 2 | "type" : "Standard", 3 | "name" : "TreeIso", 4 | "icon" : ":/CC/plugin/qTreeIso/images/forest.png", 5 | "description": "A 3D graph-based individual-tree isolator (treeiso) from Terrestrial Laser Scanning point clouds", 6 | "authors" : [ 7 | { 8 | "name" : "Zhouxin Xi" 9 | }, 10 | { 11 | "name" : "Chris Hopkinson" 12 | } 13 | ], 14 | "maintainers" : [ 15 | { 16 | "name" : "Zhouxin Xi" 17 | } 18 | ], 19 | "references": [ 20 | { 21 | "text": "3D Graph-Based Individual-Tree Isolation (Treeiso) from Terrestrial Laser Scanning Point Clouds.", 22 | "url": "https://www.mdpi.com/2072-4292/14/23/6116" 23 | }, 24 | { 25 | "text": "Artemis Lab, Department of Geography & Environment, University of Lethbridge", 26 | "url": "https://github.com/truebelief/artemis_treeiso" 27 | } 28 | ] 29 | } 30 | -------------------------------------------------------------------------------- /license.txt: -------------------------------------------------------------------------------- 1 | //####################################################################################### 2 | //# # 3 | //# CLOUDCOMPARE PLUGIN: qTreeIso # 4 | //# # 5 | //# This program is free software; you can redistribute it and/or modify # 6 | //# it under the terms of the GNU General Public License as published by # 7 | //# the Free Software Foundation; version 2 or later of the License. # 8 | //# # 9 | //# This program is distributed in the hope that it will be useful, # 10 | //# but WITHOUT ANY WARRANTY; without even the implied warranty of # 11 | //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # 12 | //# GNU General Public License for more details. # 13 | //# # 14 | //# Please cite the following paper if you find this tool helpful # 15 | //# # 16 | //# Xi, Z.; Hopkinson, C. 3D Graph-Based Individual-Tree Isolation (Treeiso) # 17 | //# from Terrestrial Laser Scanning Point Clouds. Remote Sens. 2022, 14, 6116. # 18 | //# https://doi.org/10.3390/rs14236116 # 19 | //# # 20 | //# Our work relies on the cut-pursuit algorithm, please also consider citing: # 21 | //# Landrieu, L.; Obozinski, G. Cut Pursuit: Fast Algorithms to Learn Piecewise # 22 | //# Constant Functions on General Weighted Graphs. SIAM J. Imaging Sci. # 23 | //# 2017, 10, 1724–1766. # 24 | //# # 25 | //# Copyright © # 26 | //# Artemis Lab, Department of Geography & Environment # 27 | //# University of Lethbridge, Canada # 28 | //# # 29 | //# # 30 | //# Zhouxin Xi and Chris Hopkinson; # 31 | //# truebelief2010@gmail.com; c.hopkinson@uleth.ca # 32 | //# # 33 | //####################################################################################### 34 | 35 | // A Matlab version shared via: 36 | // https://github.com/truebelief/artemis_treeiso 37 | 38 | // The development of the treeiso plugin was inspired by the CSF plugin originating from: 39 | // Zhang W, Qi J, Wan P, Wang H, Xie D, Wang X, Yan G. An Easy-to-Use Airborne LiDAR Data Filtering Method Based on Cloth Simulation. Remote Sensing. 2016; 8(6):501 -------------------------------------------------------------------------------- /qTreeIso.qrc: -------------------------------------------------------------------------------- 1 | 2 | 3 | images/forest.png 4 | info.json 5 | images/JP1_final_seg.png 6 | images/JP1_init_seg.png 7 | images/JP1_interim_seg.png 8 | 9 | 10 | -------------------------------------------------------------------------------- /src/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | 2 | target_sources( ${PROJECT_NAME} 3 | PRIVATE 4 | ${CMAKE_CURRENT_LIST_DIR}/ccTreeIsoDlg.cpp 5 | ${CMAKE_CURRENT_LIST_DIR}/cp_d0_dist.cpp 6 | ${CMAKE_CURRENT_LIST_DIR}/cut_pursuit.cpp 7 | ${CMAKE_CURRENT_LIST_DIR}/cut_pursuit_d0.cpp 8 | ${CMAKE_CURRENT_LIST_DIR}/maxflow.cpp 9 | ${CMAKE_CURRENT_LIST_DIR}/TreeIso.cpp 10 | ${CMAKE_CURRENT_LIST_DIR}/qTreeIso.cpp 11 | ) 12 | -------------------------------------------------------------------------------- /src/ccTreeIsoDlg.cpp: -------------------------------------------------------------------------------- 1 | //####################################################################################### 2 | //# # 3 | //# CLOUDCOMPARE PLUGIN: qTreeIso # 4 | //# # 5 | //# This program is free software; you can redistribute it and/or modify # 6 | //# it under the terms of the GNU General Public License as published by # 7 | //# the Free Software Foundation; version 2 or later of the License. # 8 | //# # 9 | //# This program is distributed in the hope that it will be useful, # 10 | //# but WITHOUT ANY WARRANTY; without even the implied warranty of # 11 | //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # 12 | //# GNU General Public License for more details. # 13 | //# # 14 | //# Please cite the following paper if you find this tool helpful # 15 | //# # 16 | //# Xi, Z.; Hopkinson, C. 3D Graph-Based Individual-Tree Isolation (Treeiso) # 17 | //# from Terrestrial Laser Scanning Point Clouds. Remote Sens. 2022, 14, 6116. # 18 | //# https://doi.org/10.3390/rs14236116 # 19 | //# # 20 | //# Our work relies on the cut-pursuit algorithm, please also consider citing: # 21 | //# Landrieu, L.; Obozinski, G. Cut Pursuit: Fast Algorithms to Learn Piecewise # 22 | //# Constant Functions on General Weighted Graphs. SIAM J. Imaging Sci. # 23 | //# 2017, 10, 1724–1766. # 24 | //# # 25 | //# Copyright © # 26 | //# Artemis Lab, Department of Geography & Environment # 27 | //# University of Lethbridge, Canada # 28 | //# # 29 | //# # 30 | //# Zhouxin Xi and Chris Hopkinson; # 31 | //# truebelief2010@gmail.com; c.hopkinson@uleth.ca # 32 | //# # 33 | //####################################################################################### 34 | 35 | 36 | #pragma once 37 | // A Matlab version shared via: 38 | // https://github.com/truebelief/artemis_treeiso 39 | 40 | #include "ccTreeIsoDlg.h" 41 | 42 | #include 43 | #include 44 | 45 | 46 | ccTreeIsoDlg::ccTreeIsoDlg(QWidget* parent) : QDialog(parent), Ui::TreeIsoDialog() 47 | { 48 | setupUi(this); 49 | setWindowFlags(Qt::Tool/*Qt::Dialog | Qt::WindowStaysOnTopHint*/); 50 | } 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /src/cp_d0_dist.cpp: -------------------------------------------------------------------------------- 1 | /*============================================================================= 2 | * Hugo Raguet 2018, 2022, 2023 3 | *===========================================================================*/ 4 | #include "cp_d0_dist.hpp" 5 | 6 | #define VERT_WEIGHTS_(v) (vert_weights ? vert_weights[(v)] : (real_t) 1.0) 7 | #define COOR_WEIGHTS_(d) (coor_weights ? coor_weights[(d)] : (real_t) 1.0) 8 | 9 | #define TPL template 10 | #define CP_D0_DIST Cp_d0_dist 11 | 12 | using namespace std; 13 | 14 | TPL CP_D0_DIST::Cp_d0_dist(index_t V, index_t E, const index_t* first_edge, 15 | const index_t* adj_vertices, const real_t* Y, size_t D) 16 | : Cp_d0(V, E, first_edge, adj_vertices, D), Y(Y) 17 | { 18 | vert_weights = coor_weights = nullptr; 19 | comp_weights = nullptr; 20 | 21 | loss = quadratic_loss(); 22 | fYY = 0.0; 23 | fXY = real_inf(); 24 | 25 | min_comp_weight = 0.0; 26 | } 27 | 28 | TPL CP_D0_DIST::~Cp_d0_dist(){ free(comp_weights); } 29 | 30 | TPL real_t CP_D0_DIST::distance(const real_t* Yv, const real_t* Xv) const 31 | { 32 | real_t dist = 0.0; 33 | size_t Q = loss; // number of coordinates for quadratic part 34 | if (Q != 0){ /* quadratic part */ 35 | for (size_t d = 0; d < Q; d++){ 36 | dist += COOR_WEIGHTS_(d)*(Yv[d] - Xv[d])*(Yv[d] - Xv[d]); 37 | } 38 | } 39 | if (Q != D){ /* smoothed Kullback-Leibler; 40 | just compute cross-entropy here */ 41 | real_t distKL = 0.0; 42 | const real_t s = loss < 1.0 ? loss : eps; 43 | const real_t c = 1.0 - s; 44 | const real_t u = s/(D - Q); 45 | for (size_t d = Q; d < D; d++){ 46 | distKL -= (u + c*Yv[d])*log(u + c*Xv[d]); 47 | } 48 | dist += COOR_WEIGHTS_(Q)*distKL; 49 | } 50 | return dist; 51 | } 52 | 53 | TPL void CP_D0_DIST::set_loss(real_t loss, const real_t* Y, 54 | const real_t* vert_weights, const real_t* coor_weights) 55 | { 56 | if (loss < 0.0 || (loss > 1.0 && ((size_t) loss) != loss) || loss > D){ 57 | cerr << "Cut-pursuit d0 distance: loss parameter should be positive," 58 | "either in (0,1) or an integer that do not exceed the dimension " 59 | "(" << loss << " given)." << endl; 60 | exit(EXIT_FAILURE); 61 | } 62 | if (loss == 0.0){ loss = eps; } // avoid singularities 63 | this->loss = loss; 64 | if (Y){ this->Y = Y; } 65 | this->vert_weights = vert_weights; 66 | if (0.0 < loss && loss < 1.0 && coor_weights){ 67 | cerr << "Cut-pursuit d0 distance: no sense in weighting coordinates of" 68 | " the probability space in Kullback-Leibler divergence." << endl; 69 | exit(EXIT_FAILURE); 70 | } 71 | this->coor_weights = coor_weights; 72 | if (loss == quadratic_loss()){ fYY = 0.0; return; } 73 | /* recompute the constant dist(Y, Y) for Kullback-Leibler */ 74 | const size_t Q = loss; // number of coordinates for quadratic part 75 | const real_t s = loss < 1.0 ? loss : eps; 76 | const real_t c = 1.0 - s; 77 | const real_t u = s/(D - Q); 78 | real_t fYY_par = 0.0; // auxiliary variable for parallel region 79 | for (index_t v = 0; v < V; v++){ 80 | const real_t* Yv = Y + D*v; 81 | real_t H_Yv = 0.0; 82 | for (size_t d = Q; d < D; d++){ 83 | H_Yv -= (u + c*Yv[d])*log(u + c*Yv[d]); 84 | } 85 | fYY_par += VERT_WEIGHTS_(v)*H_Yv; 86 | } 87 | fYY = fYY_par; 88 | } 89 | 90 | TPL void CP_D0_DIST::set_split_param(index_t max_split_size, comp_t K, 91 | int split_iter_num, real_t split_damp_ratio, int split_values_init_num, 92 | int split_values_iter_num) 93 | { 94 | Cp::set_split_param(max_split_size, K, 95 | split_iter_num, split_damp_ratio, split_values_init_num, 96 | split_values_iter_num); 97 | } 98 | 99 | TPL void CP_D0_DIST::set_min_comp_weight(real_t min_comp_weight) 100 | { 101 | if (min_comp_weight < 0.0){ 102 | cerr << "Cut-pursuit d0 distance: min component weight parameter " 103 | "should be positive (" << min_comp_weight << " given)." << endl; 104 | exit(EXIT_FAILURE); 105 | } 106 | this->min_comp_weight = min_comp_weight; 107 | } 108 | 109 | TPL real_t CP_D0_DIST::fv(index_t v, const real_t* Xv) const 110 | { return VERT_WEIGHTS_(v)*distance(Y + D*v, Xv); } 111 | 112 | TPL real_t CP_D0_DIST::compute_f() const 113 | { 114 | return fXY == real_inf() ? 115 | Cp_d0::compute_f() - fYY : fXY - fYY; 116 | } 117 | 118 | TPL void CP_D0_DIST::solve_reduced_problem() 119 | { 120 | free(comp_weights); 121 | comp_weights = (real_t*) malloc_check(sizeof(real_t)*rV); 122 | 123 | for (comp_t rv = 0; rv < rV; rv++){ 124 | real_t* rXv = rX + D*rv; 125 | comp_weights[rv] = 0.0; 126 | for (size_t d = 0; d < D; d++){ rXv[d] = 0.0; } 127 | for (index_t i = first_vertex[rv]; i < first_vertex[rv + 1]; i++){ 128 | index_t v = comp_list[i]; 129 | comp_weights[rv] += VERT_WEIGHTS_(v); 130 | const real_t* Yv = Y + D*v; 131 | for (size_t d = 0; d < D; d++){ rXv[d] += VERT_WEIGHTS_(v)*Yv[d]; } 132 | } 133 | if (comp_weights[rv] <= 0.0){ 134 | cerr << "Cut-pursuit d0 distance: nonpositive total component " 135 | "weight; something went wrong." << endl; 136 | exit(EXIT_FAILURE); 137 | } 138 | for (size_t d = 0; d < D; d++){ rXv[d] /= comp_weights[rv]; } 139 | } 140 | } 141 | 142 | TPL void CP_D0_DIST::set_split_value(Split_info& split_info, comp_t k, 143 | index_t v) const 144 | { 145 | const real_t* Yv = Y + D*v; 146 | real_t* sXk = split_info.sX + D*k; 147 | for (size_t d = 0; d < D; d++){ sXk[d] = Yv[d]; } 148 | } 149 | 150 | TPL void CP_D0_DIST::update_split_info(Split_info& split_info) const 151 | { 152 | comp_t rv = split_info.rv; 153 | real_t* sX = split_info.sX; 154 | real_t* total_weights = (real_t*) 155 | malloc_check(sizeof(real_t)*split_info.K); 156 | for (comp_t k = 0; k < split_info.K; k++){ 157 | total_weights[k] = 0.0; 158 | real_t* sXk = sX + D*k; 159 | for (size_t d = 0; d < D; d++){ sXk[d] = 0.0; } 160 | } 161 | for (index_t i = first_vertex[rv]; i < first_vertex[rv + 1]; i++){ 162 | index_t v = comp_list[i]; 163 | comp_t k = label_assign[v]; 164 | total_weights[k] += VERT_WEIGHTS_(v); 165 | const real_t* Yv = Y + D*v; 166 | real_t* sXk = sX + D*k; 167 | for (size_t d = 0; d < D; d++){ sXk[d] += VERT_WEIGHTS_(v)*Yv[d]; } 168 | } 169 | comp_t kk = 0; // actual number of alternatives kept 170 | for (comp_t k = 0; k < split_info.K; k++){ 171 | const real_t* sXk = sX + D*k; 172 | real_t* sXkk = sX + D*kk; 173 | if (total_weights[k]){ 174 | for (size_t d = 0; d < D; d++){ 175 | sXkk[d] = sXk[d]/total_weights[k]; 176 | } 177 | kk++; 178 | } // else no vertex assigned to k, discard this alternative 179 | } 180 | split_info.K = kk; 181 | free(total_weights); 182 | } 183 | 184 | TPL void CP_D0_DIST::compute_merge_candidate(index_t re) 185 | { 186 | comp_t ru = reduced_edges_u(re); 187 | comp_t rv = reduced_edges_v(re); 188 | real_t edge_weight = reduced_edge_weights[re]; 189 | 190 | real_t* rXu = rX + D*ru; 191 | real_t* rXv = rX + D*rv; 192 | real_t wru = comp_weights[ru]/(comp_weights[ru] + comp_weights[rv]); 193 | real_t wrv = comp_weights[rv]/(comp_weights[ru] + comp_weights[rv]); 194 | 195 | real_t gain = edge_weight; 196 | size_t Q = loss; // number of coordinates for quadratic part 197 | 198 | if (Q != 0){ 199 | /* quadratic gain */ 200 | real_t gainQ = 0.0; 201 | for (size_t d = 0; d < Q; d++){ 202 | gainQ -= COOR_WEIGHTS_(d)*(rXu[d] - rXv[d])*(rXu[d] - rXv[d]); 203 | } 204 | gain += comp_weights[ru]*wrv*gainQ; 205 | } 206 | 207 | if (gain > 0.0 || comp_weights[ru] < min_comp_weight 208 | || comp_weights[rv] < min_comp_weight){ 209 | if (!merge_values[re]){ 210 | merge_values[re] = (real_t*) malloc_check(sizeof(real_t)*D); 211 | } 212 | real_t* value = merge_values[re]; 213 | for (size_t d = 0; d < D; d++){ value[d] = wru*rXu[d] + wrv*rXv[d]; } 214 | 215 | if (Q != D){ 216 | /* smoothed Kullback-Leibler gain */ 217 | real_t gainKLu = 0.0, gainKLv = 0.0; 218 | const real_t s = loss < 1.0 ? loss : eps; 219 | const real_t c = 1.0 - s; 220 | const real_t u = s/(D - Q); 221 | for (size_t d = Q; d < D; d++){ 222 | real_t u_value_d = u + c*value[d]; 223 | real_t u_rXu_d = u + c*rXu[d]; 224 | real_t u_rXv_d = u + c*rXv[d]; 225 | gainKLu -= (u_rXu_d)*log(u_rXu_d/u_value_d); 226 | gainKLv -= (u_rXv_d)*log(u_rXv_d/u_value_d); 227 | } 228 | gain += COOR_WEIGHTS_(Q)* 229 | (comp_weights[ru]*gainKLu + comp_weights[rv]*gainKLv); 230 | } 231 | } 232 | 233 | merge_gains[re] = gain; 234 | if (gain <= 0.0 && comp_weights[ru] >= min_comp_weight 235 | && comp_weights[rv] >= min_comp_weight){ 236 | delete_merge_candidate(re); 237 | } 238 | } 239 | 240 | TPL size_t CP_D0_DIST::merge_info_complexity() const 241 | { return 2*D; } 242 | 243 | TPL comp_t CP_D0_DIST::accept_merge_candidate(index_t re) 244 | { 245 | comp_t ro = Cp_d0::accept_merge_candidate(re); 246 | comp_t ru = reduced_edges_u(re); 247 | comp_t rv = reduced_edges_v(re); 248 | if (ro != ru){ rv = ru; ru = ro; } 249 | comp_weights[ru] += comp_weights[rv]; 250 | return ru; 251 | } 252 | 253 | TPL index_t CP_D0_DIST::merge() 254 | { 255 | index_t deactivation = Cp_d0::merge(); 256 | free(comp_weights); comp_weights = nullptr; 257 | /* fXY can be updated now to avoid computing it twice later */ 258 | if (monitor_evolution()){ 259 | fXY = Cp_d0::compute_f(); 260 | } 261 | return deactivation; 262 | } 263 | 264 | TPL real_t CP_D0_DIST::compute_evolution() const 265 | { 266 | real_t dif = 0.0; 267 | for (comp_t rv = 0; rv < rV; rv++){ 268 | if (is_saturated[rv]){ continue; } 269 | const real_t* rXv = rX + D*rv; 270 | real_t distXX = 0.0; 271 | if (loss != quadratic_loss()){ 272 | const size_t Q = loss; // number of coordinates for quadratic part 273 | const real_t s = loss < 1.0 ? loss : eps; 274 | const real_t c = 1.0 - s; 275 | const real_t u = s/(D - Q); 276 | for (size_t d = Q; d < D; d++){ 277 | distXX -= (u + c*rXv[d])*log(u + c*rXv[d]); 278 | } 279 | distXX *= COOR_WEIGHTS_(Q); 280 | } 281 | for (index_t i = first_vertex[rv]; i < first_vertex[rv + 1]; i++){ 282 | index_t v = comp_list[i]; 283 | const real_t* lrXv = last_rX + D*last_comp_assign[v]; 284 | dif += VERT_WEIGHTS_(v)*(distance(rXv, lrXv) - distXX); 285 | } 286 | } 287 | real_t amp = compute_f(); 288 | return amp > eps ? dif/amp : dif/eps; 289 | } 290 | 291 | template class Cp_d0_dist; 292 | template class Cp_d0_dist; 293 | template class Cp_d0_dist; 294 | template class Cp_d0_dist; 295 | -------------------------------------------------------------------------------- /src/cut_pursuit_d0.cpp: -------------------------------------------------------------------------------- 1 | /*============================================================================= 2 | * Hugo Raguet 2019 3 | *===========================================================================*/ 4 | #include "cut_pursuit_d0.hpp" 5 | #include 6 | #include 7 | 8 | #define EDGE_WEIGHTS_(e) (edge_weights ? edge_weights[(e)] : homo_edge_weight) 9 | 10 | #define TPL template 12 | #define CP_D0 Cp_d0 13 | 14 | using namespace std; 15 | 16 | TPL CP_D0::Cp_d0(index_t V, index_t E, const index_t* first_edge, 17 | const index_t* adj_vertices, size_t D) 18 | : Cp(V, E, first_edge, adj_vertices, D) 19 | { 20 | K = 2; 21 | split_iter_num = 2; 22 | split_damp_ratio = 1.0; 23 | split_values_init_num = 3; 24 | split_values_iter_num = 3; 25 | merge_gains = nullptr; 26 | merge_values = nullptr; 27 | } 28 | 29 | TPL real_t CP_D0::compute_graph_d0() const 30 | { 31 | real_t weighted_contour_length = 0.0; 32 | 33 | for (index_t re = 0; re < rE; re++){ 34 | weighted_contour_length += reduced_edge_weights[re]; 35 | } 36 | return weighted_contour_length; 37 | } 38 | 39 | TPL real_t CP_D0::compute_f() const 40 | { 41 | real_t f = 0.0; 42 | for (comp_t rv = 0; rv < rV; rv++){ 43 | real_t* rXv = rX + D*rv; 44 | for (index_t i = first_vertex[rv]; i < first_vertex[rv + 1]; i++){ 45 | f += fv(comp_list[i], rXv); 46 | } 47 | } 48 | return f; 49 | } 50 | 51 | TPL real_t CP_D0::compute_objective() const 52 | { return compute_f() + compute_graph_d0(); } // f(x) + ||x||_d0 53 | 54 | TPL real_t CP_D0::vert_split_cost(const Split_info& split_info, index_t v, 55 | comp_t k) const 56 | { return fv(v, split_info.sX + D*k); } 57 | 58 | /* compute binary cost of choosing alternatives lu and lv at edge e */ 59 | TPL real_t CP_D0::edge_split_cost(const Split_info& split_info, index_t e, 60 | comp_t lu, comp_t lv) const 61 | { return lu == lv ? 0.0 : EDGE_WEIGHTS_(e); } 62 | 63 | TPL comp_t CP_D0::accept_merge_candidate(index_t re) 64 | { 65 | comp_t ru = reduced_edges_u(re); 66 | comp_t rv = reduced_edges_v(re); 67 | ru = merge_components(ru, rv); 68 | value_t* rXu = rX + D*ru; 69 | for (size_t d = 0; d < D; d++){ rXu[d] = merge_values[re][d]; } 70 | delete_merge_candidate(re); 71 | return ru; 72 | } 73 | 74 | TPL void CP_D0::delete_merge_candidate(index_t re) 75 | { free(merge_values[re]); merge_values[re] = nullptr; } 76 | 77 | TPL comp_t CP_D0::compute_merge_chains() 78 | { 79 | comp_t merge_count = 0; 80 | 81 | /* compute merge candidates in parallel */ 82 | merge_gains = (real_t*) malloc_check(sizeof(real_t)*rE); 83 | merge_values = (value_t**) malloc_check(sizeof(value_t*)*rE); 84 | for (index_t re = 0; re < rE; re++){ merge_values[re] = nullptr; } 85 | index_t num_pos_candidates = 0, num_neg_candidates = 0; 86 | for (index_t re = 0; re < rE; re++){ 87 | comp_t ru = reduced_edges_u(re); 88 | comp_t rv = reduced_edges_v(re); 89 | if (ru == rv){ continue; } 90 | compute_merge_candidate(re); 91 | if (merge_values[re]){ 92 | if (merge_gains[re] > 0.0){ num_pos_candidates++; } 93 | else{ num_neg_candidates++; } 94 | } 95 | } 96 | 97 | if (!(num_pos_candidates || num_neg_candidates)){ 98 | free(merge_gains); free(merge_values); 99 | return 0; 100 | } 101 | 102 | /* local read-only access to merge_gains; useful for lambdas below, 103 | * since one cannot directly capture member variables */ 104 | const real_t* _merge_gains = merge_gains; 105 | 106 | if (num_pos_candidates){ 107 | /** merge candidates with positive gains; 108 | ** these are important enough to be merged in decreasing gain order, and 109 | ** to update surrounding merge candidates after each merge: 110 | ** 1) maintain candidates in a priority order on the gain 111 | ** 2) maintain access to all reduced edges involving a given vertex, and 112 | ** to their potential corresponding candidate in the priority order; 113 | ** because of 2), the best choice for 1) is a binary search tree **/ 114 | 115 | /* 1) binary search tree on the gain */ 116 | auto compare_candidates = [_merge_gains] (index_t mc1, index_t mc2) -> bool 117 | { return _merge_gains[mc1] > _merge_gains[mc2] || 118 | /* ensure unique identification of merge candidates */ 119 | (_merge_gains[mc1] == _merge_gains[mc2] && mc1 < mc2); }; 120 | set 121 | candidates_queue(compare_candidates); 122 | for (index_t re = 0; re < rE; re++){ 123 | if (merge_values[re] && merge_gains[re] > 0.0){ 124 | candidates_queue.insert(re); 125 | } 126 | } 127 | 128 | /* 2) linked list structure for updating reduced graph while merging */ 129 | /* - given a component, we need access to the list of merge candidates 130 | * whose corresponding reduced edge involves the considered component; 131 | * - to that purpose, we maintain for each component a linked list of such 132 | * merge candidates; we call "merge candidate cell" the data structure with 133 | * the merge candidate identifier and the access to the next cell in such a 134 | * linked list; 135 | * - each active merge candidates is thus referenced in two such cells: one 136 | * within both lists of starting and ending components of the corresponding 137 | * reduced edge; 138 | * - one can thus compact information mapping unequivocally each merge 139 | * candidate mc to merge candidate cells identifiers 2*mc and 2*mc + 1; 140 | * conversely, the merge candidate of a cell mcc is mcc/2 141 | * - the link list structure can thus be maintained with the following 142 | * tables: 143 | * first_candidate_cell[ru] is the index of the first merge candidate 144 | * cell of the list of adjacent candidates for component ru 145 | * next_candidate_cell[mcc] is the index of the merge candidate cell 146 | * that comes after mcc within the list containing it 147 | */ 148 | typedef size_t Cell_id; 149 | #define EMPTY_CELL (std::numeric_limits::max()) 150 | Cell_id* first_candidate_cell = (Cell_id*) 151 | malloc_check(sizeof(Cell_id*)*rV); 152 | Cell_id* next_candidate_cell = (Cell_id*) 153 | malloc_check(sizeof(Cell_id*)*2*rE); 154 | for (comp_t rv = 0; rv < rV; rv++){ 155 | first_candidate_cell[rv] = EMPTY_CELL; 156 | } 157 | for (Cell_id mcc = 0; mcc < ((Cell_id) 2)*rE; mcc++){ 158 | next_candidate_cell[mcc] = EMPTY_CELL; 159 | } 160 | #define GET_REDUCED_EDGE(mcc) (*mcc/2) 161 | #define FIRST_CELL(mcc, rv) (mcc = &first_candidate_cell[rv]) 162 | #define NEXT_CELL(mcc) (mcc = &next_candidate_cell[*mcc]) 163 | #define DELETE_CELL(mcc) (*mcc = next_candidate_cell[*mcc]) 164 | #define IS_EMPTY(mcc) (*mcc == EMPTY_CELL) 165 | 166 | /* construct the linked list structure; 167 | * last_candidate_cell[ru] is the index of the last merge candidate cell 168 | * of the list of adjacent candidates for component ru; 169 | * useful only for constructing the list in linear time */ 170 | Cell_id* last_candidate_cell = (Cell_id*) 171 | malloc_check(sizeof(index_t*)*rV); 172 | for (comp_t rv = 0; rv < rV; rv++){ last_candidate_cell[rv] = EMPTY_CELL; } 173 | for (index_t re = 0; re < rE; re++){ 174 | comp_t ru = reduced_edges_u(re); 175 | comp_t rv = reduced_edges_v(re); 176 | if (ru == rv){ continue; } 177 | #define INSERT_CELL(rv, mcc) \ 178 | if (last_candidate_cell[rv] == EMPTY_CELL){ \ 179 | first_candidate_cell[rv] = mcc; \ 180 | last_candidate_cell[rv] = mcc; \ 181 | }else{ \ 182 | next_candidate_cell[last_candidate_cell[rv]] = mcc; \ 183 | last_candidate_cell[rv] = mcc; \ 184 | } 185 | Cell_id mcc_ru = ((Cell_id) 2)*re, mcc_rv = ((Cell_id) 2)*re + 1; 186 | INSERT_CELL(ru, mcc_ru); INSERT_CELL(rv, mcc_rv); 187 | } 188 | free(last_candidate_cell); 189 | 190 | /* iterative merge following the above order */ 191 | while (!candidates_queue.empty()){ 192 | typename set::iterator candidate = candidates_queue.begin(); 193 | index_t re = *candidate; 194 | comp_t ru = reduced_edges_u(re); 195 | comp_t rv = reduced_edges_v(re); 196 | 197 | /** accept the merge and remove from the queue **/ 198 | comp_t ro = accept_merge_candidate(re); // merge ru and rv 199 | if (ro != ru){ rv = ru; ru = ro; } // makes sure ru is the root 200 | candidates_queue.erase(candidate); 201 | merge_count++; 202 | 203 | /** update reduced graph structure and adjacent merge candidates **/ 204 | Cell_id *mcc_ru, *mcc_rv; 205 | 206 | /* first pass on the list of rv: cleanup deleted candidates, remove 207 | * current merging candidate, update vertices by replacing rv by ru */ 208 | FIRST_CELL(mcc_rv, rv); 209 | while (!IS_EMPTY(mcc_rv)){ 210 | index_t re_rv = GET_REDUCED_EDGE(mcc_rv); 211 | if (!reduced_edge_weights[re_rv]){ DELETE_CELL(mcc_rv); continue; } 212 | comp_t end_re_rv; 213 | if (reduced_edges_u(re_rv) == rv){ 214 | reduced_edges_u(re_rv) = ru; 215 | end_re_rv = reduced_edges_v(re_rv); 216 | }else{ 217 | reduced_edges_v(re_rv) = ru; 218 | end_re_rv = reduced_edges_u(re_rv); 219 | } 220 | if (end_re_rv == ru){ DELETE_CELL(mcc_rv); continue; } 221 | NEXT_CELL(mcc_rv); 222 | } 223 | 224 | /* cleanup deleted candidates and delete current merging candidate from 225 | * ru list, and search candidates adjacent to both ru and rv with same 226 | * end vertex; 227 | * NOTA: bilinear time cost in orders of merging components cannot be 228 | * avoided; in particular, ordering lists by end vertex identifiers 229 | * would require reordering of all adjacent candidates of rv, bilinear 230 | * in order of rv and sum of orders of its adjacent candidates 231 | * NOTA: might be done in parallel along ru list, but current merging 232 | * candidate must be removed before, and might not be worth it */ 233 | FIRST_CELL(mcc_ru, ru); 234 | while (!IS_EMPTY(mcc_ru)){ 235 | index_t re_ru = GET_REDUCED_EDGE(mcc_ru); 236 | if (!reduced_edge_weights[re_ru]){ DELETE_CELL(mcc_ru); continue; } 237 | comp_t end_re_ru = reduced_edges_u(re_ru) == ru ? 238 | reduced_edges_v(re_ru) : reduced_edges_u(re_ru); 239 | if (end_re_ru == ru){ DELETE_CELL(mcc_ru); continue; } 240 | for (FIRST_CELL(mcc_rv, rv); !IS_EMPTY(mcc_rv); NEXT_CELL(mcc_rv)){ 241 | index_t re_rv = GET_REDUCED_EDGE(mcc_rv); 242 | comp_t end_re_rv = reduced_edges_u(re_rv) == ru ? 243 | reduced_edges_v(re_rv) : reduced_edges_u(re_rv); 244 | if (end_re_ru == end_re_rv){ 245 | reduced_edge_weights[re_ru] += reduced_edge_weights[re_rv]; 246 | reduced_edge_weights[re_rv] = 0.0; // sum must be constant 247 | if (merge_gains[re_rv] > 0.0){ /* remove from queue */ 248 | candidate = candidates_queue.find(re_rv); 249 | candidate = candidates_queue.erase(candidate); 250 | merge_gains[re_rv] = 0.0; 251 | } 252 | delete_merge_candidate(re_rv); 253 | DELETE_CELL(mcc_rv); 254 | /* NOTA: sister candidate cell for re_rv still exists in 255 | * the list of adjacent candidates of end_re_rv; but this 256 | * situation is flagged with zero reduced edge weight */ 257 | break; 258 | } 259 | } 260 | NEXT_CELL(mcc_ru); 261 | } 262 | 263 | /* at that point, mcc_ru is the last (empty) cell of the ru list; 264 | * concatenate adjacent candidate list of rv after the one of ru */ 265 | *mcc_ru = first_candidate_cell[rv]; 266 | 267 | /* update all adjacent candidates */ 268 | for (FIRST_CELL(mcc_ru, ru); !IS_EMPTY(mcc_ru); NEXT_CELL(mcc_ru)){ 269 | index_t re = GET_REDUCED_EDGE(mcc_ru); 270 | if (merge_gains[re] > 0.0){ /* already in the queue */ 271 | candidate = candidates_queue.find(re); 272 | candidate = candidates_queue.erase(candidate); 273 | }else{ 274 | candidate = candidates_queue.end(); 275 | } 276 | compute_merge_candidate(re); 277 | if (merge_gains[re] > 0.0){ 278 | candidates_queue.insert(candidate, re); 279 | } 280 | } 281 | } // end while candidates queue not empty 282 | 283 | free(first_candidate_cell); free(next_candidate_cell); 284 | } // end if num_pos_candidates 285 | 286 | if (num_neg_candidates){ 287 | /** merge candidates with negative gains; 288 | ** these are less important, no update of adajacent candidates; 289 | ** only sort once and merge in that order **/ 290 | index_t bufsize = num_neg_candidates; 291 | index_t* neg_candidates = (index_t*) malloc_check(sizeof(index_t)*bufsize); 292 | num_neg_candidates = 0; // recounting 293 | for (index_t re = 0; re < rE; re++){ 294 | if (merge_values[re]){ 295 | if (num_neg_candidates == bufsize){ 296 | bufsize += bufsize/2 + 1; 297 | neg_candidates = (index_t*) realloc_check(neg_candidates, 298 | sizeof(index_t)*bufsize); 299 | } 300 | neg_candidates[num_neg_candidates++] = re; 301 | } 302 | } 303 | sort(neg_candidates, neg_candidates + num_neg_candidates, 304 | [_merge_gains] (index_t re1, index_t re2) -> bool 305 | { return _merge_gains[re1] > _merge_gains[re2]; }); 306 | for (index_t mc = 0; mc < num_neg_candidates; mc++){ 307 | index_t re = neg_candidates[mc]; 308 | /* ensure candidate info is up-to-date */ 309 | comp_t ru = get_merge_chain_root(reduced_edges_u(re)); 310 | comp_t rv = get_merge_chain_root(reduced_edges_v(re)); 311 | if (ru == rv){ 312 | delete_merge_candidate(re); 313 | }else{ 314 | reduced_edges_u(re) = ru; 315 | reduced_edges_v(re) = rv; 316 | compute_merge_candidate(re); 317 | if (merge_values[re]){ 318 | accept_merge_candidate(re); 319 | merge_count++; 320 | } 321 | } 322 | } 323 | 324 | free(neg_candidates); 325 | } // end if num_neg_candidates 326 | 327 | free(merge_gains); free(merge_values); 328 | return merge_count; 329 | } 330 | 331 | template class Cp_d0; 332 | template class Cp_d0; 333 | template class Cp_d0; 334 | template class Cp_d0; 335 | -------------------------------------------------------------------------------- /src/maxflow.cpp: -------------------------------------------------------------------------------- 1 | /* maxflow.cpp */ 2 | 3 | #include 4 | #include 5 | #include // for instantiation 6 | #include "maxflow.hpp" 7 | 8 | /* special constants for parent arcs */ 9 | #define TERMINAL terminal 10 | #define ORPHAN orphan 11 | /* infinite distance to the terminal */ 12 | #define INFINITE_D (std::numeric_limits::max()) 13 | 14 | #define TPL template 15 | #define MXFL Maxflow 16 | 17 | using namespace std; 18 | 19 | TPL MXFL::Maxflow(index_t node_num, index_t edge_num) 20 | : terminal(&reserved_terminal_arc), orphan(&reserved_orphan_arc), 21 | nodeptr_block(nullptr) 22 | { 23 | nodes = (node*) malloc(sizeof(node)*node_num); 24 | arcs = (arc*) malloc(sizeof(arc)*2*edge_num); 25 | if (!nodes || !arcs) { 26 | cerr << "Maxflow: not enough memory." << endl; 27 | exit(EXIT_FAILURE); 28 | } 29 | 30 | node_last = nodes + node_num; 31 | arc_last = arcs; // arcs not created yet 32 | 33 | for (node* i = nodes; i < node_last; i++){ i->first = nullptr; } 34 | } 35 | 36 | TPL MXFL::~Maxflow() 37 | { 38 | if (nodeptr_block){ 39 | delete nodeptr_block; 40 | nodeptr_block = nullptr; 41 | } 42 | free(nodes); 43 | free(arcs); 44 | } 45 | 46 | /***********************************************************************/ 47 | 48 | /* 49 | Functions for processing active list. 50 | i->next points to the next node in the list 51 | (or to i, if i is the last node in the list). 52 | If i->next is nullptr iff i is not in the list. 53 | 54 | There are two queues. Active nodes are added 55 | to the end of the second queue and read from 56 | the front of the first queue. If the first queue 57 | is empty, it is replaced by the second queue 58 | (and the second queue becomes empty). 59 | */ 60 | 61 | 62 | TPL inline void MXFL::set_active(node *i) 63 | { 64 | if (!i->next){ 65 | /* it's not in the list yet */ 66 | if (queue_last[1]) queue_last[1]->next = i; 67 | else queue_first[1] = i; 68 | queue_last[1] = i; 69 | i->next = i; 70 | } 71 | } 72 | 73 | /* 74 | Returns the next active node. 75 | If it is connected to the sink, it stays in the list, (???) 76 | otherwise it is removed from the list 77 | */ 78 | TPL inline typename MXFL::node* MXFL::next_active() 79 | { 80 | node *i; 81 | 82 | while (true){ 83 | if (!(i = queue_first[0])){ 84 | queue_first[0] = i = queue_first[1]; 85 | queue_last[0] = queue_last[1]; 86 | queue_first[1] = nullptr; 87 | queue_last[1] = nullptr; 88 | if (!i) return nullptr; 89 | } 90 | 91 | /* remove it from the active list */ 92 | if (i->next == i) queue_first[0] = queue_last[0] = nullptr; 93 | else queue_first[0] = i->next; 94 | i->next = nullptr; 95 | 96 | /* a node in the list is active iff it has a parent */ 97 | if (i->parent) return i; 98 | } 99 | } 100 | 101 | /***********************************************************************/ 102 | 103 | TPL inline void MXFL::set_orphan_front(node *i) 104 | { 105 | nodeptr *np; 106 | i->parent = ORPHAN; 107 | np = nodeptr_block->New(); 108 | np->ptr = i; 109 | np->next = orphan_first; 110 | orphan_first = np; 111 | } 112 | 113 | TPL inline void MXFL::set_orphan_rear(node *i) 114 | { 115 | nodeptr *np; 116 | i->parent = ORPHAN; 117 | np = nodeptr_block->New(); 118 | np->ptr = i; 119 | if (orphan_last) orphan_last->next = np; 120 | else orphan_first = np; 121 | orphan_last = np; 122 | np->next = nullptr; 123 | } 124 | 125 | /***********************************************************************/ 126 | 127 | TPL void MXFL::maxflow_init() 128 | { 129 | node *i; 130 | 131 | queue_first[0] = queue_last[0] = nullptr; 132 | queue_first[1] = queue_last[1] = nullptr; 133 | orphan_first = nullptr; 134 | 135 | TIME = 0; 136 | 137 | for (i = nodes; i < node_last; i++){ 138 | i->next = nullptr; 139 | i->TS = TIME; 140 | if (i->term_res_cap > 0){ 141 | /* i is connected to the source */ 142 | i->is_sink = false; 143 | i->parent = TERMINAL; 144 | set_active(i); 145 | i->DIST = 1; 146 | }else if (i->term_res_cap < 0){ 147 | /* i is connected to the sink */ 148 | i->is_sink = true; 149 | i->parent = TERMINAL; 150 | set_active(i); 151 | i->DIST = 1; 152 | }else{ 153 | i->parent = nullptr; 154 | } 155 | } 156 | } 157 | 158 | TPL void MXFL::augment(arc *middle_arc) 159 | { 160 | node *i; 161 | arc *a; 162 | flow_t bottleneck; 163 | 164 | 165 | /* 1. Finding bottleneck capacity */ 166 | /* 1a - the source tree */ 167 | bottleneck = middle_arc->res_cap; 168 | for (i = middle_arc->sister->head; ; i = a->head) 169 | { 170 | a = i->parent; 171 | if (a == TERMINAL) break; 172 | if (bottleneck > a->sister->res_cap) bottleneck = a->sister->res_cap; 173 | } 174 | if (bottleneck > i->term_res_cap) bottleneck = i->term_res_cap; 175 | /* 1b - the sink tree */ 176 | for (i = middle_arc->head; ; i = a->head) 177 | { 178 | a = i->parent; 179 | if (a == TERMINAL) break; 180 | if (bottleneck > a->res_cap) bottleneck = a->res_cap; 181 | } 182 | if (bottleneck > - i->term_res_cap) bottleneck = - i->term_res_cap; 183 | 184 | 185 | /* 2. Augmenting */ 186 | /* 2a - the source tree */ 187 | middle_arc->sister->res_cap += bottleneck; 188 | middle_arc->res_cap -= bottleneck; 189 | for (i = middle_arc->sister->head; ; i = a->head) 190 | { 191 | a = i->parent; 192 | if (a == TERMINAL) break; 193 | a->res_cap += bottleneck; 194 | a->sister->res_cap -= bottleneck; 195 | if (!a->sister->res_cap){ set_orphan_front(i); } 196 | } 197 | i->term_res_cap -= bottleneck; 198 | if (!i->term_res_cap){ set_orphan_front(i); } 199 | /* 2b - the sink tree */ 200 | for (i = middle_arc->head; ; i = a->head) 201 | { 202 | a = i->parent; 203 | if (a == TERMINAL) break; 204 | a->sister->res_cap += bottleneck; 205 | a->res_cap -= bottleneck; 206 | if (!a->res_cap){ set_orphan_front(i); } 207 | } 208 | i->term_res_cap += bottleneck; 209 | if (!i->term_res_cap){ set_orphan_front(i); } 210 | } 211 | 212 | /***********************************************************************/ 213 | 214 | TPL void MXFL::process_source_orphan(node *i) 215 | { 216 | node *j; 217 | arc *a0, *a0_min = nullptr, *a; 218 | index_t d, d_min = INFINITE_D; 219 | 220 | /* trying to find a new parent */ 221 | for (a0 = i->first; a0; a0 = a0->next) 222 | if (a0->sister->res_cap){ 223 | j = a0->head; 224 | if (!j->is_sink && (a = j->parent)){ 225 | /* checking the origin of j */ 226 | d = 0; 227 | while (true){ 228 | if (j->TS == TIME){ 229 | d += j->DIST; 230 | break; 231 | } 232 | a = j->parent; 233 | d++; 234 | if (a == TERMINAL){ 235 | j->TS = TIME; 236 | j->DIST = 1; 237 | break; 238 | } 239 | if (a == ORPHAN){ 240 | d = INFINITE_D; 241 | break; 242 | } 243 | j = a->head; 244 | } 245 | if (d < INFINITE_D){ /* j originates from the source - done */ 246 | if (d < d_min){ 247 | a0_min = a0; 248 | d_min = d; 249 | } 250 | /* set marks along the path */ 251 | for (j = a0->head; j->TS != TIME; j = j->parent->head){ 252 | j->TS = TIME; 253 | j->DIST = d--; 254 | } 255 | } 256 | } 257 | } 258 | 259 | if ((i->parent = a0_min)){ 260 | i->TS = TIME; 261 | i->DIST = d_min + 1; 262 | }else{ 263 | /* process neighbors */ 264 | for (a0 = i->first; a0; a0 = a0->next){ 265 | j = a0->head; 266 | if (!j->is_sink && (a = j->parent)){ 267 | if (a0->sister->res_cap){ set_active(j); } 268 | if (a != TERMINAL && a != ORPHAN && a->head == i){ 269 | set_orphan_rear(j); 270 | } 271 | } 272 | } 273 | } 274 | } 275 | 276 | TPL void MXFL::process_sink_orphan(node *i) 277 | { 278 | node *j; 279 | arc *a0, *a0_min = nullptr, *a; 280 | index_t d, d_min = INFINITE_D; 281 | 282 | /* trying to find a new parent */ 283 | for (a0 = i->first; a0; a0 = a0->next) 284 | if (a0->res_cap){ 285 | j = a0->head; 286 | if (j->is_sink && (a = j->parent)){ 287 | /* checking the origin of j */ 288 | d = 0; 289 | while (true){ 290 | if (j->TS == TIME){ 291 | d += j->DIST; 292 | break; 293 | } 294 | a = j->parent; 295 | d++; 296 | if (a == TERMINAL){ 297 | j->TS = TIME; 298 | j->DIST = 1; 299 | break; 300 | } 301 | if (a == ORPHAN){ 302 | d = INFINITE_D; 303 | break; 304 | } 305 | j = a->head; 306 | } 307 | if (d < INFINITE_D){ /* j originates from the sink - done */ 308 | if (d < d_min){ 309 | a0_min = a0; 310 | d_min = d; 311 | } 312 | /* set marks along the path */ 313 | for (j = a0->head; j->TS != TIME; j = j->parent->head){ 314 | j->TS = TIME; 315 | j->DIST = d--; 316 | } 317 | } 318 | } 319 | } 320 | 321 | if ((i->parent = a0_min)){ 322 | i->TS = TIME; 323 | i->DIST = d_min + 1; 324 | }else{ 325 | /* process neighbors */ 326 | for (a0 = i->first; a0; a0 = a0->next){ 327 | j = a0->head; 328 | if (j->is_sink && (a = j->parent)){ 329 | if (a0->res_cap) set_active(j); 330 | if (a != TERMINAL && a != ORPHAN && a->head == i){ 331 | set_orphan_rear(j); 332 | } 333 | } 334 | } 335 | } 336 | } 337 | 338 | /***********************************************************************/ 339 | 340 | TPL void MXFL::maxflow() 341 | { 342 | node *i, *j, *current_node = nullptr; 343 | arc *a; 344 | nodeptr *np, *np_next; 345 | 346 | if (!nodeptr_block){ 347 | nodeptr_block = new DBlock(NODEPTR_BLOCK_SIZE); 348 | } 349 | 350 | maxflow_init(); 351 | 352 | while (true){ 353 | 354 | if ((i = current_node)){ 355 | i->next = nullptr; /* remove active flag */ 356 | if (!i->parent) i = nullptr; 357 | } 358 | 359 | if (!i){ if (!(i = next_active())){ break; } } 360 | 361 | /* growth */ 362 | if (!i->is_sink){ 363 | /* grow source tree */ 364 | for (a = i->first; a; a = a->next) 365 | if (a->res_cap){ 366 | j = a->head; 367 | if (!j->parent){ 368 | j->is_sink = false; 369 | j->parent = a->sister; 370 | j->TS = i->TS; 371 | j->DIST = i->DIST + 1; 372 | set_active(j); 373 | }else if (j->is_sink){ 374 | break; 375 | }else if (j->TS <= i->TS && j->DIST > i->DIST){ 376 | /* heuristic - trying to make the distance from j to the 377 | source shorter */ 378 | j->parent = a->sister; 379 | j->TS = i->TS; 380 | j->DIST = i->DIST + 1; 381 | } 382 | } 383 | }else{ 384 | /* grow sink tree */ 385 | for (a = i->first; a; a = a->next) 386 | if (a->sister->res_cap){ 387 | j = a->head; 388 | if (!j->parent){ 389 | j->is_sink = true; 390 | j->parent = a->sister; 391 | j->TS = i->TS; 392 | j->DIST = i->DIST + 1; 393 | set_active(j); 394 | }else if (!j->is_sink){ 395 | a = a->sister; break; 396 | }else if (j->TS <= i->TS && j->DIST > i->DIST){ 397 | /* heuristic - trying to make the distance from j to the 398 | sink shorter */ 399 | j->parent = a->sister; 400 | j->TS = i->TS; 401 | j->DIST = i->DIST + 1; 402 | } 403 | } 404 | } 405 | 406 | if (++TIME <= 0){ 407 | /* changed type from long to index_t */ 408 | /* can't we prove this won't overflow? */ 409 | cerr << "Maxflow: timestamp overflow." << endl; 410 | exit(EXIT_FAILURE); 411 | } 412 | 413 | if (a){ /* found a valid path; a is the middle arc */ 414 | i->next = i; // set active flag 415 | current_node = i; 416 | 417 | augment(a); 418 | 419 | /* adoption */ 420 | while ((np = orphan_first)){ 421 | np_next = np->next; 422 | np->next = nullptr; 423 | 424 | while ((np = orphan_first)){ 425 | orphan_first = np->next; 426 | i = np->ptr; 427 | nodeptr_block->Delete(np); 428 | if (!orphan_first) orphan_last = nullptr; 429 | if (i->is_sink) process_sink_orphan(i); 430 | else process_source_orphan(i); 431 | } 432 | 433 | orphan_first = np_next; 434 | } 435 | }else{ 436 | current_node = nullptr; 437 | } 438 | 439 | } // end main loop 440 | 441 | delete nodeptr_block; 442 | nodeptr_block = nullptr; 443 | } 444 | 445 | template class Maxflow; 446 | template class Maxflow; 447 | -------------------------------------------------------------------------------- /src/qTreeIso.cpp: -------------------------------------------------------------------------------- 1 | //####################################################################################### 2 | //# # 3 | //# CLOUDCOMPARE PLUGIN: qTreeIso # 4 | //# # 5 | //# This program is free software; you can redistribute it and/or modify # 6 | //# it under the terms of the GNU General Public License as published by # 7 | //# the Free Software Foundation; version 2 or later of the License. # 8 | //# # 9 | //# This program is distributed in the hope that it will be useful, # 10 | //# but WITHOUT ANY WARRANTY; without even the implied warranty of # 11 | //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # 12 | //# GNU General Public License for more details. # 13 | //# # 14 | //# Please cite the following paper if you find this tool helpful # 15 | //# # 16 | //# Xi, Z.; Hopkinson, C. 3D Graph-Based Individual-Tree Isolation (Treeiso) # 17 | //# from Terrestrial Laser Scanning Point Clouds. Remote Sens. 2022, 14, 6116. # 18 | //# https://doi.org/10.3390/rs14236116 # 19 | //# # 20 | //# Our work relies on the cut-pursuit algorithm, please also consider citing: # 21 | //# Landrieu, L.; Obozinski, G. Cut Pursuit: Fast Algorithms to Learn Piecewise # 22 | //# Constant Functions on General Weighted Graphs. SIAM J. Imaging Sci. # 23 | //# 2017, 10, 1724–1766. # 24 | //# # 25 | //# Copyright © # 26 | //# Artemis Lab, Department of Geography & Environment # 27 | //# University of Lethbridge, Canada # 28 | //# # 29 | //# # 30 | //# Zhouxin Xi and Chris Hopkinson; # 31 | //# truebelief2010@gmail.com; c.hopkinson@uleth.ca # 32 | //# # 33 | //####################################################################################### 34 | 35 | // Matlab and python versions shared via: 36 | // https://github.com/truebelief/artemis_treeiso 37 | 38 | #include "qTreeIso.h" 39 | 40 | //Qt 41 | #include 42 | #include 43 | #include 44 | #include 45 | #include 46 | #include 47 | 48 | //Local 49 | #include "ccTreeIsoDlg.h" 50 | #include "qTreeIsoCommands.h" 51 | 52 | //System 53 | #include 54 | #include 55 | #include 56 | #include 57 | 58 | //qCC_db 59 | #include 60 | #include 61 | #include 62 | #include 63 | #include 64 | 65 | //TreeIso 66 | #include 67 | 68 | qTreeIso::qTreeIso(QObject* parent) 69 | : QObject(parent) 70 | , ccStdPluginInterface(":/CC/plugin/qTreeIso/info.json") 71 | , m_action(nullptr) 72 | { 73 | } 74 | 75 | void qTreeIso::onNewSelection(const ccHObject::Container& selectedEntities) 76 | { 77 | if (m_action) 78 | { 79 | bool hasCloud = false; 80 | for (ccHObject* entity : selectedEntities) 81 | { 82 | if (entity && entity->isA(CC_TYPES::POINT_CLOUD)) 83 | { 84 | hasCloud = true; 85 | break; 86 | } 87 | } 88 | m_action->setEnabled(hasCloud); 89 | } 90 | } 91 | 92 | QList qTreeIso::getActions() 93 | { 94 | if (!m_action) 95 | { 96 | m_action = new QAction(getName(), this); 97 | m_action->setToolTip(getDescription()); 98 | m_action->setIcon(getIcon()); 99 | 100 | //connect appropriate signal 101 | connect(m_action, &QAction::triggered, this, &qTreeIso::doAction); 102 | } 103 | 104 | return { m_action }; 105 | } 106 | 107 | void qTreeIso::doAction() 108 | { 109 | Parameters parameters; 110 | ccTreeIsoDlg treeisoDlg(m_app ? m_app->getMainWindow() : nullptr); 111 | 112 | connect(treeisoDlg.pushButtonInitSeg, &QPushButton::clicked, [&] 113 | { 114 | parameters.min_nn1 = treeisoDlg.spinBoxK1->value(); 115 | parameters.reg_strength1 = treeisoDlg.doubleSpinBoxLambda1->value();; 116 | parameters.decimate_res1 = treeisoDlg.doubleSpinBoxDecRes1->value(); 117 | parameters.threads1 = treeisoDlg.doubleSpinBoxThreads1->value(); 118 | 119 | init_segs(parameters, &treeisoDlg); 120 | }); 121 | 122 | connect(treeisoDlg.pushButtonInterSeg, &QPushButton::clicked, [&] 123 | { 124 | parameters.min_nn2 = treeisoDlg.spinBoxK2->value(); 125 | parameters.reg_strength2 = treeisoDlg.doubleSpinBoxLambda2->value(); 126 | parameters.decimate_res2 = treeisoDlg.doubleSpinBoxDecRes2->value(); 127 | parameters.max_gap = treeisoDlg.doubleSpinBoxMaxGap->value(); 128 | parameters.threads2 = treeisoDlg.doubleSpinBoxThreads2->value(); 129 | 130 | intermediate_segs(parameters, &treeisoDlg); 131 | 132 | }); 133 | 134 | connect(treeisoDlg.pushButtonReseg, &QPushButton::clicked, [&] 135 | { 136 | parameters.rel_height_length_ratio = treeisoDlg.doubleSpinBoxRelHLRatio->value(); 137 | parameters.vertical_weight = treeisoDlg.doubleSpinBoxVWeight->value(); 138 | 139 | final_segs(parameters, &treeisoDlg); 140 | }); 141 | treeisoDlg.pushButtonInitSeg->setEnabled(true); 142 | 143 | if (treeisoDlg.exec()) 144 | { 145 | if (m_app) 146 | { 147 | m_app->refreshAll(); 148 | } 149 | else 150 | { 151 | // m_app should have already been initialized by CC when plugin is loaded! 152 | assert(false); 153 | } 154 | } 155 | } 156 | 157 | void qTreeIso::init_segs(const Parameters& parameters, QWidget* parent/*=nullptr*/) 158 | { 159 | // display the progress dialog 160 | QProgressDialog* progressDlg = new QProgressDialog(parent); 161 | progressDlg->setWindowTitle("TreeIso Step 1. Initial segmentation"); 162 | progressDlg->setLabelText(tr("Computing....")); 163 | progressDlg->setCancelButton(nullptr); 164 | progressDlg->setRange(0, 100); // infinite progress bar 165 | progressDlg->show(); 166 | 167 | std::function progressCallback = [progressDlg](int percent) { 168 | progressDlg->setValue(percent); 169 | QApplication::processEvents(); // Allow UI updates 170 | }; 171 | 172 | if (!TreeIso::Init_seg(parameters.min_nn1, parameters.reg_strength1, parameters.decimate_res1, parameters.threads1, m_app, progressCallback)) 173 | { 174 | progressCallback(0); 175 | m_app->dispToConsole("Discontinued in initial segmentation.", ccMainAppInterface::ERR_CONSOLE_MESSAGE); 176 | progressDlg->close(); 177 | QApplication::processEvents(); 178 | m_app->updateUI(); 179 | m_app->refreshAll(); 180 | return; 181 | } 182 | 183 | progressDlg->close(); 184 | QApplication::processEvents(); 185 | 186 | m_app->updateUI(); 187 | m_app->refreshAll(); 188 | } 189 | 190 | void qTreeIso::intermediate_segs(const Parameters& parameters, QWidget* parent/*=nullptr*/) 191 | { 192 | // display the progress dialog 193 | QProgressDialog* progressDlg = new QProgressDialog(parent); 194 | progressDlg->setWindowTitle("TreeIso Step 2. Interim segmentation"); 195 | progressDlg->setLabelText(tr("Computing....")); 196 | progressDlg->setCancelButton(nullptr); 197 | progressDlg->setRange(0, 100); // infinite progress bar 198 | progressDlg->show(); 199 | 200 | std::function progressCallback = [progressDlg](int percent) { 201 | progressDlg->setValue(percent); 202 | QApplication::processEvents(); // Allow UI updates 203 | }; 204 | 205 | if (!TreeIso::Intermediate_seg(parameters.min_nn2, parameters.reg_strength2, parameters.decimate_res2, parameters.max_gap, parameters.threads2, m_app, progressCallback)) 206 | { 207 | progressCallback(0); 208 | m_app->dispToConsole("Error in interim segmentation!", ccMainAppInterface::ERR_CONSOLE_MESSAGE); 209 | progressDlg->close(); 210 | QApplication::processEvents(); 211 | m_app->updateUI(); 212 | m_app->refreshAll(); 213 | return; 214 | } 215 | 216 | progressDlg->hide(); 217 | QApplication::processEvents(); 218 | 219 | m_app->updateUI(); 220 | m_app->refreshAll(); 221 | } 222 | 223 | void qTreeIso::final_segs(const Parameters& parameters, QWidget* parent/*=nullptr*/) 224 | { 225 | // display the progress dialog 226 | QProgressDialog* progressDlg = new QProgressDialog(parent); 227 | progressDlg->setWindowTitle("TreeIso Step 3. Final segmentation"); 228 | progressDlg->setLabelText(tr("Computing....")); 229 | progressDlg->setCancelButton(nullptr); 230 | progressDlg->setRange(0, 100); // infinite progress bar 231 | progressDlg->show(); 232 | 233 | std::function progressCallback = [progressDlg](int percent) { 234 | progressDlg->setValue(percent); 235 | QApplication::processEvents(); // Allow UI updates 236 | }; 237 | 238 | if (!TreeIso::Final_seg(parameters.min_nn2, parameters.rel_height_length_ratio, parameters.vertical_weight, m_app, progressCallback)) 239 | { 240 | progressCallback(0); 241 | m_app->dispToConsole("Error in final segmentation!", ccMainAppInterface::ERR_CONSOLE_MESSAGE); 242 | progressDlg->close(); 243 | QApplication::processEvents(); 244 | m_app->updateUI(); 245 | m_app->refreshAll(); 246 | return; 247 | } 248 | 249 | progressDlg->close(); 250 | QApplication::processEvents(); 251 | 252 | m_app->updateUI(); 253 | m_app->refreshAll(); 254 | } 255 | 256 | void qTreeIso::registerCommands(ccCommandLineInterface* cmd) 257 | { 258 | if (!cmd) 259 | { 260 | assert(false); 261 | return; 262 | } 263 | cmd->registerCommand(ccCommandLineInterface::Command::Shared(new CommandTreeIso)); 264 | } 265 | -------------------------------------------------------------------------------- /ui/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | 2 | target_sources( ${PROJECT_NAME} 3 | PRIVATE 4 | ${CMAKE_CURRENT_LIST_DIR}/TreeIsoDlg.ui 5 | ) 6 | -------------------------------------------------------------------------------- /ui/TreeIsoDlg.ui: -------------------------------------------------------------------------------- 1 | 2 | 3 | TreeIsoDialog 4 | 5 | 6 | 7 | 0 8 | 0 9 | 392 10 | 519 11 | 12 | 13 | 14 | Individual-tree isolator (ground LiDAR) 15 | 16 | 17 | 18 | :/CC/plugin/qTreeIso/images/forest.png:/CC/plugin/qTreeIso/images/forest.png 19 | 20 | 21 | 22 | 23 | 24 | true 25 | 26 | 27 | ***Treeiso *plugin (v2)** 28 | 29 | `A graph-based tree point cloud isolator (assuming ground points have already 30 | been removed)` 31 | 32 | `Reference` 33 | 34 | `Xi, Z.; Hopkinson, C. 3D Graph-Based Individual-Tree Isolation (Treeiso) from 35 | Terrestrial Laser Scanning Point Clouds. Remote Sens. 2022, 14, 6116. 36 | https://doi.org/10.3390/rs14236116` 37 | 38 | `Landrieu, Loic, and Guillaume Obozinski. Cut pursuit: Fast algorithms to learn 39 | piecewise constant functions on general weighted graphs. SIAM Journal on 40 | Imaging Sciences. 2017, 10.4, 1724-1766.` 41 | 42 | 43 | 44 | 45 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> 46 | <html><head><meta name="qrichtext" content="1" /><meta charset="utf-8" /><style type="text/css"> 47 | p, li { white-space: pre-wrap; } 48 | hr { height: 1px; border-width: 0; } 49 | li.unchecked::marker { content: "\2610"; } 50 | li.checked::marker { content: "\2612"; } 51 | </style></head><body style=" font-family:'Segoe UI'; font-size:9pt; font-weight:400; font-style:normal;"> 52 | <p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:700; font-style:italic;">Treeiso </span><span style=" font-weight:700;">plugin (v2)</span></p> 53 | <p style=" margin-top:6px; margin-bottom:6px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Courier New';">A graph-based tree point cloud isolator (assuming ground points have already been removed)</span></p> 54 | <p style=" margin-top:6px; margin-bottom:6px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Courier New'; font-weight:700;">Reference</span></p> 55 | <p style=" margin-top:6px; margin-bottom:6px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Courier New';">Xi, Z.; Hopkinson, C. 3D Graph-Based Individual-Tree Isolation (Treeiso) from Terrestrial Laser Scanning Point Clouds. Remote Sens. 2022, 14, 6116. https://doi.org/10.3390/rs14236116</span></p> 56 | <p style=" margin-top:6px; margin-bottom:6px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Courier New';">Landrieu, Loic, and Guillaume Obozinski. Cut pursuit: Fast algorithms to learn piecewise constant functions on general weighted graphs. SIAM Journal on Imaging Sciences. 2017, 10.4, 1724-1766.</span></p></body></html> 57 | 58 | 59 | 60 | 61 | 62 | 63 | 0 64 | 65 | 66 | 67 | 68 | 0 69 | 0 70 | 71 | 72 | 73 | false 74 | 75 | 76 | Initial segmentation 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | <html><head/><body><p><span style=" font-size:10pt; font-weight:600; color:#aa0000;">1. 3D Cut-pursuit algorithm</span></p></body></html> 87 | 88 | 89 | 90 | 91 | 92 | 93 | <html><head/><body><p>This step may take a little while—please be patient. <br> It will create small clusters with natural breaks.</p></body></html> 94 | 95 | 96 | 97 | 98 | 99 | 100 | Qt::Vertical 101 | 102 | 103 | 104 | 20 105 | 40 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | <span style=" font-size:10pt; font-weight:600; color:#aa0000;">K: Nearest neighbors to search</span> 114 | 115 | 116 | 117 | 118 | 119 | 120 | 3 121 | 122 | 123 | 40 124 | 125 | 126 | 5 127 | 128 | 129 | 130 | 131 | 132 | 133 | Qt::Vertical 134 | 135 | 136 | 137 | 20 138 | 40 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | <html><head/><body><p><span style=" font-size:10pt; font-weight:600; color:#aa0000;">λ: Regularization strength</span></p></body></html> 147 | 148 | 149 | 150 | 151 | 152 | 153 | 0.000000000000000 154 | 155 | 156 | 50.000000000000000 157 | 158 | 159 | 0.050000000000000 160 | 161 | 162 | 1.000000000000000 163 | 164 | 165 | 166 | 167 | 168 | 169 | Qt::Vertical 170 | 171 | 172 | 173 | 20 174 | 40 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | <html><head/><body><p><span style=" font-size:10pt; font-weight:600; color:#aa0000;">Decimated resolution (m) to speed up</span></p></body></html> 183 | 184 | 185 | 186 | 187 | 188 | 189 | 3 190 | 191 | 192 | 0.001000000000000 193 | 194 | 195 | 0.010000000000000 196 | 197 | 198 | 0.050000000000000 199 | 200 | 201 | 202 | 203 | 204 | 205 | Qt::Vertical 206 | 207 | 208 | 209 | 20 210 | 40 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | <html><head/><body><p><span style=" font-size:10pt; font-weight:600; color:#aa0000;">Number of threads for KNN calculation </span></p></body></html> 219 | 220 | 221 | 222 | 223 | 224 | 225 | 1 226 | 227 | 228 | 229 | 230 | 231 | 232 | Execute 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | true 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | :/CC/plugin/qTreeIso/images/JP1_init_seg.png 251 | 252 | 253 | false 254 | 255 | 256 | Qt::AlignCenter 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 0 268 | 0 269 | 270 | 271 | 272 | false 273 | 274 | 275 | Interim segmentation 276 | 277 | 278 | 279 | 280 | 281 | 282 | 283 | 284 | 285 | <html><head/><body><p><span style=" font-size:10pt; font-weight:600; color:#aa0000;">2. 2D Cut-pursuit algorithm</span></p></body></html> 286 | 287 | 288 | 289 | 290 | 291 | 292 | This step merges previous clusters horizontally. 293 | 294 | 295 | 296 | 297 | 298 | 299 | Qt::Vertical 300 | 301 | 302 | 303 | 20 304 | 40 305 | 306 | 307 | 308 | 309 | 310 | 311 | 312 | <span style=" font-size:10pt; font-weight:600; color:#aa0000;">K: Nearest neighbors to search</span> 313 | 314 | 315 | 316 | 317 | 318 | 319 | 2 320 | 321 | 322 | 10 323 | 324 | 325 | 326 | 327 | 328 | 329 | Qt::Vertical 330 | 331 | 332 | 333 | 20 334 | 40 335 | 336 | 337 | 338 | 339 | 340 | 341 | 342 | <html><head/><body><p><span style=" font-size:10pt; font-weight:600; color:#aa0000;">λ: Regularization strength</span></p></body></html> 343 | 344 | 345 | 346 | 347 | 348 | 349 | 50.000000000000000 350 | 351 | 352 | 0.050000000000000 353 | 354 | 355 | 10.000000000000000 356 | 357 | 358 | 359 | 360 | 361 | 362 | Qt::Vertical 363 | 364 | 365 | 366 | 20 367 | 40 368 | 369 | 370 | 371 | 372 | 373 | 374 | 375 | <html><head/><body><p><span style=" font-size:10pt; font-weight:600; color:#aa0000;">Max gap (m)</span></p></body></html> 376 | 377 | 378 | 379 | 380 | 381 | 382 | 0.010000000000000 383 | 384 | 385 | 0.500000000000000 386 | 387 | 388 | 2.000000000000000 389 | 390 | 391 | 392 | 393 | 394 | 395 | Qt::Vertical 396 | 397 | 398 | 399 | 20 400 | 40 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | <html><head/><body><p><span style=" font-size:10pt; font-weight:600; color:#aa0000;">Decimated resolution (m) to speed up</span></p></body></html> 409 | 410 | 411 | 412 | 413 | 414 | 415 | 3 416 | 417 | 418 | 0.001000000000000 419 | 420 | 421 | 0.010000000000000 422 | 423 | 424 | 0.100000000000000 425 | 426 | 427 | 428 | 429 | 430 | 431 | Qt::Vertical 432 | 433 | 434 | 435 | 20 436 | 40 437 | 438 | 439 | 440 | 441 | 442 | 443 | 444 | <html><head/><body><p><span style=" font-size:10pt; font-weight:600; color:#aa0000;">Number of threads for KNN calculation </span></p></body></html> 445 | 446 | 447 | 448 | 449 | 450 | 451 | 1 452 | 453 | 454 | 455 | 456 | 457 | 458 | Execute 459 | 460 | 461 | 462 | 463 | 464 | 465 | 466 | 467 | true 468 | 469 | 470 | 471 | 472 | 473 | 474 | 475 | 476 | :/CC/plugin/qTreeIso/images/JP1_interim_seg.png 477 | 478 | 479 | false 480 | 481 | 482 | Qt::AlignCenter 483 | 484 | 485 | 486 | 487 | 488 | 489 | 490 | 491 | 492 | 493 | 0 494 | 0 495 | 496 | 497 | 498 | false 499 | 500 | 501 | Refined segmentation 502 | 503 | 504 | 505 | 506 | 507 | 508 | 509 | 510 | 511 | <html><head/><body><p><span style=" font-size:10pt; font-weight:600; color:#aa0000;">3. Global refinement</span></p></body></html> 512 | 513 | 514 | 515 | 516 | 517 | 518 | Final merging based on gaps and overlapping ratio. 519 | 520 | 521 | 522 | 523 | 524 | 525 | Qt::Vertical 526 | 527 | 528 | 529 | 20 530 | 40 531 | 532 | 533 | 534 | 535 | 536 | 537 | 538 | <html><head/><body><p><span style=" font-size:10pt; font-weight:600; color:#aa0000;">Vertical weight</span></p></body></html> 539 | 540 | 541 | 542 | 543 | 544 | 545 | 0.010000000000000 546 | 547 | 548 | 0.100000000000000 549 | 550 | 551 | 0.500000000000000 552 | 553 | 554 | 555 | 556 | 557 | 558 | Qt::Vertical 559 | 560 | 561 | 562 | 20 563 | 40 564 | 565 | 566 | 567 | 568 | 569 | 570 | 571 | <html><head/><body><p><span style=" font-size:10pt; font-weight:600; color:#aa0000;">Relative height length ratio</span></p></body></html> 572 | 573 | 574 | 575 | 576 | 577 | 578 | 0.010000000000000 579 | 580 | 581 | 0.100000000000000 582 | 583 | 584 | 0.500000000000000 585 | 586 | 587 | 588 | 589 | 590 | 591 | Qt::Vertical 592 | 593 | 594 | 595 | 20 596 | 40 597 | 598 | 599 | 600 | 601 | 602 | 603 | 604 | Execute 605 | 606 | 607 | 608 | 609 | 610 | 611 | 612 | 613 | true 614 | 615 | 616 | 617 | 618 | 619 | 620 | 621 | 622 | :/CC/plugin/qTreeIso/images/JP1_final_seg.png 623 | 624 | 625 | false 626 | 627 | 628 | Qt::AlignCenter 629 | 630 | 631 | 632 | 633 | 634 | 635 | 636 | 637 | 638 | 639 | 640 | 641 | 642 | Times New Roman 643 | false 644 | true 645 | 646 | 647 | 648 | Qt::Horizontal 649 | 650 | 651 | QDialogButtonBox::Ok 652 | 653 | 654 | 655 | 656 | 657 | 658 | 659 | 660 | 661 | 662 | buttonBox 663 | rejected() 664 | TreeIsoDialog 665 | reject() 666 | 667 | 668 | 316 669 | 260 670 | 671 | 672 | 286 673 | 274 674 | 675 | 676 | 677 | 678 | buttonBox 679 | accepted() 680 | TreeIsoDialog 681 | accept() 682 | 683 | 684 | 248 685 | 254 686 | 687 | 688 | 157 689 | 274 690 | 691 | 692 | 693 | 694 | 695 | --------------------------------------------------------------------------------