├── .github └── workflows │ └── main.yml ├── .gitignore ├── LICENSE ├── MANIFEST.in ├── README.md ├── environment.yml ├── example ├── PyCrown_example.ipynb ├── data │ ├── CHM.tif │ ├── DSM.tif │ ├── DTM.tif │ ├── POINTS.las │ └── POINTS.laz ├── example.py ├── step_1.jpg ├── step_2.jpg ├── step_3.jpg ├── step_4.jpg ├── step_5.jpg ├── step_6a.jpg └── step_6b.jpg ├── pycrown ├── __init__.py ├── _crown_dalponteCIRC_numba.py ├── _crown_dalponte_cython.pyx ├── _crown_dalponte_numba.py └── pycrown.py ├── requirements.txt ├── setup.py └── tests ├── __init__.py ├── base_test.py └── treetopcorrection_test.py /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: manaakiwhenua-standards 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - name : 'Checkout' 12 | uses : 'actions/checkout@v2' 13 | - name : 'manaakiwhenua-standards' 14 | uses : manaakiwhenua/manaakiwhenua-standards@v0.1.1 15 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .eggs/ 2 | *.egg-info/ 3 | result/ 4 | build/ 5 | dist/ 6 | .pytest_cache 7 | __pycache__ 8 | *.shp 9 | *.shx 10 | *.dbf 11 | *.cpg 12 | *.prj 13 | *.c 14 | *.pyd 15 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include pycrown/*.* 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![manaakiwhenua-standards](https://github.com/manaakiwhenua/pycrown/workflows/manaakiwhenua-standards/badge.svg)](https://github.com/manaakiwhenua/manaakiwhenua-standards) 2 | 3 | 4 | # PyCrown - Fast raster-based individual tree segmentation for LiDAR data 5 | Author: Dr Jan Schindler (formerly Zörner) () 6 | 7 | Published under GNU GPLv3 8 | 9 | 10 | # Summary 11 | PyCrown is a Python package for identifying tree top positions in a canopy height model (CHM) and delineating individual tree crowns. 12 | 13 | The tree top mapping and crown delineation method (optimized with Cython and Numba), uses local maxima in the canopy height model (CHM) as initial tree locations and identifies the correct tree top positions even in steep terrain by combining a raster-based tree crown delineation approach with information from the digital surface model (DSM) and terrain model (DTM). 14 | 15 | *Citation:* 16 | 17 | Zörner, J.; Dymond, J.; Shepherd J.; Jolly, B. PyCrown - Fast raster-based individual tree segmentation for LiDAR data. Landcare Research NZ Ltd. 2018, https://doi.org/10.7931/M0SR-DN55 18 | 19 | *Research Article:* 20 | 21 | Zörner, J., Dymond, J.R., Shepherd, J.D., Wiser, S.K., Bunting, P., Jolly, B. (2018) Lidar-based regional inventory of tall trees - Wellington, New Zealand. Forests 9, 702-71. https://doi.org/10.3390/f9110702 22 | 23 | 24 | # Purpose and methods 25 | A number of open-source tools to identify tree top locations and delineate tree crowns already exist. The purpose of this package is to provide a fast and flexible Python-based implementation which builds on top of already well-established algorithms. 26 | 27 | Tree tops are identified in the first iteration through local maxima in the smoothed CHM. 28 | 29 | We re-implement the crown delineation algorithms from **Dalponte and Coomes (2016)** in Python. The original code was published as R-package *itcSegment* () and was further optimized for speed in the *lidR* R-package (). 30 | 31 | Our Cython and Numba implementations of the original algorithm provide a significant speed-up compared to *itcSegment* and a moderate improvement over the version available in the *lidR* package. 32 | 33 | We also adapted the crown algorithm slightly to grow in circular fashion around the tree top which gives crown a smoother, more natural looking shape. 34 | 35 | We add an additional step to correct for erroneous tree top locations on steep slopes by taking either the high point from the surface model or the centre of mass of the tree crown as new tree top. 36 | 37 | Reference: 38 | 39 | **Dalponte, M. and Coomes, D.A. (2016)** *Tree-centric mapping of forest carbon density from airborne laser scanning and hyperspectral data*. Methods in Ecology and Evolution, 7, 1236-1245. 40 | 41 | 42 | # Main outputs 43 | * **Tree top locations** (stored as 3D ESRI .shp-file) 44 | * **Tree crowns** (stored as 2D ESRI .shp-file) 45 | * **Individual tree classification of the 3D point cloud** (stored as .las-file) 46 | 47 | 48 | # Contributors 49 | * Dr Jan Zörner (Manaaki Whenua - Landcare Research, Lincoln, New Zealand) 50 | * Dr John Dymond (Manaaki Whenua - Landcare Research, Palmerston North, New Zealand) 51 | * Dr James Shepherd (Manaaki Whenua - Landcare Research, Palmerston North, New Zealand) 52 | * Dr Ben Jolly (Manaaki Whenua - Landcare Research, Palmerston North, New Zealand) 53 | 54 | 55 | # Requirements 56 | It is assumed that you generated a canopy height model (CHM), digital surface model (DSM) and digital terrain model (DTM) from the LiDAR dataset before running *PyCrown*. 57 | If you want to classify individual trees in the point cloud, it is recommended to normalize heights to *height above ground elevation* (also done externally). 58 | 59 | For processing laser scanning data we recommend the open-source software *SPDLib* (http://www.spdlib.org). 60 | 61 | 62 | # Installation and environment set-up 63 | **Python 3.6 is required.** 64 | 65 | Tested on: Windows 10, Debian 9 (Stretch), Fedora 28, Ubuntu 18.04 & 16.04 66 | 67 | ## Environment set-up 68 | ### With Conda package manager (recommended) 69 | #### Create the environment and install all required packages 70 | 71 | `conda env create` 72 | 73 | #### Activate the environment 74 | 75 | Windows: `activate pycrown-env` 76 | 77 | Linux: `source activate pycrown-env` 78 | 79 | ### With Python's venv and pip 80 | #### Create the environment 81 | 82 | `python -m venv pycrown-env` 83 | 84 | Linux: `source pycrown-env/bin/activate` 85 | 86 | Windows: `pycrown-env\Scripts\activate.bat` 87 | 88 | #### Install all required packages 89 | 90 | `python -m pip install --upgrade pip` 91 | 92 | `pip install -r requirements.txt` 93 | 94 | ## Run Tests 95 | There are only some rudimentary tests provided at the moment, but it is advised to check that everything works: 96 | 97 | `python setup.py test` 98 | 99 | ## Install PyCrown 100 | Build and install the PyCrown module with: 101 | 102 | `python setup.py install` 103 | 104 | 105 | # Common problems 106 | ## laspy.util.LaspyException: Laszip was not found on the system 107 | On some platforms (e.g. Ubuntu 16.04) the installation of laspy does not include laszip/laszip-cli. 108 | See the [issue report](https://github.com/laspy/laspy/issues/79) on github for more infos. 109 | 110 | In this case, please follow these steps: 111 | 112 | * `wget http://lastools.org/download/LAStools.zip` 113 | * `unzip LAStools.zip && cd LAStools && make` 114 | * `cp bin/laszip /home/USERNAME/miniconda3/envs/pycrown-env/bin/` 115 | 116 | If you encounter this error under Windows, please download LAStools.zip, extract the archive and copy the file "laszip.exe" from the "bin"-directory to the conda environment, e.g. C:\Users\\AppData\Local\Continuum\miniconda3\envs\pycrown-env\Scripts\ or C:\Users\\Miniconda3\envs\pycrown-env\Scripts 117 | 118 | ## Error while building 'pycrown._crown_dalponte_cython' extension 119 | Building the Cython module requires C++ build tools which may need to be installed on your system. 120 | 121 | The Windows error message on Windows provides instructions: 122 | `error: Microsoft Visual C++ 14.0 is required. Get it with "Build Tools for Visual Studio": https://visualstudio.microsoft.com/downloads/` 123 | During the setup process, please select 'C++ Build Tools'. 124 | 125 | ## TypeError: a bytes-like object is required, not 'FakeMmap' when trying to load .laz files 126 | There seems to be an incompatibility between laspy and numpy in recent versions. The combination `numpy==1.16.4` and `laspy==1.5.1` works for me. 127 | I suggest either not using .laz files for the time being or downgrading to the appropiate package versions. 128 | Please also refer to this github issue: https://github.com/laspy/laspy/issues/112 129 | 130 | 131 | # Getting Started 132 | You can find an IPython Notebook demonstrating each step of the tree segmentation approach in the *example* folder. 133 | 134 | You can also run the example python script directly. Results are stored in the *example/result* folder. 135 | 136 | `cd example` 137 | 138 | `python example.py` 139 | 140 | ## Main processing steps 141 | ### Step 1: Smoothing of CHM using a median filter 142 | ![Step 1](example/step_1.jpg) 143 | 144 | ### Step 2: Tree top detection using local maxima filter 145 | ![Step 2](example/step_2.jpg) 146 | 147 | ### Step 3: Tree Crown Delineation using an adapted Dalponte and Coomes (2016) scheme 148 | ![Step 3](example/step_3.jpg) 149 | 150 | ### Step 4: Tree top correction of trees on steep slopes 151 | ![Step 4](example/step_4.jpg) 152 | 153 | ### Step 5: Smoothing of crown polygons using first returns of normalized LiDAR point clouds 154 | ![Step 5](example/step_5.jpg) 155 | 156 | ### Step 6: Classification of individual trees in the 3D point cloud (visualized with CloudCompare) 157 | ![Classified Point Cloud](example/step_6a.jpg) 158 | ![Classified Point Cloud](example/step_6b.jpg) 159 | -------------------------------------------------------------------------------- /environment.yml: -------------------------------------------------------------------------------- 1 | name: pycrown-env 2 | channels: 3 | - conda 4 | dependencies: 5 | - python=3.6 6 | - pip>=10.0 7 | - numpy==1.16.4 8 | - scipy==1.1.0 9 | - scikit-image>=0.14.0 10 | - Cython>=0.28.4 11 | - numba>=0.39.0 12 | - pandas==0.23.3 13 | - geopandas==0.3.0 14 | - Rtree>=0.8.3 15 | - Fiona>=1.7.10 16 | - GDAL>=2.2.2 17 | - Shapely>=1.6.4 18 | - rasterio>=0.36.0 19 | - pip: 20 | - laspy==1.5.1 21 | -------------------------------------------------------------------------------- /example/PyCrown_example.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Tree Segmentation Example\n", 8 | "This is a simple example of what the PyCrown package can do: from pre-calculated rasters (CHM, DSM and DTM) and a height-normalized 3D LiDAR point cloud, individual trees can be segmented.\n", 9 | "Outputs are shapefiles of tree top locations, crown shapes as well as a .LAS-file containing classified trees." 10 | ] 11 | }, 12 | { 13 | "cell_type": "markdown", 14 | "metadata": {}, 15 | "source": [ 16 | "## Start with importing the modules" 17 | ] 18 | }, 19 | { 20 | "cell_type": "code", 21 | "execution_count": 1, 22 | "metadata": {}, 23 | "outputs": [], 24 | "source": [ 25 | "import sys\n", 26 | "from datetime import datetime\n", 27 | "from pycrown import PyCrown" 28 | ] 29 | }, 30 | { 31 | "cell_type": "markdown", 32 | "metadata": {}, 33 | "source": [ 34 | "## Set input files\n", 35 | "Specify the file locations for the CHM, DSM, DTM and the LiDAR point cloud.\n", 36 | "The latter is only needed if the point cloud should be classified into individual trees." 37 | ] 38 | }, 39 | { 40 | "cell_type": "code", 41 | "execution_count": 2, 42 | "metadata": {}, 43 | "outputs": [], 44 | "source": [ 45 | "F_CHM = 'data/CHM.tif'\n", 46 | "F_DTM = 'data/DTM.tif'\n", 47 | "F_DSM = 'data/DSM.tif'\n", 48 | "F_LAS = 'data/POINTS.las'" 49 | ] 50 | }, 51 | { 52 | "cell_type": "markdown", 53 | "metadata": {}, 54 | "source": [ 55 | "## Initialize an instance of PyCrown" 56 | ] 57 | }, 58 | { 59 | "cell_type": "code", 60 | "execution_count": 3, 61 | "metadata": {}, 62 | "outputs": [], 63 | "source": [ 64 | "PC = PyCrown(F_CHM, F_DTM, F_DSM, F_LAS, outpath='result')" 65 | ] 66 | }, 67 | { 68 | "cell_type": "markdown", 69 | "metadata": {}, 70 | "source": [ 71 | "## Clip all input data to new bounding box." 72 | ] 73 | }, 74 | { 75 | "cell_type": "code", 76 | "execution_count": 4, 77 | "metadata": {}, 78 | "outputs": [], 79 | "source": [ 80 | "PC.clip_data_to_bbox((1802150, 1802408, 5467305, 5467480))" 81 | ] 82 | }, 83 | { 84 | "cell_type": "markdown", 85 | "metadata": {}, 86 | "source": [ 87 | "## Smooth CHM\n", 88 | "A 5x5m block median filter is used (set circular=True to enable a disc-shaped window)." 89 | ] 90 | }, 91 | { 92 | "cell_type": "code", 93 | "execution_count": 5, 94 | "metadata": {}, 95 | "outputs": [], 96 | "source": [ 97 | "PC.filter_chm(5, ws_in_pixels=True, circular=False)" 98 | ] 99 | }, 100 | { 101 | "cell_type": "markdown", 102 | "metadata": {}, 103 | "source": [ 104 | "## Tree Detection with local maximum filter" 105 | ] 106 | }, 107 | { 108 | "cell_type": "code", 109 | "execution_count": 6, 110 | "metadata": {}, 111 | "outputs": [], 112 | "source": [ 113 | "PC.tree_detection(PC.chm, ws=5, hmin=16.)" 114 | ] 115 | }, 116 | { 117 | "cell_type": "markdown", 118 | "metadata": {}, 119 | "source": [ 120 | "## Clip trees to bounding box \n", 121 | "(no trees on image edge)\n", 122 | "original extent: 1802140, 1802418, 5467295, 5467490 " 123 | ] 124 | }, 125 | { 126 | "cell_type": "code", 127 | "execution_count": 7, 128 | "metadata": {}, 129 | "outputs": [], 130 | "source": [ 131 | "PC.clip_trees_to_bbox(bbox=(1802160, 1802400, 5467315, 5467470))" 132 | ] 133 | }, 134 | { 135 | "cell_type": "markdown", 136 | "metadata": {}, 137 | "source": [ 138 | "## Crown Delineation" 139 | ] 140 | }, 141 | { 142 | "cell_type": "code", 143 | "execution_count": 8, 144 | "metadata": {}, 145 | "outputs": [ 146 | { 147 | "name": "stdout", 148 | "output_type": "stream", 149 | "text": [ 150 | "Tree crowns delineation: 0.007s\n" 151 | ] 152 | } 153 | ], 154 | "source": [ 155 | "PC.crown_delineation(algorithm='dalponteCIRC_numba', th_tree=15.,\n", 156 | " th_seed=0.7, th_crown=0.55, max_crown=10.)" 157 | ] 158 | }, 159 | { 160 | "cell_type": "markdown", 161 | "metadata": {}, 162 | "source": [ 163 | "## (Optional) Correct tree tops on steep terrain" 164 | ] 165 | }, 166 | { 167 | "cell_type": "code", 168 | "execution_count": 9, 169 | "metadata": {}, 170 | "outputs": [ 171 | { 172 | "name": "stdout", 173 | "output_type": "stream", 174 | "text": [ 175 | "Number of trees: 128\n", 176 | "Tree tops corrected: 9\n", 177 | "Tree tops corrected: 7.03125%\n", 178 | "DSM correction: 5\n", 179 | "COM correction: 4\n" 180 | ] 181 | } 182 | ], 183 | "source": [ 184 | "PC.correct_tree_tops()" 185 | ] 186 | }, 187 | { 188 | "cell_type": "markdown", 189 | "metadata": {}, 190 | "source": [ 191 | "## Calculate tree height and elevation" 192 | ] 193 | }, 194 | { 195 | "cell_type": "code", 196 | "execution_count": 10, 197 | "metadata": {}, 198 | "outputs": [], 199 | "source": [ 200 | "PC.get_tree_height_elevation(loc='top')\n", 201 | "PC.get_tree_height_elevation(loc='top_cor')" 202 | ] 203 | }, 204 | { 205 | "cell_type": "markdown", 206 | "metadata": {}, 207 | "source": [ 208 | "## Screen small trees" 209 | ] 210 | }, 211 | { 212 | "cell_type": "code", 213 | "execution_count": 11, 214 | "metadata": {}, 215 | "outputs": [], 216 | "source": [ 217 | "PC.screen_small_trees(hmin=20., loc='top')" 218 | ] 219 | }, 220 | { 221 | "cell_type": "markdown", 222 | "metadata": {}, 223 | "source": [ 224 | "## Convert raster crowns to polygons" 225 | ] 226 | }, 227 | { 228 | "cell_type": "code", 229 | "execution_count": 12, 230 | "metadata": {}, 231 | "outputs": [ 232 | { 233 | "name": "stdout", 234 | "output_type": "stream", 235 | "text": [ 236 | "Converting LAS point cloud to shapely points\n", 237 | "Converting raster crowns to shapely polygons\n", 238 | "Attach LiDAR points to corresponding crowns\n", 239 | "Create convex hull around first return points\n", 240 | "Classifying point cloud\n" 241 | ] 242 | } 243 | ], 244 | "source": [ 245 | "PC.crowns_to_polys_raster()\n", 246 | "PC.crowns_to_polys_smooth(store_las=True)" 247 | ] 248 | }, 249 | { 250 | "cell_type": "markdown", 251 | "metadata": {}, 252 | "source": [ 253 | "## Check that all geometries are valid" 254 | ] 255 | }, 256 | { 257 | "cell_type": "code", 258 | "execution_count": 13, 259 | "metadata": {}, 260 | "outputs": [], 261 | "source": [ 262 | "PC.quality_control()" 263 | ] 264 | }, 265 | { 266 | "cell_type": "markdown", 267 | "metadata": {}, 268 | "source": [ 269 | "## Print out number of trees" 270 | ] 271 | }, 272 | { 273 | "cell_type": "code", 274 | "execution_count": 14, 275 | "metadata": {}, 276 | "outputs": [ 277 | { 278 | "name": "stdout", 279 | "output_type": "stream", 280 | "text": [ 281 | "Number of trees detected: 115\n" 282 | ] 283 | } 284 | ], 285 | "source": [ 286 | "print(f\"Number of trees detected: {len(PC.trees)}\")" 287 | ] 288 | }, 289 | { 290 | "cell_type": "markdown", 291 | "metadata": {}, 292 | "source": [ 293 | "## Export results" 294 | ] 295 | }, 296 | { 297 | "cell_type": "code", 298 | "execution_count": 15, 299 | "metadata": {}, 300 | "outputs": [], 301 | "source": [ 302 | "PC.export_raster(PC.chm, PC.outpath / 'chm.tif', 'CHM')\n", 303 | "PC.export_tree_locations(loc='top')\n", 304 | "PC.export_tree_locations(loc='top_cor')\n", 305 | "PC.export_tree_crowns(crowntype='crown_poly_raster')\n", 306 | "PC.export_tree_crowns(crowntype='crown_poly_smooth')" 307 | ] 308 | }, 309 | { 310 | "cell_type": "code", 311 | "execution_count": null, 312 | "metadata": {}, 313 | "outputs": [], 314 | "source": [] 315 | } 316 | ], 317 | "metadata": { 318 | "kernelspec": { 319 | "display_name": "Python 3", 320 | "language": "python", 321 | "name": "python3" 322 | }, 323 | "language_info": { 324 | "codemirror_mode": { 325 | "name": "ipython", 326 | "version": 3 327 | }, 328 | "file_extension": ".py", 329 | "mimetype": "text/x-python", 330 | "name": "python", 331 | "nbconvert_exporter": "python", 332 | "pygments_lexer": "ipython3", 333 | "version": "3.6.6" 334 | } 335 | }, 336 | "nbformat": 4, 337 | "nbformat_minor": 2 338 | } -------------------------------------------------------------------------------- /example/data/CHM.tif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manaakiwhenua/pycrown/3d8db4e03d82d5846ff68fc5fa9c18803d823464/example/data/CHM.tif -------------------------------------------------------------------------------- /example/data/DSM.tif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manaakiwhenua/pycrown/3d8db4e03d82d5846ff68fc5fa9c18803d823464/example/data/DSM.tif -------------------------------------------------------------------------------- /example/data/DTM.tif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manaakiwhenua/pycrown/3d8db4e03d82d5846ff68fc5fa9c18803d823464/example/data/DTM.tif -------------------------------------------------------------------------------- /example/data/POINTS.las: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manaakiwhenua/pycrown/3d8db4e03d82d5846ff68fc5fa9c18803d823464/example/data/POINTS.las -------------------------------------------------------------------------------- /example/data/POINTS.laz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manaakiwhenua/pycrown/3d8db4e03d82d5846ff68fc5fa9c18803d823464/example/data/POINTS.laz -------------------------------------------------------------------------------- /example/example.py: -------------------------------------------------------------------------------- 1 | """ 2 | PyCrown - Fast raster-based individual tree segmentation for LiDAR data 3 | ----------------------------------------------------------------------- 4 | Copyright: 2018, Jan Zörner 5 | Licence: GNU GPLv3 6 | """ 7 | 8 | from datetime import datetime 9 | 10 | from pycrown import PyCrown 11 | 12 | 13 | if __name__ == '__main__': 14 | 15 | TSTART = datetime.now() 16 | 17 | F_CHM = 'data/CHM.tif' 18 | F_DTM = 'data/DTM.tif' 19 | F_DSM = 'data/DSM.tif' 20 | F_LAS = 'data/POINTS.las' 21 | 22 | PC = PyCrown(F_CHM, F_DTM, F_DSM, F_LAS, outpath='result') 23 | 24 | # Cut off edges 25 | # PC.clip_data_to_bbox((1802200, 1802400, 5467250, 5467450)) 26 | 27 | # Smooth CHM with 5m median filter 28 | PC.filter_chm(5, ws_in_pixels=True) 29 | 30 | # Tree Detection with local maximum filter 31 | PC.tree_detection(PC.chm, ws=5, ws_in_pixels=True, hmin=16.) 32 | 33 | # Clip trees to bounding box (no trees on image edge) 34 | # original extent: 1802140, 1802418, 5467295, 5467490 35 | # PC.clip_trees_to_bbox(bbox=(1802150, 1802408, 5467305, 5467480)) 36 | # PC.clip_trees_to_bbox(bbox=(1802160, 1802400, 5467315, 5467470)) 37 | PC.clip_trees_to_bbox(inbuf=11) # inward buffer of 11 metre 38 | 39 | # Crown Delineation 40 | PC.crown_delineation(algorithm='dalponteCIRC_numba', th_tree=15., 41 | th_seed=0.7, th_crown=0.55, max_crown=10.) 42 | 43 | # Correct tree tops on steep terrain 44 | PC.correct_tree_tops() 45 | 46 | # Calculate tree height and elevation 47 | PC.get_tree_height_elevation(loc='top') 48 | PC.get_tree_height_elevation(loc='top_cor') 49 | 50 | # Screen small trees 51 | PC.screen_small_trees(hmin=20., loc='top') 52 | 53 | # Convert raster crowns to polygons 54 | PC.crowns_to_polys_raster() 55 | PC.crowns_to_polys_smooth(store_las=True) 56 | 57 | # Check that all geometries are valid 58 | PC.quality_control() 59 | 60 | # Export results 61 | PC.export_raster(PC.chm, PC.outpath / 'chm.tif', 'CHM') 62 | PC.export_tree_locations(loc='top') 63 | PC.export_tree_locations(loc='top_cor') 64 | PC.export_tree_crowns(crowntype='crown_poly_raster') 65 | PC.export_tree_crowns(crowntype='crown_poly_smooth') 66 | 67 | TEND = datetime.now() 68 | 69 | print(f"Number of trees detected: {len(PC.trees)}") 70 | print(f'Processing time: {TEND-TSTART} [HH:MM:SS]') 71 | -------------------------------------------------------------------------------- /example/step_1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manaakiwhenua/pycrown/3d8db4e03d82d5846ff68fc5fa9c18803d823464/example/step_1.jpg -------------------------------------------------------------------------------- /example/step_2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manaakiwhenua/pycrown/3d8db4e03d82d5846ff68fc5fa9c18803d823464/example/step_2.jpg -------------------------------------------------------------------------------- /example/step_3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manaakiwhenua/pycrown/3d8db4e03d82d5846ff68fc5fa9c18803d823464/example/step_3.jpg -------------------------------------------------------------------------------- /example/step_4.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manaakiwhenua/pycrown/3d8db4e03d82d5846ff68fc5fa9c18803d823464/example/step_4.jpg -------------------------------------------------------------------------------- /example/step_5.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manaakiwhenua/pycrown/3d8db4e03d82d5846ff68fc5fa9c18803d823464/example/step_5.jpg -------------------------------------------------------------------------------- /example/step_6a.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manaakiwhenua/pycrown/3d8db4e03d82d5846ff68fc5fa9c18803d823464/example/step_6a.jpg -------------------------------------------------------------------------------- /example/step_6b.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manaakiwhenua/pycrown/3d8db4e03d82d5846ff68fc5fa9c18803d823464/example/step_6b.jpg -------------------------------------------------------------------------------- /pycrown/__init__.py: -------------------------------------------------------------------------------- 1 | from .pycrown import PyCrown 2 | -------------------------------------------------------------------------------- /pycrown/_crown_dalponteCIRC_numba.py: -------------------------------------------------------------------------------- 1 | """ 2 | PyCrown - Fast raster-based individual tree segmentation for LiDAR data 3 | ----------------------------------------------------------------------- 4 | Copyright: 2018, Jan Zörner 5 | Licence: GNU GPLv3 6 | """ 7 | 8 | from numba import jit, float32, int32, float_ 9 | import numpy as np 10 | 11 | 12 | @jit(nopython=True, nogil=True, parallel=False) 13 | def get_neighbourhood(radius): 14 | """ creates list of row and column coordinates for circular indexing around 15 | a central pixel and for different distances from the centre 16 | 17 | Parameters 18 | ---------- 19 | radius : int 20 | radius of circular kernel 21 | 22 | Returns 23 | ------- 24 | ndarray 25 | array of column coordinates _relative_ to the central pixel 26 | ndarray 27 | array of row coordinates _relative_ to the central pixel 28 | ndarray 29 | indices for splitting the array of row/column coordinates into 30 | different distances from the centre 31 | """ 32 | # build a circular kernel 33 | xy = np.arange(-radius, radius+1).reshape(radius*2+1, 1) 34 | kernel = xy**2 + xy.reshape(1, radius*2+1)**2 35 | 36 | # numba v0.39 doesn't support np.unique, so use a workaround 37 | sfkernel = np.sort(kernel.flatten()) 38 | unique = list(sfkernel[:1]) 39 | for x in sfkernel: 40 | if x != unique[-1]: 41 | unique.append(x) 42 | 43 | nums = unique[1:] 44 | start = 1 45 | for num in range(len(nums)): 46 | if nums[num] >= radius**2: 47 | continue 48 | n1, n0 = np.where(kernel == nums[num]) 49 | if start: 50 | neighbours_x = list(n1.astype(np.int32)) 51 | neighbours_y = list(n0.astype(np.int32)) 52 | breaks = [len(n0)] 53 | start = 0 54 | else: 55 | neighbours_x += list(n1.astype(np.int32)) 56 | neighbours_y += list(n0.astype(np.int32)) 57 | breaks.append(len(n0)) 58 | breaks = np.array(breaks, dtype=np.int32) 59 | neighbours_x = np.array(neighbours_x, dtype=np.int32) - radius 60 | neighbours_y = np.array(neighbours_y, dtype=np.int32) - radius 61 | return neighbours_x, neighbours_y, breaks 62 | 63 | 64 | @jit(int32[:, :](float32[:, :], int32[:, :], float_, float_, float_, float_), 65 | nopython=True, nogil=True, parallel=False) 66 | def _crown_dalponteCIRC(Chm, Trees, th_seed, th_crown, th_tree, max_crown): 67 | ''' 68 | Crown delineation based on Dalponte and Coomes (2016) and 69 | lidR R-package (https://github.com/Jean-Romain/lidR/) 70 | In contrast to the moving window growing scheme from the original algorithm 71 | this code implements a circular region growing around the tree top which 72 | leads to smoother crown patterns and speeds up the calculation by one order 73 | of magnitude 74 | 75 | Parameters 76 | ---------- 77 | Chm : ndarray 78 | Canopy height model as n x m raster 79 | Trees : ndarray 80 | Tree top pixel coordinates as nx2 ndarray 81 | th_tree : float 82 | Threshold below which a pixel cannot be a tree. Default 2 83 | th_seed : float 84 | Growing threshold 1. A pixel is added to a region if its height 85 | is greater than the tree height multiplied by this value. It 86 | should be between 0 and 1. Default 0.45 87 | th_crown : float 88 | Growing threshold 2. A pixel is added to a region if its height 89 | is greater than the current mean height of the region 90 | multiplied by this value. It should be between 0 and 1. 91 | Default 0.55. 92 | max_crown : float 93 | Maximum value of the crown diameter of a detected tree (in 94 | pixels). Default 10 95 | 96 | Returns 97 | ------- 98 | ndarray 99 | Raster of tree crowns 100 | ''' 101 | 102 | ntops = Trees.shape[1] 103 | npixel = np.ones(ntops) 104 | tidx_x, tidx_y = Trees[0], Trees[1] 105 | Crowns = np.zeros_like(Chm, dtype=np.int32) 106 | nrows = Chm.shape[0] 107 | ncols = Chm.shape[1] 108 | sum_height = np.zeros(ntops) 109 | for i in range(ntops): 110 | Crowns[tidx_y[i], tidx_x[i]] = i + 1 111 | sum_height[i] = Chm[tidx_y[i], tidx_x[i]] 112 | 113 | tree_idx = np.arange(ntops) 114 | neighbours = np.zeros((4, 2)).astype(np.int32) 115 | 116 | # Create the circular look-up indices 117 | neighbours_x, neighbours_y, breaks = get_neighbourhood(int(max_crown)) 118 | 119 | step = 0 120 | for n_neighbours in breaks: 121 | grown = False 122 | for tidx in tree_idx: 123 | 124 | # Pixel coordinates of current seed 125 | seed_y = tidx_y[tidx] 126 | seed_x = tidx_x[tidx] 127 | # Seed height 128 | seed_h = Chm[seed_y, seed_x] 129 | # Mean height of the crown 130 | mh_crown = sum_height[tidx] / npixel[tidx] 131 | 132 | # Go through neighbourhood 133 | for n in range(n_neighbours): 134 | # Pixel coordinates of current neighbour 135 | nb_x = seed_x + neighbours_x[step + n] 136 | nb_y = seed_y + neighbours_y[step + n] 137 | 138 | # avoid out-of-bounds exceptions 139 | if nb_x < 1 or nb_x > ncols-2 or nb_y < 1 or nb_y > nrows-2: 140 | continue 141 | 142 | # Neighbour height 143 | nb_h = Chm[nb_y, nb_x] 144 | 145 | # Perform different checks: 146 | # 1. Neighbour height is above minimum threshold 147 | # 2. Neighbour does not belong to other crown 148 | # 3. Neighbour height is above threshold 1 149 | # 4. Neighbour height is above threshold 2 150 | # 5. Neighbour height below treetop+5% 151 | # 7. Neighbour is not too far from the tree top (x-dir) 152 | # 8. Neighbour is not too far from the tree top (y-dir) 153 | if nb_h > th_tree and \ 154 | not Crowns[nb_y, nb_x] and \ 155 | nb_h > (seed_h * th_seed) and \ 156 | nb_h > (mh_crown * th_crown) and \ 157 | nb_h <= (seed_h * 1.05) and \ 158 | abs(seed_x-nb_x) < max_crown and \ 159 | abs(seed_y-nb_y) < max_crown: 160 | 161 | # Positions of the 4 neighbours 162 | neighbours[0, 0] = nb_y - 1 163 | neighbours[0, 1] = nb_x 164 | neighbours[1, 0] = nb_y 165 | neighbours[1, 1] = nb_x - 1 166 | neighbours[2, 0] = nb_y 167 | neighbours[2, 1] = nb_x + 1 168 | neighbours[3, 0] = nb_y + 1 169 | neighbours[3, 1] = nb_x 170 | 171 | for j in range(4): 172 | 173 | # if neighbours[j, 0] <= 0 or \ 174 | # neighbours[j, 0] >= nrows or \ 175 | # neighbours[j, 1] <= 0 or \ 176 | # neighbours[j, 1] >= ncols: 177 | # continue 178 | 179 | # Check that pixel is connected to current crown 180 | if Crowns[neighbours[j, 0], neighbours[j, 1]] == tidx+1: 181 | # If all conditions are met, add neighbour to crown 182 | Crowns[nb_y, nb_x] = tidx + 1 183 | npixel[tidx] += 1 184 | sum_height[tidx] += nb_h 185 | grown = True 186 | break 187 | 188 | step += n_neighbours 189 | if not grown: 190 | break 191 | 192 | return Crowns 193 | -------------------------------------------------------------------------------- /pycrown/_crown_dalponte_cython.pyx: -------------------------------------------------------------------------------- 1 | """ 2 | PyCrown - Fast raster-based individual tree segmentation for LiDAR data 3 | ----------------------------------------------------------------------- 4 | Copyright: 2018, Jan Zörner 5 | Licence: GNU GPLv3 6 | """ 7 | 8 | # cython: boundscheck=False 9 | # cython: cdivision=True 10 | # cython: wraparound=False 11 | 12 | import numpy as np 13 | cimport numpy as np 14 | from libc.math cimport abs 15 | 16 | 17 | def _crown_dalponte(float[:, :] Chm, int[:, :] Trees, 18 | float th_seed, float th_crown, float th_tree, 19 | float max_crown): 20 | ''' 21 | Crown delineation based on Dalponte and Coomes (2016) and 22 | lidR R-package (https://github.com/Jean-Romain/lidR/) 23 | 24 | Parameters 25 | ---------- 26 | Chm : ndarray 27 | Canopy height model as n x m raster 28 | Trees : ndarray 29 | Tree top pixel coordinates as nx2 ndarray 30 | th_tree : float 31 | Threshold below which a pixel cannot be a tree. Default 2 32 | th_seed : float 33 | Growing threshold 1. A pixel is added to a region if its height 34 | is greater than the tree height multiplied by this value. It 35 | should be between 0 and 1. Default 0.45 36 | th_crown : float 37 | Growing threshold 2. A pixel is added to a region if its height 38 | is greater than the current mean height of the region 39 | multiplied by this value. It should be between 0 and 1. 40 | Default 0.55. 41 | max_crown : float 42 | Maximum value of the crown diameter of a detected tree (in 43 | pixels). Default 10 44 | 45 | Returns 46 | ------- 47 | Cronws : ndarray 48 | Raster of tree crowns 49 | ''' 50 | 51 | grown = True 52 | cdef int i, j, row, col, seed_y, seed_x, nb_y, nb_x, tidx 53 | cdef int nrow = Chm.shape[0] 54 | cdef int ncol = Chm.shape[1] 55 | cdef int ntops = Trees.shape[1] 56 | cdef int[:] tidx_x = np.floor(Trees[0]).astype(np.int32) 57 | cdef int[:] tidx_y = np.floor(Trees[1]).astype(np.int32) 58 | cdef int[:, :] Crowns = np.zeros((nrow, ncol), dtype=np.int32) 59 | cdef int[:] npixel = np.ones(ntops, dtype=np.int32) 60 | cdef int[:, :] neighbours = np.zeros((4, 2), dtype=np.int32) 61 | cdef float[:] sum_height = np.zeros(ntops, dtype=np.float32) 62 | cdef float seed_h, mh_crown, nb_h 63 | for i in range(ntops): 64 | Crowns[tidx_y[i], tidx_x[i]] = i + 1 65 | sum_height[i] = Chm[tidx_y[i], tidx_x[i]] 66 | cdef int[:, :] CrownsTemp = Crowns.copy() 67 | 68 | while grown: 69 | grown = False 70 | for row in range(1, nrow - 1): 71 | for col in range(1, ncol - 1): 72 | 73 | # enter if pixel belongs to a tree top or tree crown 74 | if Crowns[row, col]: 75 | 76 | # id of the tree crown for the current pixel 77 | tidx = Crowns[row, col] - 1 78 | 79 | # Pixel coordinates of current seed 80 | seed_y = tidx_y[tidx] 81 | seed_x = tidx_x[tidx] 82 | 83 | # Seed height 84 | seed_h = Chm[seed_y, seed_x] 85 | 86 | # Mean height of the crown 87 | mh_crown = sum_height[tidx] / npixel[tidx] 88 | 89 | # Positions of the 4 neighbours 90 | neighbours[0, 0] = row - 1 91 | neighbours[0, 1] = col 92 | neighbours[1, 0] = row 93 | neighbours[1, 1] = col - 1 94 | neighbours[2, 0] = row 95 | neighbours[2, 1] = col + 1 96 | neighbours[3, 0] = row + 1 97 | neighbours[3, 1] = col 98 | 99 | # Go through neighbourhood 100 | for j in range(4): 101 | # Pixel coordinates of current neighbour 102 | nb_y = neighbours[j, 0] 103 | nb_x = neighbours[j, 1] 104 | # Neighbour height 105 | nb_h = Chm[nb_y, nb_x] 106 | 107 | # Perform different checks: 108 | # 1. Neighbour height is above minimum threshold 109 | # 2. Neighbour does not belong to other crown 110 | # 3. Neighbour height is above threshold 1 111 | # 4. Neighbour height is above threshold 2 112 | # 5. Neighbour height below treetop+5% 113 | # 7. Neighbour is not too far from the tree top (x-dir) 114 | # 8. Neighbour is not too far from the tree top (y-dir) 115 | if nb_h > th_tree and \ 116 | not CrownsTemp[nb_y, nb_x] and \ 117 | nb_h > (seed_h * th_seed) and \ 118 | nb_h > (mh_crown * th_crown) and \ 119 | nb_h <= (seed_h * 1.05) and \ 120 | abs(seed_x-nb_x) < max_crown and \ 121 | abs(seed_y-nb_y) < max_crown: 122 | # If all conditions are met, add neighbour to crown 123 | CrownsTemp[nb_y, nb_x] = Crowns[row, col] 124 | npixel[tidx] += 1 125 | sum_height[tidx] += nb_h 126 | grown = True 127 | 128 | Crowns[:, :] = CrownsTemp.copy() 129 | 130 | return Crowns 131 | -------------------------------------------------------------------------------- /pycrown/_crown_dalponte_numba.py: -------------------------------------------------------------------------------- 1 | """ 2 | PyCrown - Fast raster-based individual tree segmentation for LiDAR data 3 | ----------------------------------------------------------------------- 4 | Copyright: 2018, Jan Zörner 5 | Licence: GNU GPLv3 6 | """ 7 | 8 | from numba import jit, float32, int32, float_ 9 | import numpy as np 10 | 11 | 12 | @jit(int32[:, :](float32[:, :], int32[:, :], float_, float_, float_, float_), 13 | nopython=True, nogil=True, parallel=False) 14 | def _crown_dalponte(Chm, Trees, th_seed, th_crown, th_tree, max_crown): 15 | ''' 16 | Crown delineation based on Dalponte and Coomes (2016) and 17 | lidR R-package (https://github.com/Jean-Romain/lidR/) 18 | 19 | Parameters 20 | ---------- 21 | Chm : ndarray 22 | Canopy height model as n x m raster 23 | Trees : ndarray 24 | Tree top pixel coordinates as nx2 ndarray 25 | th_tree : float 26 | Threshold below which a pixel cannot be a tree. Default 2 27 | th_seed : float 28 | Growing threshold 1. A pixel is added to a region if its height 29 | is greater than the tree height multiplied by this value. It 30 | should be between 0 and 1. Default 0.45 31 | th_crown : float 32 | Growing threshold 2. A pixel is added to a region if its height 33 | is greater than the current mean height of the region 34 | multiplied by this value. It should be between 0 and 1. 35 | Default 0.55. 36 | max_crown : float 37 | Maximum value of the crown diameter of a detected tree (in 38 | pixels). Default 10 39 | 40 | Returns 41 | ------- 42 | Cronws : ndarray 43 | Raster of tree crowns 44 | ''' 45 | 46 | grown = True 47 | nrow = Chm.shape[0] 48 | ncol = Chm.shape[1] 49 | ntops = Trees.shape[1] 50 | npixel = np.ones(ntops, dtype=np.float32) 51 | neighbours = np.zeros((4, 2)).astype(np.int32) 52 | tidx_x = np.floor(Trees[0]).astype(np.intp) 53 | tidx_y = np.floor(Trees[1]).astype(np.intp) 54 | Crowns = np.zeros((nrow, ncol), dtype=np.int32) 55 | sum_height = np.zeros(ntops) 56 | for i in range(ntops): 57 | Crowns[tidx_y[i], tidx_x[i]] = i + 1 58 | sum_height[i] = Chm[tidx_y[i], tidx_x[i]] 59 | CrownsTemp = Crowns.copy() 60 | 61 | while grown: 62 | grown = False 63 | for row in range(1, nrow - 1): 64 | for col in range(1, ncol - 1): 65 | 66 | # enter if pixel belongs to a tree top or tree crown 67 | if Crowns[row, col]: 68 | 69 | # id of the tree crown for the current pixel 70 | tidx = Crowns[row, col] - 1 71 | 72 | # Pixel coordinates of current seed 73 | seed_y = tidx_y[tidx] 74 | seed_x = tidx_x[tidx] 75 | 76 | # Seed height 77 | seed_h = Chm[seed_y, seed_x] 78 | 79 | # Mean height of the crown 80 | mh_crown = sum_height[tidx] / npixel[tidx] 81 | 82 | # Positions of the 4 neighbours 83 | neighbours[0, 0] = row - 1 84 | neighbours[0, 1] = col 85 | neighbours[1, 0] = row 86 | neighbours[1, 1] = col - 1 87 | neighbours[2, 0] = row 88 | neighbours[2, 1] = col + 1 89 | neighbours[3, 0] = row + 1 90 | neighbours[3, 1] = col 91 | 92 | # Go through neighbourhood 93 | for j in range(4): 94 | # Pixel coordinates of current neighbour 95 | nb_y = neighbours[j, 0] 96 | nb_x = neighbours[j, 1] 97 | # Neighbour height 98 | nb_h = Chm[nb_y, nb_x] 99 | 100 | # Perform different checks: 101 | # 1. Neighbour height is above minimum threshold 102 | # 2. Neighbour does not belong to other crown 103 | # 3. Neighbour height is above threshold 1 104 | # 4. Neighbour height is above threshold 2 105 | # 5. Neighbour height below treetop+5% 106 | # 7. Neighbour is not too far from the tree top (x-dir) 107 | # 8. Neighbour is not too far from the tree top (y-dir) 108 | if nb_h > th_tree and \ 109 | not CrownsTemp[nb_y, nb_x] and \ 110 | nb_h > (seed_h * th_seed) and \ 111 | nb_h > (mh_crown * th_crown) and \ 112 | nb_h <= (seed_h * 1.05) and \ 113 | abs(seed_x-nb_x) < max_crown and \ 114 | abs(seed_y-nb_y) < max_crown: 115 | # If all conditions are met, add neighbour to crown 116 | CrownsTemp[nb_y, nb_x] = Crowns[row, col] 117 | npixel[tidx] += 1 118 | sum_height[tidx] += nb_h 119 | grown = True 120 | 121 | Crowns = CrownsTemp.copy() 122 | 123 | return Crowns 124 | -------------------------------------------------------------------------------- /pycrown/pycrown.py: -------------------------------------------------------------------------------- 1 | """ 2 | PyCrown - Fast raster-based individual tree segmentation for LiDAR data 3 | ----------------------------------------------------------------------- 4 | Copyright: 2018, Jan Zörner 5 | Licence: GNU GPLv3 6 | """ 7 | 8 | import time 9 | import platform 10 | import warnings 11 | from math import floor 12 | from pathlib import Path 13 | 14 | import pyximport 15 | 16 | import numpy as np 17 | import pandas as pd 18 | import geopandas as gpd 19 | 20 | import scipy.ndimage as ndimage 21 | import scipy.ndimage.filters as filters 22 | from scipy.spatial.distance import cdist 23 | 24 | from skimage.morphology import watershed 25 | from skimage.filters import threshold_otsu 26 | # from skimage.feature import peak_local_max 27 | 28 | import gdal 29 | import osr 30 | 31 | from shapely.geometry import mapping, Point, Polygon 32 | 33 | from rasterio.features import shapes as rioshapes 34 | 35 | import fiona 36 | from fiona.crs import from_epsg 37 | 38 | import laspy 39 | 40 | try: 41 | from pycrown import _crown_dalponte_cython 42 | except ImportError: 43 | print("WARNING: Cython module not compiled. 'crown_dalponte_cython' not available") 44 | from pycrown import _crown_dalponte_numba 45 | from pycrown import _crown_dalponteCIRC_numba 46 | 47 | gdal.UseExceptions() 48 | warnings.filterwarnings('ignore') 49 | 50 | 51 | class NoTreesException(Exception): 52 | """ Raised when no tree detected """ 53 | pass 54 | 55 | 56 | class GDALFileNotFoundException(Exception): 57 | """ Raised when GDAL file not found """ 58 | pass 59 | 60 | 61 | class PyCrown: 62 | 63 | __author__ = "Dr. Jan Zörner" 64 | __copyright__ = "Copyright 2018, Jan Zörner" 65 | __credits__ = ["Jan Zörner", "John Dymond", "James Shepherd", "Ben Jolly"] 66 | __license__ = "GNU GPLv3" 67 | __version__ = "0.1" 68 | __maintainer__ = "Jan Zörner" 69 | __email__ = "zoernerj@landcareresearch.co.nz" 70 | __status__ = "Development" 71 | 72 | def __init__(self, chm_file, dtm_file, dsm_file, las_file=None, 73 | outpath=None, suffix=None): 74 | """ PyCrown class 75 | 76 | Parameters 77 | ---------- 78 | chm_file : str 79 | Path to Canopy Height Model 80 | dtm_file : str 81 | Path to Digital Terrain Model 82 | dsm_file : str 83 | Path to Digital Surface Model 84 | las_file : str 85 | Path to LAS (LiDAR point cloud) file 86 | outpath : str, optional 87 | Output directory 88 | suffix : str, optional 89 | text appended to output file names 90 | 91 | Example 92 | ------- 93 | 94 | PC = PyCrown(F_CHM, F_DTM, F_DSM, F_LAS, outpath=sys.argv[1]) 95 | PC.filter_chm(5) 96 | PC.tree_detection(PC.chm, ws=5, hmin=16.) 97 | PC.crown_delineation(algorithm='dalponteCIRC_numba', th_tree=15., 98 | th_seed=0.7, th_crown=0.55, max_crown=10.) 99 | PC.correct_tree_tops() 100 | PC.get_tree_height_elevation(loc='top') 101 | PC.get_tree_height_elevation(loc='top_cor') 102 | PC.screen_small_trees(hmin=20., loc='top') 103 | PC.crowns_to_polys_raster() 104 | PC.crowns_to_polys_smooth(store_las=True) 105 | PC.quality_control() 106 | PC.export_raster(PC.chm, PC.outpath / 'chm.tif', 'CHM') 107 | PC.export_tree_locations(loc='top') 108 | PC.export_tree_locations(loc='top_cor') 109 | PC.export_tree_crowns(crowntype='crown_poly_raster') 110 | PC.export_tree_crowns(crowntype='crown_poly_smooth') 111 | """ 112 | 113 | suffix = f'_{suffix}' if suffix else '' 114 | 115 | self.outpath = Path(outpath) if outpath else Path('./') 116 | 117 | # Load the CHM 118 | self.chm_file = Path(chm_file) 119 | try: 120 | chm_gdal = gdal.Open(str(self.chm_file), gdal.GA_ReadOnly) 121 | except RuntimeError as e: 122 | raise IOError(e) 123 | proj = osr.SpatialReference(wkt=chm_gdal.GetProjection()) 124 | self.epsg = int(proj.GetAttrValue('AUTHORITY', 1)) 125 | self.srs = from_epsg(self.epsg) 126 | self.geotransform = chm_gdal.GetGeoTransform() 127 | self.resolution = abs(self.geotransform[-1]) 128 | self.ul_lon = chm_gdal.GetGeoTransform()[0] 129 | self.ul_lat = chm_gdal.GetGeoTransform()[3] 130 | self.chm0 = chm_gdal.GetRasterBand(1).ReadAsArray() 131 | chm_gdal = None 132 | 133 | 134 | # Load the DTM 135 | try: 136 | self.dtm_file = Path(dtm_file) 137 | except RuntimeError as e: 138 | raise IOError(e) 139 | dtm_gdal = gdal.Open(str(self.dtm_file), gdal.GA_ReadOnly) 140 | self.dtm = dtm_gdal.GetRasterBand(1).ReadAsArray() 141 | dtm_gdal = None 142 | 143 | # Load the DSM 144 | try: 145 | self.dsm_file = Path(dsm_file) 146 | except RuntimeError as e: 147 | raise IOError(e) 148 | dsm_gdal = gdal.Open(str(self.dsm_file), gdal.GA_ReadOnly) 149 | self.dsm = dsm_gdal.GetRasterBand(1).ReadAsArray() 150 | dsm_gdal = None 151 | 152 | # Load the LiDAR point cloud 153 | self.lidar_in_crowns = None 154 | self.las = None 155 | if las_file: 156 | self._load_lidar_points_cloud(las_file) 157 | 158 | self.chm = None 159 | self.crowns = None 160 | self.tree_markers = None 161 | self.tt_corrected = None 162 | 163 | self.trees = pd.DataFrame(columns=[ 164 | 'top_height', 'top_elevation', 165 | 'top_cor_height', 'top_cor_elevation', 166 | 'crown_poly_raster', 'crown_poly_smooth', 167 | 'top_cor', 'top', 'tt_corrected' 168 | ]) 169 | 170 | self.trees = self.trees.astype(dtype={ 171 | 'top_height': 'float', 172 | 'top_elevation': 'float', 173 | 'top_cor_height': 'float', 174 | 'top_cor_elevation': 'float', 175 | 'crown_poly_raster': 'object', 176 | 'crown_poly_smooth': 'object', 177 | 'top_cor': 'object', 178 | 'top': 'object', 179 | 'tt_corrected': 'int' 180 | }) 181 | 182 | def _load_lidar_points_cloud(self, fname): 183 | """ Loads LiDAR dataset 184 | 185 | Parameters 186 | ---------- 187 | fname : str 188 | Path to LiDAR dataset (.las or .laz-file) 189 | """ 190 | las = laspy.file.File(str(fname), mode='r') 191 | lidar_points = np.array(( 192 | las.x, las.y, las.z, las.intensity, las.return_num, 193 | las.classification 194 | )).transpose() 195 | colnames = ['x', 'y', 'z', 'intensity', 'return_num', 'classification'] 196 | self.las = pd.DataFrame(lidar_points, columns=colnames) 197 | las.close() 198 | 199 | def _check_empty(self): 200 | """ Helper function raising an Exception if no trees present 201 | 202 | Raises 203 | ------ 204 | NoTreesException 205 | raises Exception if no trees present 206 | """ 207 | if self.trees.empty: 208 | raise NoTreesException 209 | 210 | def _to_lonlat(self, pix_x, pix_y, resolution): 211 | ''' Convert pixel coordinates to longitude/latitude 212 | 213 | Parameters 214 | ---------- 215 | pix_x : int, float, ndarray 216 | Column coordinate of raster 217 | pix_y : int, float, ndarray 218 | Row coordinate of raster 219 | resolution: int 220 | resolution (in m) of raster 221 | 222 | Returns 223 | ------- 224 | tuple 225 | longitude(s), latitude(s) 226 | ''' 227 | lon = self.ul_lon + (pix_x * resolution) 228 | lat = self.ul_lat - (pix_y * resolution) 229 | return lon, lat 230 | 231 | def _to_colrow(self, lon, lat, resolution): 232 | ''' Convert longitude/latitude to pixel coordinates 233 | returns either tuple of floats or 2xn ndarray 234 | 235 | Parameters 236 | ---------- 237 | lon : int, float, ndarray, (pandas) Series 238 | Longtitude 239 | lat : int, float, ndarray, (pandas) Series 240 | Latitude 241 | resolution: int 242 | resolution (in m) of raster 243 | 244 | Returns 245 | ------- 246 | tuple 247 | Column/Row coordinate as floats 248 | or: 249 | ndarray 250 | Column/Row coordinate as 2xn ndarray 251 | ''' 252 | x = (lon - self.ul_lon) / resolution 253 | y = (self.ul_lat - lat) / resolution 254 | if isinstance(x, type(y)): 255 | if isinstance(x, float): 256 | return int(x), int(y) 257 | if isinstance(x, (np.ndarray, pd.Series)): 258 | return np.array([x, y], dtype=int) 259 | else: 260 | raise Exception("Can't handle different input types for x, y.") 261 | 262 | def _get_z(self, lon, lat, band, resolution): 263 | """ Returns data from raster band for coordinate location(s) 264 | 265 | Parameters 266 | ---------- 267 | lon : int, float, ndarray, (pandas) Series 268 | Longtitude 269 | lat : int, float, ndarray, (pandas) Series 270 | Latitude 271 | band : ndarray 272 | raster layer (e.g., CHM or DSM) 273 | resolution: int 274 | resolution (in m) of raster 275 | 276 | Returns 277 | ------- 278 | float 279 | raster value at longitude/latitude position 280 | """ 281 | x, y = self._to_colrow(lon, lat, resolution) 282 | return band[y, x] 283 | 284 | def _tree_lonlat(self, loc='top'): 285 | ''' returns longitude/latitude of tree tops 286 | 287 | Parameters 288 | ---------- 289 | loc : str, optional 290 | initial or corrected tree top location: `top` or `top_cor` 291 | 292 | Returns 293 | ------- 294 | tuple 295 | ndarrays of longitude(s), latitude(s) of tree tops 296 | ''' 297 | lons = np.array([tree[1][loc].x for tree in self.trees.iterrows()]) 298 | lats = np.array([tree[1][loc].y for tree in self.trees.iterrows()]) 299 | return lons, lats 300 | 301 | 302 | def _tree_colrow(self, loc, resolution): 303 | """ returns column/row of tree tops 304 | 305 | Parameters 306 | ---------- 307 | loc : str, optional 308 | initial or corrected tree top location: `top` or `top_cor` 309 | resolution: int 310 | resolution (in m) of raster 311 | 312 | Returns 313 | ------- 314 | ndarray 315 | 2xn ndarray of column(s), row(s) positions of tree tops 316 | """ 317 | return self._to_colrow(np.array([tree.x for tree in self.trees[loc]]), 318 | np.array([tree.y for tree in self.trees[loc]]), 319 | resolution).astype(np.int32) 320 | 321 | def _watershed(self, inraster, th_tree=15.): 322 | """ Simple implementation of a watershed tree crown delineation 323 | 324 | Parameters 325 | ---------- 326 | inraster : ndarray 327 | raster of height values (e.g., CHM) 328 | th_tree : float 329 | minimum height of tree crown 330 | 331 | Returns 332 | ------- 333 | ndarray 334 | raster of individual tree crowns 335 | """ 336 | inraster_mask = inraster.copy() 337 | inraster_mask[inraster <= th_tree] = 0 338 | raster = inraster.copy() 339 | raster[np.isnan(raster)] = 0. 340 | labels = watershed(-raster, self.tree_markers, mask=inraster_mask) 341 | return labels 342 | 343 | def _screen_crowns(self, cond): 344 | """ Remove crowns outside tile from crowns raster and reindex 345 | the remaining ones 346 | 347 | Parameters 348 | ---------- 349 | cond : list 350 | list of booleans. Keep trees/crowns with True 351 | """ 352 | counter = 1 353 | for idx, valid in enumerate(cond): 354 | if valid: 355 | self.crowns[self.crowns == idx + 1] = counter 356 | counter += 1 357 | else: 358 | self.crowns[self.crowns == idx + 1] = 0. 359 | 360 | @staticmethod 361 | def _get_kernel(radius=5, circular=False): 362 | """ returns a block or disc-shaped filter kernel with given radius 363 | 364 | Parameters 365 | ---------- 366 | radius : int, optional 367 | radius of the filter kernel 368 | circular : bool, optional 369 | set to True for disc-shaped filter kernel, block otherwise 370 | 371 | Returns 372 | ------- 373 | ndarray 374 | filter kernel 375 | """ 376 | if circular: 377 | y, x = np.ogrid[-radius:radius+1, -radius:radius+1] 378 | return x**2 + y**2 <= radius**2 379 | else: 380 | return np.ones((int(radius), int(radius))) 381 | 382 | def _smooth_raster(self, raster, ws, resolution, circular=False): 383 | """ Smooth a raster with a median filter 384 | 385 | Parameters 386 | ---------- 387 | raster : ndarray 388 | raster to be smoothed 389 | ws : int 390 | window size of smoothing filter 391 | resolution : int 392 | resolution of raster in m 393 | circular : bool, optional 394 | set to True for disc-shaped filter kernel, block otherwise 395 | 396 | Returns 397 | ------- 398 | ndarray 399 | smoothed raster 400 | """ 401 | return filters.median_filter( 402 | raster, footprint=self._get_kernel(ws, circular=circular)) 403 | 404 | def clip_data_to_bbox(self, bbox, las_offset=10): 405 | """ Clip input data to subset region based on bounding box 406 | 407 | Parameters 408 | ---------- 409 | bbox : tuple 410 | lon_min, lon_max, lat_min, lat_max 411 | las_offset : int, optional 412 | buffer around bounding for LiDAR data (in m) 413 | """ 414 | 415 | lon_min, lon_max, lat_min, lat_max = bbox 416 | col_min, row_max = self._to_colrow(lon_min, lat_min, self.resolution) 417 | col_max, row_min = self._to_colrow(lon_max, lat_max, self.resolution) 418 | 419 | self.chm0 = self.chm0[row_min:row_max, col_min:col_max] 420 | if isinstance(self.chm, np.ndarray): 421 | self.chm = self.chm[row_min:row_max, col_min:col_max] 422 | self.dtm = self.dtm[row_min:row_max, col_min:col_max] 423 | self.dsm = self.dsm[row_min:row_max, col_min:col_max] 424 | lasmask = ( 425 | (self.las.x >= lon_min - las_offset) & 426 | (self.las.x <= lon_max + las_offset) & 427 | (self.las.y >= lat_min - las_offset) & 428 | (self.las.y <= lat_max + las_offset) 429 | ) 430 | self.las = self.las[lasmask] 431 | 432 | self.ul_lon = lon_min 433 | self.ul_lat = lat_max 434 | 435 | def get_tree_height_elevation(self, loc='top'): 436 | ''' Sets tree height and elevation in tree dataframe 437 | 438 | Parameters 439 | ---------- 440 | loc : str, optional 441 | initial or corrected tree top location: `top` or `top_cor` 442 | ''' 443 | lons, lats = self._tree_lonlat(loc) 444 | self.trees[f'{loc}_height'] = self._get_z( 445 | lons, lats, self.chm, self.resolution) 446 | self.trees[f'{loc}_elevation'] = self._get_z( 447 | lons, lats, self.dtm, self.resolution) 448 | 449 | def filter_chm(self, ws, ws_in_pixels=False, circular=False): 450 | ''' Pre-process the canopy height model (smoothing and outlier removal). 451 | The original CHM (self.chm0) is not overwritten, but a new one is 452 | stored (self.chm). 453 | 454 | Parameters 455 | ---------- 456 | ws : int 457 | window size of smoothing filter in metre (set in_pixel=True, otherwise) 458 | ws_in_pixels : bool, optional 459 | sets ws in pixel 460 | circular : bool, optional 461 | set to True for disc-shaped filter kernel, block otherwise 462 | ''' 463 | if not ws_in_pixels: 464 | if ws % self.resolution: 465 | raise Exception("Image filter size not an integer number. Please check if image resolution matches filter size (in metre or pixel).") 466 | else: 467 | ws = int(ws / self.resolution) 468 | 469 | self.chm = self._smooth_raster(self.chm0, ws, self.resolution, 470 | circular=circular) 471 | self.chm0[np.isnan(self.chm0)] = 0. 472 | zmask = (self.chm < 0.5) | np.isnan(self.chm) | (self.chm > 60.) 473 | self.chm[zmask] = 0 474 | 475 | def tree_detection(self, raster, resolution=None, ws=5, hmin=20, 476 | return_trees=False, ws_in_pixels=False): 477 | ''' Detect individual trees from CHM raster based on a maximum filter. 478 | Identified trees are either stores as list in the tree dataframe or 479 | returned as ndarray. 480 | 481 | Parameters 482 | ---------- 483 | raster : ndarray 484 | raster of height values (e.g., CHM) 485 | resolution : int, optional 486 | resolution of raster in m 487 | ws : float 488 | moving window size (in metre) to detect the local maxima 489 | hmin : float 490 | Minimum height of a tree. Threshold below which a pixel 491 | or a point cannot be a local maxima 492 | return_trees : bool 493 | set to True if detected trees shopuld be returned as 494 | ndarray instead of being stored in tree dataframe 495 | ws_in_pixels : bool 496 | sets ws in pixel 497 | 498 | Returns 499 | ------- 500 | ndarray (optional) 501 | nx2 array of tree top pixel coordinates 502 | ''' 503 | 504 | if not isinstance(raster, np.ndarray): 505 | raise Exception("Please provide an input raster as numpy ndarray.") 506 | 507 | resolution = resolution if resolution else self.resolution 508 | 509 | if not ws_in_pixels: 510 | if ws % resolution: 511 | raise Exception("Image filter size not an integer number. Please check if image resolution matches filter size (in metre or pixel).") 512 | else: 513 | ws = int(ws / resolution) 514 | 515 | # Maximum filter to find local peaks 516 | raster_maximum = filters.maximum_filter( 517 | raster, footprint=self._get_kernel(ws, circular=True)) 518 | tree_maxima = raster == raster_maximum 519 | 520 | # alternative using skimage peak_local_max 521 | # chm = inraster.copy() 522 | # chm[np.isnan(chm)] = 0. 523 | # tree_maxima = peak_local_max(chm, indices=False, footprint=kernel) 524 | 525 | # remove tree tops lower than minimum height 526 | tree_maxima[raster <= hmin] = 0 527 | 528 | # label each tree 529 | self.tree_markers, num_objects = ndimage.label(tree_maxima) 530 | 531 | if num_objects == 0: 532 | raise NoTreesException 533 | 534 | # if canopy height is the same for multiple pixels, 535 | # place the tree top in the center of mass of the pixel bounds 536 | yx = np.array( 537 | ndimage.center_of_mass( 538 | raster, self.tree_markers, range(1, num_objects+1) 539 | ), dtype=np.float32 540 | ) + 0.5 541 | xy = np.array((yx[:, 1], yx[:, 0])).T 542 | 543 | trees = [Point(*self._to_lonlat(xy[tidx, 0], xy[tidx, 1], resolution)) 544 | for tidx in range(len(xy))] 545 | 546 | if return_trees: 547 | return np.array(trees, dtype=object), xy 548 | else: 549 | df = pd.DataFrame(np.array([trees, trees], dtype='object').T, 550 | dtype='object', columns=['top_cor', 'top']) 551 | self.trees = self.trees.append(df) 552 | 553 | self._check_empty() 554 | 555 | def crown_delineation(self, algorithm, loc='top', **kwargs): 556 | """ Function calling external crown delineation algorithms 557 | 558 | Parameters 559 | ---------- 560 | algorithm : str 561 | crown delineation algorithm to be used, choose from: 562 | ['dalponte_cython', 'dalponte_numba', 563 | 'dalponteCIRC_numba', 'watershed_skimage'] 564 | loc : str, optional 565 | tree seed position: `top` or `top_cor` 566 | th_seed : float 567 | factor 1 for minimum height of tree crown 568 | th_crown : float 569 | factor 2 for minimum height of tree crown 570 | th_tree : float 571 | minimum height of tree seed (in m) 572 | max_crown : float 573 | maximum radius of tree crown (in m) 574 | 575 | Returns 576 | ------- 577 | ndarray 578 | raster of individual tree crowns 579 | """ 580 | timeit = 'Tree crowns delineation: {:.3f}s' 581 | 582 | # get the tree seeds (starting points for crown delineation) 583 | seeds = self._tree_colrow(loc, self.resolution) 584 | inraster = kwargs.get('inraster') 585 | 586 | if not isinstance(inraster, np.ndarray): 587 | inraster = self.chm 588 | else: 589 | inraster = inraster 590 | 591 | if kwargs.get('max_crown'): 592 | max_crown = kwargs['max_crown'] / self.resolution 593 | 594 | if algorithm == 'dalponte_cython': 595 | tt = time.time() 596 | crowns = _crown_dalponte_cython._crown_dalponte( 597 | inraster, seeds, 598 | th_seed=float(kwargs['th_seed']), 599 | th_crown=float(kwargs['th_crown']), 600 | th_tree=float(kwargs['th_tree']), 601 | max_crown=float(max_crown) 602 | ) 603 | print(timeit.format(time.time() - tt)) 604 | 605 | elif algorithm == 'dalponte_numba': 606 | tt = time.time() 607 | crowns = _crown_dalponte_numba._crown_dalponte( 608 | inraster, seeds, 609 | th_seed=float(kwargs['th_seed']), 610 | th_crown=float(kwargs['th_crown']), 611 | th_tree=float(kwargs['th_tree']), 612 | max_crown=float(max_crown) 613 | ) 614 | print(timeit.format(time.time() - tt)) 615 | 616 | elif algorithm == 'dalponteCIRC_numba': 617 | tt = time.time() 618 | crowns = _crown_dalponteCIRC_numba._crown_dalponteCIRC( 619 | inraster, seeds, 620 | th_seed=float(kwargs['th_seed']), 621 | th_crown=float(kwargs['th_crown']), 622 | th_tree=float(kwargs['th_tree']), 623 | max_crown=float(max_crown) 624 | ) 625 | print(timeit.format(time.time() - tt)) 626 | 627 | elif algorithm == 'watershed_skimage': 628 | tt = time.time() 629 | crowns = self._watershed( 630 | inraster, th_tree=float(kwargs['th_tree']) 631 | ) 632 | print(timeit.format(time.time() - tt)) 633 | 634 | self.crowns = np.array(crowns, dtype=np.int32) 635 | 636 | def clip_trees_to_bbox(self, bbox=None, inbuf=None, f_tiles=None, row=None, 637 | col=None, loc='top'): 638 | """ Clip tree tops and crowns to bounding box or tile extent. 639 | Tree dataframe is updated with subset of trees. 640 | 641 | Parameters 642 | ---------- 643 | bbox : tuple, optional 644 | floats for (lon_min, lon_max, lat_min, lat_max) 645 | inbuf : integer or float, optional 646 | distance of inward buffer in metres 647 | f_tiles : str, optional 648 | Path to LiDAR tiles polygon with coordinates for all 649 | bounding boxes for each tile 650 | row : int, optional 651 | row number of tile 652 | col : int, optional 653 | column number of tile 654 | loc : str, optional 655 | tree seed position: `top` or `top_cor` 656 | """ 657 | if bbox: 658 | lon_min, lon_max, lat_min, lat_max = bbox 659 | elif inbuf: 660 | lat_max = self.ul_lat - inbuf 661 | lat_min = self.ul_lat - (self.chm.shape[0] * self.resolution) - inbuf 662 | lon_min = self.ul_lon + inbuf 663 | lon_max = self.ul_lon + (self.chm.shape[1] * self.resolution) - inbuf 664 | elif f_tiles: 665 | # get the bounding box of each tile 666 | with fiona.open(f_tiles, 'r') as tilepolys_layer: 667 | tiles = {} 668 | for tile in tilepolys_layer: 669 | r = tile['properties']['Row'] 670 | c = tile['properties']['Col'] 671 | lon_min = tile['geometry']['coordinates'][0][0][0] 672 | lat_min = tile['geometry']['coordinates'][0][0][1] 673 | lon_max = tile['geometry']['coordinates'][0][2][0] 674 | lat_max = tile['geometry']['coordinates'][0][1][1] 675 | tiles[r, c] = lon_min, lat_min, lon_max, lat_max 676 | 677 | # identify and clip tree tops inside tile 678 | lon_min, lat_min, lon_max, lat_max = tiles[row, col] 679 | else: 680 | raise Exception("No clipping method specified.") 681 | 682 | tree_lons, tree_lats = self._tree_lonlat(loc) 683 | cond = ( 684 | (tree_lons >= lon_min) & (tree_lons < lon_max) & 685 | (tree_lats >= lat_min) & (tree_lats < lat_max) 686 | ) 687 | self.trees = self.trees[cond] 688 | 689 | if isinstance(self.crowns, np.ndarray): 690 | self._screen_crowns(cond) 691 | 692 | def correct_tree_tops(self, check_all=False): 693 | """ Correct the location of tree tops in steep terrain. 694 | Tree dataframe is updated with corrected tree top positions (`top_cor`). 695 | 696 | Parameters 697 | ---------- 698 | check_all : bool, optional 699 | set to True if all trees should be corrected, ignoring 700 | whether they are located on steep terrain 701 | """ 702 | 703 | print(f'Number of trees: {len(self.trees)}') 704 | 705 | # calculate center of mass of crowns 706 | comass = np.array( 707 | ndimage.center_of_mass(self.crowns, self.crowns, 708 | range(1, self.crowns.max() + 1)) 709 | ) 710 | 711 | corr_n = 0 712 | corr_dsm = 0 713 | corr_com = 0 714 | 715 | for tidx in range(len(self.trees)): 716 | tree = self.trees.iloc[tidx] 717 | col, row = self._to_colrow(tree['top'].x, tree['top'].y, 718 | self.resolution) 719 | rcindices = np.where(self.crowns == tidx + 1) 720 | dtm_mean = np.nanmean(self.dtm[rcindices]) 721 | dtm_std = np.nanstd(self.dtm[rcindices]) 722 | dsm_max = np.nanmax(self.dsm[rcindices]) 723 | 724 | if np.isnan(dtm_mean) or np.isnan(dsm_max): 725 | self.trees.tt_corrected.iloc[tidx] = -1 726 | continue 727 | 728 | # check if tree top too far down-slope compared to crown_mean 729 | if self.dtm[row, col] <= (dtm_mean - dtm_std) or check_all: 730 | 731 | # find highest DSM location in crown 732 | midx = np.where(self.dsm[rcindices] == dsm_max)[0][0] 733 | dsmhigh = np.array((rcindices[0][midx] + 0.5, 734 | rcindices[1][midx] + 0.5)) 735 | 736 | # calculate map distances 737 | distances = cdist(np.stack(rcindices, axis=1), 738 | comass[tidx][np.newaxis]) 739 | dist_dh_com = cdist(dsmhigh[np.newaxis], 740 | comass[tidx][np.newaxis]) 741 | 742 | # assign high point position from DSM if new location is not 743 | # too far from centre of mass of the crown, in the latter case 744 | # place the tree top at the centre of mass 745 | corr_n += 1 746 | 747 | if dist_dh_com <= (1. * np.nanmean(distances)): 748 | cor_col, cor_row = dsmhigh[1], dsmhigh[0] 749 | corr_dsm += 1 750 | self.trees.tt_corrected.iloc[tidx] = 1 751 | else: 752 | cor_col, cor_row = comass[tidx][1], comass[tidx][0] 753 | corr_com += 1 754 | self.trees.tt_corrected.iloc[tidx] = 2 755 | 756 | # Set new tree top height 757 | self.trees.top_cor.iloc[tidx] = \ 758 | Point(*self._to_lonlat(cor_col, cor_row, self.resolution)) 759 | 760 | else: 761 | self.trees.tt_corrected.iloc[tidx] = 0 762 | 763 | print(f'Tree tops corrected: {corr_n}') 764 | if len(self.trees) > 0: 765 | print(f'Tree tops corrected: {100 * corr_n / len(self.trees)}%') 766 | print(f'DSM correction: {corr_dsm}') 767 | print(f'COM correction: {corr_com}') 768 | return corr_dsm, corr_com 769 | 770 | def screen_small_trees(self, hmin=20., loc='top'): 771 | """ Remove small trees from index based on minimum threshold. 772 | Tree dataframe and crowns raster is updated. 773 | 774 | Parameters 775 | ---------- 776 | hmin : float 777 | minimum height of tree top 778 | loc : str, optional 779 | tree seed position: `top` or `top_cor` 780 | """ 781 | cond = self.trees[f'{loc}_height'] >= hmin 782 | self.trees = self.trees[cond] 783 | 784 | if isinstance(self.crowns, np.ndarray): 785 | self._screen_crowns(cond) 786 | 787 | self._check_empty() 788 | 789 | def crowns_to_polys_raster(self): 790 | ''' Converts tree crown raster to individual polygons and stores them 791 | in the tree dataframe 792 | ''' 793 | polys = [] 794 | for feature in rioshapes(self.crowns, mask=self.crowns.astype(bool)): 795 | 796 | # Convert pixel coordinates to lon/lat 797 | edges = feature[0]['coordinates'][0].copy() 798 | for i in range(len(edges)): 799 | edges[i] = self._to_lonlat(*edges[i], self.resolution) 800 | 801 | # poly_smooth = self.smooth_poly(Polygon(edges), s=None, k=9) 802 | polys.append(Polygon(edges)) 803 | self.trees.crown_poly_raster = polys 804 | 805 | def crowns_to_polys_smooth(self, store_las=True, thin_perc=None, 806 | first_return=True): 807 | """ Smooth crown polygons using Dalponte & Coomes (2016) approach: 808 | Builds a convex hull around first return points (which lie within the 809 | rasterized crowns). 810 | Optionally, the trees in the LiDAR point cloud are classified based on 811 | the generated convex hull. 812 | 813 | Parameters 814 | ---------- 815 | store_las : bool 816 | set to True if LiDAR point clouds shopuld be classified 817 | and stored externally 818 | thin_perc : None or int 819 | percentage amount by how much the point cloud should be 820 | thinned out randomly 821 | first_return : bool 822 | use first return points to create convex hull (all 823 | points otherwise) 824 | """ 825 | 826 | if thin_perc: 827 | thin_size = floor(len(self.las) * (1 - thin_perc)) 828 | lidar_geodf = self.las.sample(n=thin_size) 829 | else: 830 | lidar_geodf = self.las 831 | 832 | print('Converting LAS point cloud to shapely points') 833 | geometry = [Point(xy) for xy in zip(lidar_geodf.x, lidar_geodf.y)] 834 | lidar_geodf = gpd.GeoDataFrame(lidar_geodf, crs=f'epsg:{self.epsg}', 835 | geometry=geometry) 836 | 837 | print('Converting raster crowns to shapely polygons') 838 | polys = [] 839 | for feature in rioshapes(self.crowns, mask=self.crowns.astype(bool)): 840 | edges = np.array(list(zip(*feature[0]['coordinates'][0]))) 841 | edges = np.array(self._to_lonlat(edges[0], edges[1], 842 | self.resolution)).T 843 | polys.append(Polygon(edges)) 844 | crown_geodf = gpd.GeoDataFrame( 845 | pd.DataFrame(np.arange(len(self.trees))), 846 | crs=f'epsg:{self.epsg}', geometry=polys 847 | ) 848 | 849 | print('Attach LiDAR points to corresponding crowns') 850 | lidar_in_crowns = gpd.sjoin(lidar_geodf, crown_geodf, 851 | op='within', how="inner") 852 | 853 | lidar_tree_class = np.zeros(lidar_in_crowns['index_right'].size) 854 | lidar_tree_mask = np.zeros(lidar_in_crowns['index_right'].size, 855 | dtype=bool) 856 | 857 | print('Create convex hull around first return points') 858 | polys = [] 859 | for tidx in range(len(self.trees)): 860 | bool_indices = lidar_in_crowns['index_right'] == tidx 861 | lidar_tree_class[bool_indices] = tidx 862 | points = lidar_in_crowns[bool_indices] 863 | # check that not all values are the same 864 | if len(points.z) > 1 and not np.allclose(points.z, 865 | points.iloc[0].z): 866 | points = points[points.z >= threshold_otsu(points.z)] 867 | if first_return: 868 | points = points[points.return_num == 1] # first returns 869 | hull = points.unary_union.convex_hull 870 | polys.append(hull) 871 | lidar_tree_mask[bool_indices] = \ 872 | lidar_in_crowns[bool_indices].within(hull) 873 | self.trees.crown_poly_smooth = polys 874 | 875 | if store_las: 876 | print('Classifying point cloud') 877 | lidar_in_crowns = lidar_in_crowns[lidar_tree_mask] 878 | lidar_tree_class = lidar_tree_class[lidar_tree_mask] 879 | header = laspy.header.Header() 880 | self.outpath.mkdir(parents=True, exist_ok=True) 881 | outfile = laspy.file.File( 882 | self.outpath / "trees.las", mode="w", header=header 883 | ) 884 | xmin = np.floor(np.min(lidar_in_crowns.x)) 885 | ymin = np.floor(np.min(lidar_in_crowns.y)) 886 | zmin = np.floor(np.min(lidar_in_crowns.z)) 887 | outfile.header.offset = [xmin, ymin, zmin] 888 | outfile.header.scale = [0.001, 0.001, 0.001] 889 | outfile.x = lidar_in_crowns.x 890 | outfile.y = lidar_in_crowns.y 891 | outfile.z = lidar_in_crowns.z 892 | outfile.intensity = lidar_tree_class 893 | outfile.close() 894 | 895 | self.lidar_in_crowns = lidar_in_crowns 896 | 897 | def quality_control(self, all_good=False): 898 | """ Remove trees from tree dataframe with missing DTM/DSM data & 899 | crowns that are not polygons 900 | 901 | Parameters 902 | ---------- 903 | all_good : bool 904 | set to True if all trees should pass the quality check 905 | """ 906 | if all_good: 907 | self.trees.tt_corrected = np.zeros(len(self.trees), dtype=int) 908 | else: 909 | cond = ( 910 | (self.trees.tt_corrected >= 0) & 911 | self.trees.crown_poly_raster.apply( 912 | lambda x: isinstance(x, Polygon)) 913 | ) 914 | self.trees = self.trees[cond] 915 | 916 | self._check_empty() 917 | 918 | def export_tree_locations(self, loc='top'): 919 | """ Convert tree top raster indices to georeferenced 3D point shapefile 920 | 921 | Parameters 922 | ---------- 923 | loc : str, optional 924 | tree seed position: `top` or `top_cor` 925 | """ 926 | outfile = self.outpath / f'tree_location_{loc}.shp' 927 | outfile.parent.mkdir(parents=True, exist_ok=True) 928 | 929 | if outfile.exists(): 930 | outfile.unlink() 931 | 932 | schema = { 933 | 'geometry': '3D Point', 934 | 'properties': {'DN': 'int', 'TH': 'float', 'COR': 'int'} 935 | } 936 | with fiona.collection( 937 | str(outfile), 'w', 'ESRI Shapefile', schema, crs=self.srs 938 | ) as output: 939 | for tidx in range(len(self.trees)): 940 | feat = {} 941 | tree = self.trees.iloc[tidx] 942 | feat['geometry'] = mapping( 943 | Point(tree[loc].x, tree[loc].y, tree[f'{loc}_elevation']) 944 | ) 945 | feat['properties'] = {'DN': tidx, 946 | 'TH': float(tree[f'{loc}_height']), 947 | 'COR': int(tree.tt_corrected)} 948 | output.write(feat) 949 | 950 | def export_tree_crowns(self, crowntype='crown_poly_smooth'): 951 | """ Convert tree crown raster to georeferenced polygon shapefile 952 | 953 | Parameters 954 | ---------- 955 | crowntype : str, optional 956 | choose whether the raster of smoothed version should be 957 | exported: `crown_poly_smooth` or `crown_poly_raster` 958 | """ 959 | outfile = self.outpath / f'tree_{crowntype}.shp' 960 | outfile.parent.mkdir(parents=True, exist_ok=True) 961 | 962 | if outfile.exists(): 963 | outfile.unlink() 964 | 965 | schema = { 966 | 'geometry': 'Polygon', 967 | 'properties': {'DN': 'int', 'TTH': 'float', 'TCH': 'float'} 968 | } 969 | with fiona.collection( 970 | str(outfile), 'w', 'ESRI Shapefile', 971 | schema, crs=self.srs 972 | ) as output: 973 | for tidx in range(len(self.trees)): 974 | feat = {} 975 | tree = self.trees.iloc[tidx] 976 | feat['geometry'] = mapping(tree[crowntype]) 977 | feat['properties'] = { 978 | 'DN': tidx, 979 | 'TTH': float(tree.top_height), 980 | 'TCH': float(tree.top_cor_height) 981 | } 982 | output.write(feat) 983 | 984 | def export_raster(self, raster, fname, title, res=None): 985 | """ Write array to raster file with gdal 986 | 987 | Parameters 988 | ---------- 989 | raster : ndarray 990 | raster to be exported 991 | fname : str 992 | file name 993 | title : str 994 | gdal title of the file 995 | res : int/float, optional 996 | resolution of the raster in m, if not provided the same as 997 | the input CHM 998 | """ 999 | res = res if res else self.resolution 1000 | 1001 | fname.parent.mkdir(parents=True, exist_ok=True) 1002 | 1003 | driver = gdal.GetDriverByName('GTIFF') 1004 | y_pixels, x_pixels = raster.shape 1005 | gdal_file = driver.Create( 1006 | f'{fname}', x_pixels, y_pixels, 1, gdal.GDT_Float32 1007 | ) 1008 | gdal_file.SetGeoTransform( 1009 | (self.ul_lon, res, 0., self.ul_lat, 0., -res) 1010 | ) 1011 | dataset_srs = gdal.osr.SpatialReference() 1012 | dataset_srs.ImportFromEPSG(self.epsg) 1013 | gdal_file.SetProjection(dataset_srs.ExportToWkt()) 1014 | band = gdal_file.GetRasterBand(1) 1015 | band.SetDescription(title) 1016 | band.SetNoDataValue(0.) 1017 | band.WriteArray(raster) 1018 | gdal_file.FlushCache() 1019 | gdal_file = None 1020 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | numpy>=1.14.5 2 | scipy==1.1.0 3 | scikit-image>=0.14.0 4 | Cython>=0.28.4 5 | numba>=0.39.0 6 | pandas==0.23.3 7 | geopandas==0.3.0 8 | Rtree>=0.8.3 9 | Fiona>=1.7.10 10 | laspy>=1.5.1 11 | GDAL>=2.2.2 12 | Shapely>=1.6.4 13 | rasterio>=0.36.0 14 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # ============================================================================== 2 | # PyCrown - Fast raster-based individual tree segmentation for LiDAR data 3 | # ------------------------------------------------------------------------------ 4 | # Copyright: 2018, Jan Zörner 5 | # Licence: GNU GPLv3 6 | # ============================================================================== 7 | 8 | import os 9 | import setuptools 10 | from distutils.core import setup 11 | from distutils.extension import Extension 12 | from Cython.Build import cythonize 13 | import numpy as np 14 | 15 | 16 | with open('requirements.txt') as requirements_file: 17 | requirements = requirements_file.read().splitlines() 18 | 19 | extensions = [ 20 | Extension( 21 | 'pycrown._crown_dalponte_cython', 22 | sources=['pycrown/_crown_dalponte_cython.pyx'], 23 | include_dirs=[np.get_include()], 24 | optional=True 25 | ) 26 | ] 27 | 28 | setup( 29 | name='PyCrown', 30 | ext_modules=cythonize(extensions), 31 | version='0.2', 32 | test_suite='tests', 33 | packages=['pycrown'], 34 | install_requires=requirements, 35 | license='MIT', 36 | author='Dr. Jan Zörner', 37 | author_email='zoernerj@landcareresearch.co.nz', 38 | description="Fast Raster-based Tree Crown Segmentation" 39 | ) 40 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manaakiwhenua/pycrown/3d8db4e03d82d5846ff68fc5fa9c18803d823464/tests/__init__.py -------------------------------------------------------------------------------- /tests/base_test.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from pycrown import PyCrown 3 | 4 | class TestExampleNoLAS(unittest.TestCase): 5 | 6 | def setUp(self): 7 | ''' initialize test scenario ''' 8 | F_CHM = 'example/data/CHM.tif' 9 | F_DTM = 'example/data/DTM.tif' 10 | F_DSM = 'example/data/DSM.tif' 11 | self.PC = PyCrown(F_CHM, F_DTM, F_DSM, outpath="./") 12 | 13 | def test_treedetection_without_smoothing(self): 14 | self.PC.tree_detection(self.PC.chm0, ws=5, hmin=16.) 15 | self.assertGreater(self.PC.trees.size, 0) 16 | 17 | def test_treedetection_with_smoothing(self): 18 | self.PC.filter_chm(5) 19 | self.PC.tree_detection(self.PC.chm, ws=5, hmin=16.) 20 | self.assertGreater(self.PC.trees.size, 0) 21 | 22 | def test_crowndelineation(self): 23 | self.PC.filter_chm(5) 24 | self.PC.tree_detection(self.PC.chm, ws=5, hmin=16.) 25 | self.PC.crown_delineation( 26 | algorithm='dalponteCIRC_numba', th_tree=15., 27 | th_seed=0.7, th_crown=0.55, max_crown=10. 28 | ) 29 | self.PC.correct_tree_tops() 30 | self.PC.get_tree_height_elevation(loc='top') 31 | self.PC.get_tree_height_elevation(loc='top_cor') 32 | self.PC.screen_small_trees(hmin=20., loc='top') 33 | self.PC.crowns_to_polys_raster() 34 | self.PC.quality_control() 35 | 36 | 37 | if __name__ == '__main__': 38 | unittest.main() 39 | -------------------------------------------------------------------------------- /tests/treetopcorrection_test.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from pycrown import PyCrown 3 | 4 | 5 | class TestTreeTopCorrection(unittest.TestCase): 6 | 7 | def setUp(self): 8 | ''' initialize test scenario ''' 9 | F_CHM = 'example/data/CHM.tif' 10 | F_DTM = 'example/data/DTM.tif' 11 | F_DSM = 'example/data/DSM.tif' 12 | F_LAS = 'example/data/POINTS.las' 13 | self.PC = PyCrown(F_CHM, F_DTM, F_DSM, F_LAS) 14 | self.PC.filter_chm(5) 15 | self.PC.tree_detection(self.PC.chm, ws=5, hmin=16.) 16 | self.PC.clip_trees_to_bbox(bbox=(1802160, 1802400, 5467315, 5467470)) 17 | self.PC.crown_delineation(algorithm='dalponteCIRC_numba', th_tree=15., 18 | th_seed=0.7, th_crown=0.55, max_crown=10.) 19 | self.PC.get_tree_height_elevation() 20 | 21 | def test_number_corrected_trees(self): 22 | ''' test the number of corrected trees per method: 23 | A: DSM top positon, B: centre of mass of tree crown ''' 24 | corr_dsm, corr_com = self.PC.correct_tree_tops() 25 | self.assertEqual(corr_dsm, 5) 26 | self.assertEqual(corr_com, 4) 27 | 28 | def test_tree_height_corrected_trees(self): 29 | ''' test that the corrected tree heights are on average lower than 30 | the original tree heights (based on assumption that trees are situated 31 | on steep terrain and or crowns overwang cliff edges) ''' 32 | _, _ = self.PC.correct_tree_tops() 33 | self.PC.get_tree_height_elevation(loc='top') 34 | self.PC.get_tree_height_elevation(loc='top_cor') 35 | 36 | trees = self.PC.trees[self.PC.trees.tt_corrected > 0.] 37 | 38 | dsm_corrected = trees.tt_corrected == 1. 39 | differences_dsm_correction = (trees.top_cor_height[dsm_corrected] - 40 | trees.top_height[dsm_corrected]) 41 | self.assertTrue(differences_dsm_correction.mean() < 0.) 42 | 43 | com_corrected = trees.tt_corrected == 2. 44 | differences_com_correction = (trees.top_cor_height[com_corrected] - 45 | trees.top_height[com_corrected]) 46 | self.assertTrue(differences_com_correction.mean() < 0.) 47 | 48 | 49 | if __name__ == '__main__': 50 | unittest.main() 51 | --------------------------------------------------------------------------------