├── CMakeLists.txt ├── LICENSE ├── README.md ├── config └── eklt.conf ├── dependencies.yaml ├── images ├── errors.png ├── feature_tracks_preview.png └── thumbnail.png ├── include ├── error.h ├── optimizer.h ├── patch.h ├── tracker.h ├── types.h └── viewer.h ├── launch └── eklt.launch ├── package.xml └── src ├── eklt_node.cpp ├── optimizer.cpp ├── tracker.cpp └── viewer.cpp /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 2.8.3) 2 | project(eklt) 3 | 4 | find_package(catkin_simple REQUIRED) 5 | find_package(OpenCV REQUIRED) 6 | catkin_simple(ALL_DEPS_REQUIRED) 7 | 8 | SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -O3 -fopenmp") 9 | SET(CMAKE_BUILD_TYPE Release) 10 | 11 | set(HEADERS 12 | include/error.h 13 | include/optimizer.h 14 | include/patch.h 15 | include/tracker.h 16 | include/viewer.h 17 | ) 18 | 19 | set(SOURCES 20 | src/optimizer.cpp 21 | src/tracker.cpp 22 | src/viewer.cpp 23 | ) 24 | 25 | cs_add_library(${PROJECT_NAME} ${SOURCES} ${HEADERS}) 26 | 27 | # make executable 28 | cs_add_executable(eklt_node src/eklt_node.cpp) 29 | target_link_libraries(eklt_node ${PROJECT_NAME} ${OpenCV_LIBRARIES} ${catkin_LIBRARIES}) 30 | 31 | cs_install() 32 | cs_export() -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # EKLT: Asynchronous, Photometric Feature Tracking using Events and Frames 2 | [](https://youtu.be/ZyD1YPW1h4U) 3 | 4 | This repository implements the work in the 2019 IJCV paper [**EKLT: Asynchronous, Photometric Feature Tracking using Events and Frames**](http://rpg.ifi.uzh.ch/docs/IJCV19_Gehrig.pdf) by [Daniel Gehrig](https://danielgehrig18.github.io/), [Henri Rebecq](http://henri.rebecq.fr), [Guillermo Gallego](http://www.guillermogallego.es), and [Davide Scaramuzza](http://rpg.ifi.uzh.ch/people_scaramuzza.html). 5 | Also check out our feature tracking evaluation package [here](https://github.com/uzh-rpg/rpg_feature_tracking_analysis). 6 | 7 | ### Citation 8 | A pdf of the paper is [available here](http://rpg.ifi.uzh.ch/docs/IJCV19_Gehrig.pdf). If you use any of this code, please cite this publication as follows: 9 | 10 | ```bibtex 11 | @Article{Gehrig19ijcv, 12 | author = {Daniel Gehrig and Henri Rebecq and Guillermo Gallego and 13 | Davide Scaramuzza}, 14 | title = {{EKLT}: Asynchronous, Photometric Feature Tracking using Events and Frames}, 15 | journal = "Int. J. Comput. Vis.", 16 | year = 2019, 17 | } 18 | ``` 19 | ## Overview 20 | 21 | EKLT works by leveraging the complementarity between events and frames for feature tracking. Using the events, it manages to track in the blind-time between two frames. First features are extracted on the frames and then tracked using only the events. The tracker then produces asynchronous feature tracks with high temporal resolution. More 22 | details can be found in the [paper](http://rpg.ifi.uzh.ch/docs/IJCV19_Gehrig.pdf) and [video](https://youtu.be/ZyD1YPW1h4U). 23 | 24 | ## Installation 25 | 26 | This code was tested on [ROS melodic](http://wiki.ros.org/melodic/Installation) and [ROS kinetic](http://wiki.ros.org/kinetic/Installation). 27 | Install [catkin tools](http://catkin-tools.readthedocs.org/en/latest/installing.html) and [vcstool](https://github.com/dirk-thomas/vcstool) if needed: 28 | 29 | sudo apt install python-catkin-tools python-vcstool 30 | 31 | Create a new catkin workspace if needed: 32 | 33 | mkdir -p catkin_ws/src 34 | cd catkin_ws 35 | catkin config --init --mkdirs --extend /opt/ros/melodic --cmake-args -DCMAKE_BUILD_TYPE=Release 36 | 37 | Then clone the repo and all its dependencies using vcs-import 38 | 39 | cd src 40 | git clone git@github.com:uzh-rpg/rpg_eklt.git 41 | vcs-import < rpg_eklt/dependencies.yaml 42 | 43 | Finally, build the project and then source the workspace 44 | 45 | catkin build eklt 46 | source ~/catkin_ws/devel/setup.bash 47 | 48 | ## Running Example 49 | 50 | Download [boxes_6dof](http://rpg.ifi.uzh.ch/datasets/davis/boxes_6dof.bag) from the [Event Camera Dataset](http://rpg.ifi.uzh.ch/davis_data.html) which was recorded using the [DVS ROS driver](https://github.com/uzh-rpg/rpg_dvs_ros) into a new directory 51 | 52 | cd /tmp/ 53 | wget http://rpg.ifi.uzh.ch/datasets/eklt_example.zip 54 | unzip eklt_example.zip 55 | rm eklt_example.zip 56 | 57 | Run EKLT with the following command: 58 | 59 | roslaunch eklt eklt.launch tracks_file_txt:=/tmp/eklt_example/tracks.txt v:=1 60 | 61 | In a separate terminal play the rosbag: 62 | 63 | rosbag play /tmp/eklt_example/boxes_6dof.bag 64 | 65 | **Configuration parameters**: 66 | Configuration parameters for eklt can be viewed by running the following command in a sourced terminal: 67 | 68 | rosrun eklt eklt_node --help 69 | 70 | The individual parameters can be changed in `config/eklt.conf`. In particular, the parameter `min_corners` has been set to 0 which makes it such that no new features are initialized after the first image. This configuration was used in the paper. However, for continuous tracking you can set this value higher (50 is a good number). 71 | Additional optional parameters can be set through the launch file `eklt.launch`: 72 | 73 | * `v:=1` verbosity level of `VLOG` from the `glog` library 74 | * `bag:=/path/to.bag`: path to the bag which will be used to perform evalution 75 | * `tracks_file_txt:=/path/to/file.txt`: path to output file where feature tracks will be stored. 76 | 77 | ## Evaluation 78 | 79 | The tracks file generated by the prevous command contains all of the information necessary to reconstruct feature tracks. The feature tracks are stored in the following format: 80 | 81 | |feature id| timestamp | x | y | 82 | |:--------:|:------------------:|:-----:|:-----:| 83 | |0 |1468940293.922985274|187.032|132.671| 84 | |2 |1468940293.958816290|204.603|105.36 | 85 | |1 |1468940293.957388878|222.378|104.176| 86 | |0 |1468940293.964686394|223.596|19.1384| 87 | |1 |1468940293.960546732|182.122|52.1019| 88 | |2 |1468940293.960608244|172.227|47.1469| 89 | 90 | These feature tracks can be used directly for evaluation with [this feature tracking analysis package](https://github.com/uzh-rpg/rpg_feature_tracking_analysis). First clone the repo into your workspace 91 | 92 | cd ~/catkin_ws/src 93 | git clone git@github.com:uzh-rpg/rpg_feature_tracking_analysis.git 94 | 95 | and run the following command 96 | 97 | python ~/catkin_ws/src/rpg_feature_tracking_analysis/evaluate_tracks.py --error_threshold 10 --tracker_type KLT --file /tmp/eklt_example/tracks.txt --dataset /tmp/eklt_example/dataset.yaml --root /tmp/eklt_example/ --plot_errors 98 | 99 | A preview of the output (stored in `/tmp/eklt_example/results/errors.pdf`) is shown below. In addition, the tracking error and feature age are stored in `/tmp/eklt_example/results/errors.txt` and `/tmp/eklt_example/results/feature_age.txt` respectively. 100 | 101 | 102 | 103 | ## Visualization 104 | 105 | When running the example a visualization of the feature tracks is publisher to the topic `/feature_tracks` 106 | 107 | 108 | 109 | The visualization shows the features projected on to the current frames together with their flow angle estimate (blue arrow). Changing the flags `display_features`, `display_feature_id` and `display_feature_patches` toggle the display of the features, feature ids and feature patches respectively. 110 | 111 | ## Additional Resources on Event Cameras 112 | 113 | * [Event-based Vision Survey](http://rpg.ifi.uzh.ch/docs/EventVisionSurvey.pdf) 114 | * [List of Event-based Vision Resources](https://github.com/uzh-rpg/event-based_vision_resources) 115 | * [Event Camera Dataset](http://rpg.ifi.uzh.ch/davis_data.html) 116 | * [Event Camera Simulator](http://rpg.ifi.uzh.ch/esim) 117 | * [RPG research page on Event Cameras](http://rpg.ifi.uzh.ch/research_dvs.html) 118 | * [EKLT Conference paper, ECCV'18](http://rpg.ifi.uzh.ch/docs/ECCV18_Gehrig.pdf) 119 | -------------------------------------------------------------------------------- /config/eklt.conf: -------------------------------------------------------------------------------- 1 | --batch_size=300 2 | --update_every_n_events=30 3 | --displacement_px=0.6 4 | --patch_size=25 5 | --max_num_iterations=10 6 | --tracking_quality=0.6 7 | --bootstrap="klt" 8 | --lk_window_size=20 9 | --num_pyramidal_layers=3 10 | 11 | --scale=4 12 | --display_features=true 13 | --display_feature_id=false 14 | --display_feature_patches=false 15 | --update_every_n_events=20 16 | --arrow_length=5 17 | 18 | --max_corners=100 19 | --min_corners=0 20 | --min_distance=10 21 | --quality_level=0.01 22 | --block_size=3 23 | --k=0.04 24 | 25 | --first_image_t=-1 26 | --tracks_file_txt= 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /dependencies.yaml: -------------------------------------------------------------------------------- 1 | repositories: 2 | ceres_catkin: 3 | type: git 4 | url: git@github.com:ethz-asl/ceres_catkin.git 5 | version: master 6 | rpg_dvs_ros: 7 | type: git 8 | url: git@github.com:uzh-rpg/rpg_dvs_ros.git 9 | version: master 10 | suitesparse: 11 | type: git 12 | url: git@github.com:ethz-asl/suitesparse.git 13 | version: master 14 | cmake_external_project_catkin: 15 | type: git 16 | url: git@github.com:zurich-eye/cmake_external_project_catkin.git 17 | version: master 18 | catkin_simple: 19 | type: git 20 | url: git@github.com:catkin/catkin_simple.git 21 | version: master 22 | gflags_catkin: 23 | type: git 24 | url: git@github.com:ethz-asl/gflags_catkin.git 25 | version: master 26 | glog_catkin: 27 | type: git 28 | url: git@github.com:ethz-asl/glog_catkin.git 29 | version: master 30 | eigen_checks: 31 | type: git 32 | url: git@github.com:ethz-asl/eigen_checks.git 33 | version: master 34 | eigen_catkin: 35 | type: git 36 | url: git@github.com:ethz-asl/eigen_catkin.git 37 | version: master -------------------------------------------------------------------------------- /images/errors.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uzh-rpg/rpg_eklt/037b0b3021ff9973e62aff066216f0ef11afb22a/images/errors.png -------------------------------------------------------------------------------- /images/feature_tracks_preview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uzh-rpg/rpg_eklt/037b0b3021ff9973e62aff066216f0ef11afb22a/images/feature_tracks_preview.png -------------------------------------------------------------------------------- /images/thumbnail.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uzh-rpg/rpg_eklt/037b0b3021ff9973e62aff066216f0ef11afb22a/images/thumbnail.png -------------------------------------------------------------------------------- /include/error.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | #include "types.h" 8 | 9 | 10 | namespace nlls 11 | { 12 | /** 13 | * @brief Config which contains all the arguments that are used to compute the loss. 14 | */ 15 | struct CostFunctionConfig 16 | { 17 | CostFunctionConfig(cv::Point2d feature, 18 | cv::Point2d init_feature, 19 | const cv::Mat* event_frame, 20 | Interpolator* grad_interp) 21 | :feature_(feature), event_frame_(event_frame), grad_interp_(grad_interp), init_feature_(init_feature) 22 | { 23 | patch_size_ = event_frame_->size[0]; 24 | half_size_ = (event_frame_->size[0]-1)/2; 25 | size_ = patch_size_*patch_size_; 26 | norm_event_frame_ = cv::norm(*event_frame_); 27 | } 28 | 29 | cv::Point2d feature_; 30 | cv::Point2d init_feature_; 31 | const cv::Mat* event_frame_; 32 | 33 | int patch_size_; 34 | int half_size_; 35 | int size_; 36 | int height_; 37 | int width_; 38 | 39 | Interpolator* grad_interp_; 40 | 41 | double norm_event_frame_; 42 | }; 43 | 44 | /** 45 | * @brief Implements the cost function in equation (7) of the paper. 46 | */ 47 | struct ErrorRotation 48 | { 49 | 50 | ErrorRotation(CostFunctionConfig* config) : config_(config) {} 51 | 52 | static void getP0(double p[], const cv::Mat& warp) 53 | { 54 | p[0] = std::atan2(warp.at(1,0), warp.at(0,0)); 55 | p[1] = warp.at(0,2); 56 | p[2] = warp.at(1,2); 57 | } 58 | 59 | static void getWarp(double p0[], cv::Mat& warp) 60 | { 61 | warp = (cv::Mat_(3,3) << std::cos(p0[0]), -std::sin(p0[0]), p0[1], 62 | std::sin(p0[0]), std::cos(p0[0]), p0[2], 63 | 0, 0, 1); 64 | } 65 | 66 | template 67 | bool operator()(const T* p, const T* v, T* residual) const 68 | { 69 | // warp image gradient 70 | T norm_sq(1e-3); 71 | warp(p, v, residual, norm_sq); 72 | 73 | // compute loss function in equation (7) of the paper 74 | // we need to do 2 passes since we need to normalize by the gradient 75 | for (int i=0;isize_;i++) 76 | { 77 | residual[i] = residual[i] / ceres::sqrt(norm_sq) + 78 | config_->event_frame_->at(i / config_->patch_size_, i % config_->patch_size_) / config_->norm_event_frame_; 79 | } 80 | return true; 81 | } 82 | 83 | template 84 | void warp(const T* p, const T* v, T* residual, T &norm_sq) const 85 | { 86 | // remap the image gradient according to equation (4) 87 | const T& r = p[0], tx = p[1], ty = p[2]; 88 | 89 | T vx = ceres::cos(v[0]); 90 | T vy = ceres::sin(v[0]); 91 | 92 | T a0 = ceres::cos(p[0]); 93 | T a1 = -ceres::sin(p[0]); 94 | 95 | T a2 = -a1; 96 | T a3 = a0; 97 | 98 | for (int y=0;ypatch_size_;y++) 99 | { 100 | for (int x=0;xpatch_size_;x++) 101 | { 102 | T x_p = a0*T(x) + a1*T(y) + a0*(config_->feature_.x - config_->half_size_) + a1 * (config_->feature_.y - config_->half_size_) + p[1]; 103 | T y_p = a2*T(x) + a3*T(y) + a2*(config_->feature_.x - config_->half_size_) + a3 * (config_->feature_.y - config_->half_size_) + p[2]; 104 | 105 | T g[2]; 106 | config_->grad_interp_->Evaluate(y_p, x_p, g); 107 | residual[x + config_->patch_size_ * y] = g[0] * vx + g[1] * vy; 108 | norm_sq += ceres::pow(residual[x + config_->patch_size_ * y], 2); 109 | } 110 | } 111 | } 112 | 113 | CostFunctionConfig* config_; 114 | }; 115 | 116 | 117 | struct Generator 118 | { 119 | static ceres::CostFunction* Create(cv::Point2d feature, 120 | cv::Point2d init_feature, 121 | const cv::Mat* event_frame, 122 | Interpolator* grad_interp, 123 | ErrorRotation* &functor) 124 | { 125 | CostFunctionConfig* config = new CostFunctionConfig(feature, init_feature, event_frame, grad_interp); 126 | functor = new ErrorRotation(config); 127 | int size = pow(event_frame->size[0], 2); 128 | return new ceres::AutoDiffCostFunction(functor, size); 129 | } 130 | }; 131 | 132 | } // nlls 133 | -------------------------------------------------------------------------------- /include/optimizer.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | #include "error.h" 6 | #include "patch.h" 7 | #include "types.h" 8 | 9 | 10 | namespace nlls 11 | { 12 | 13 | struct Optimizer 14 | /** 15 | * @brief The Optimizer performs optimization to find the best warp and optical flow for each patch. 16 | */ 17 | { 18 | Optimizer(); 19 | ~Optimizer(); 20 | 21 | /** 22 | * @brief Counts how many features are using the current image with timestamp time. 23 | * If none are using it, free the memory. 24 | */ 25 | void decrementCounter(ros::Time& time); 26 | 27 | /** 28 | * @ brief precomputes log gradients of the image 29 | */ 30 | void getLogGradients(const cv::Mat& img, cv::Mat& I_x, cv::Mat& I_y); 31 | bool precomputeLogImageArray(const tracker::Patches& patches, const tracker::ImageBuffer::iterator& image_it); 32 | 33 | /** 34 | * @brief perform optimization of cost function (7) in the original paper. 35 | */ 36 | void optimizeParameters(const cv::Mat &event_frame, tracker::Patch &patch); 37 | 38 | ceres::Problem::Options prob_options; 39 | ceres::Solver::Options solver_options; 40 | ceres::LossFunction* loss_function; 41 | 42 | OptimizerData optimizer_data_; 43 | 44 | int patch_size_; 45 | ceres::CostFunction* cost_function_; 46 | }; 47 | 48 | } 49 | -------------------------------------------------------------------------------- /include/patch.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #include "error.h" 13 | #include "types.h" 14 | 15 | DECLARE_int32(patch_size); 16 | DECLARE_int32(batch_size); 17 | DECLARE_int32(update_every_n_events); 18 | 19 | 20 | namespace tracker 21 | { 22 | 23 | /** 24 | * @brief The Patch struct which corresponds to an image patch defined by its center (feature position) and 25 | * dimension (patch size) 26 | */ 27 | struct Patch 28 | { 29 | /** 30 | * @brief Patch constructor for patch. Is defined by its center, linear warping matrix, half size ( half the patch 31 | * side length and the direction of optical flow in its region. 32 | * @param center Position of the patch defined by the location of the associated corner 33 | * @param warping Affine 3x3 matrix describing the current transformation taking pixels in the patch to the initial image. 34 | * @param flow_angle Angle (rad) of the optical flow in the patch around the initial feature 35 | * @param half_size half size of the patch side length 36 | * @param t_init time stamp of the image where the corner was extracted 37 | */ 38 | Patch(cv::Point2d center, ros::Time t_init): 39 | init_center_(center), flow_angle_(0), t_init_(t_init), t_curr_(t_init), event_counter_(0), color_(0, 0, 255), 40 | lost_(false), initialized_(false), tracking_quality_(1) 41 | { 42 | warping_ = cv::Mat::eye(3,3,CV_64F); 43 | 44 | half_size_ = (FLAGS_patch_size - 1) / 2; 45 | batch_size_ = FLAGS_batch_size; 46 | update_rate_ = FLAGS_update_every_n_events; 47 | 48 | reset(init_center_, t_init); 49 | } 50 | 51 | Patch() : Patch(cv::Point2f(-1,-1), ros::Time::now()) 52 | { 53 | // contstructor for initializing lost features 54 | lost_ = true; 55 | } 56 | 57 | /** 58 | * @brief contains checks if event is contained in square around the current feature position 59 | */ 60 | inline bool contains(double x, double y) 61 | { 62 | return half_size_ >= std::abs(x - center_.x) && half_size_ >= std::abs(y - center_.y); 63 | } 64 | 65 | /** 66 | * @brief insert an event in the event frame of the patch, incrementing the corresponding pixel by the polarity of the 67 | * event. 68 | */ 69 | inline void insert(const dvs_msgs::Event& event) 70 | { 71 | event_buffer_.push_front(event); 72 | 73 | if (event_buffer_.size() > FLAGS_batch_size) 74 | { 75 | event_buffer_.pop_back(); 76 | } 77 | 78 | event_counter_++; 79 | } 80 | 81 | /** 82 | * @brief warpPixel applies the inverse of the linear warp to unwarped and writes to warped. 83 | */ 84 | inline void warpPixel(cv::Point2d unwarped, cv::Point2d &warped) 85 | { 86 | // compute the position of the feature according to the warp (equation (8) in the paper) 87 | cv::Mat W = warping_.inv(); 88 | 89 | warped.x = W.at(0,0) * unwarped.x + W.at(0,1) * unwarped.y + W.at(0,2); 90 | warped.y = W.at(1,0) * unwarped.x + W.at(1,1) * unwarped.y + W.at(1,2); 91 | } 92 | 93 | /** 94 | * @brief getEventFramesAndReset returns the event_frame (according to equation (2) in the paper and resets the counter. 95 | */ 96 | inline void getEventFramesAndReset(cv::Mat &event_frame) 97 | { 98 | // implements the function (2) in the paper 99 | event_frame = cv::Mat::zeros(2*half_size_+1, 2*half_size_+1, CV_64F); 100 | 101 | int iterations = batch_size_< event_buffer_.size() ? batch_size_-1 : event_buffer_.size()-1; 102 | for (int i=0; i(y+1, x+1) += increment * rx * ry; 117 | event_frame.at(y , x+1) += increment * rx * (1 - ry); 118 | event_frame.at(y+1, x ) += increment * (1 - rx) * ry; 119 | event_frame.at(y , x ) += increment * (1 - rx) * (1 - ry); 120 | } 121 | 122 | // timstamp the image at the middle of the event batch 123 | t_curr_ = ros::Time(0.5*(event_buffer_[0].ts.toSec() + event_buffer_[iterations].ts.toSec())); 124 | event_counter_ = 0; 125 | } 126 | 127 | /** 128 | * @brief resets patch after it has been lost. 129 | */ 130 | inline void reset(cv::Point2d init_center, ros::Time t) 131 | { 132 | // reset feature after it has been lost 133 | event_counter_ = 0; 134 | tracking_quality_=1; 135 | lost_ = false; 136 | initialized_ = false; 137 | flow_angle_ = 0; 138 | 139 | center_ = init_center; 140 | init_center_ = init_center; 141 | t_curr_ = t; 142 | t_init_ = t; 143 | 144 | warping_ = cv::Mat::eye(3, 3, CV_64F); 145 | event_buffer_.clear(); 146 | 147 | // set random color 148 | static std::uniform_real_distribution unif(0, 255); 149 | static std::default_random_engine re; 150 | color_ = cv::Scalar(unif(re), unif(re), unif(re)); 151 | 152 | static int id = 0; 153 | id_ = id++; 154 | } 155 | 156 | cv::Point2d init_center_; 157 | cv::Point2d center_; 158 | cv::Mat warping_; 159 | double flow_angle_; 160 | 161 | int half_size_; 162 | 163 | int event_counter_; 164 | 165 | ros::Time t_init_; 166 | ros::Time t_curr_; 167 | 168 | double tracking_quality_; 169 | cv::Scalar color_; 170 | 171 | int id_; 172 | int batch_size_; 173 | int update_rate_; 174 | bool lost_; 175 | bool initialized_; 176 | 177 | std::deque event_buffer_; 178 | }; 179 | 180 | } 181 | -------------------------------------------------------------------------------- /include/tracker.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | #include 10 | #include 11 | #include 12 | 13 | #include "patch.h" 14 | #include "optimizer.h" 15 | #include "viewer.h" 16 | 17 | DECLARE_double(tracking_quality); 18 | 19 | 20 | namespace tracker 21 | { 22 | /** 23 | * @brief The Tracker class: uses Images to initialize corners and then tracks them using events. 24 | * Images are subscribed to and, when collected Harris Corners are extracted. Events falling in a patch around the corners 25 | * forming an event-frame-patch are used as observations and tracked versus the image gradient in the patch 26 | * at initialization. 27 | */ 28 | class Tracker 29 | { 30 | public: 31 | Tracker(ros::NodeHandle &nh, viewer::Viewer &viewer); 32 | private: 33 | /** 34 | * @brief Initializes a viewer and optimizer with the first image. Also extracts first features. 35 | * @param image_it CV_8U gray-scale image on which features are extracted. 36 | */ 37 | void init(const ImageBuffer::iterator& image_it); 38 | /** 39 | * @brief working thread 40 | */ 41 | void processEvents(); 42 | /** 43 | * @brief Blocks while there are no events in buffer 44 | * @param next event 45 | */ 46 | inline void waitForEvent( dvs_msgs::Event& ev) 47 | { 48 | static ros::Rate r(100); 49 | 50 | while (true) 51 | { 52 | { 53 | std::unique_lock lock(events_mutex_); 54 | if (events_.size()>0) 55 | { 56 | ev = events_.front(); 57 | events_.pop_front(); 58 | return; 59 | } 60 | } 61 | r.sleep(); 62 | VLOG_EVERY_N(1, 30) << "Waiting for events."; 63 | } 64 | } 65 | /** 66 | * @brief blocks until first image is received 67 | */ 68 | void waitForFirstImage(ImageBuffer::iterator& current_image_it); 69 | /** 70 | * @brief Always assigns image to the first image before time t_start 71 | */ 72 | inline bool updateFirstImageBeforeTime(ros::Time t_start, ImageBuffer::iterator& current_image_it) 73 | { 74 | bool next_image = false; 75 | auto next_image_it = current_image_it; 76 | 77 | while (next_image_it->first < t_start) 78 | { 79 | ++next_image_it; 80 | if (next_image_it == images_.end()) 81 | break; 82 | 83 | if (next_image_it->first < t_start) 84 | { 85 | next_image = true; 86 | current_image_it = next_image_it; 87 | } 88 | } 89 | 90 | return next_image; 91 | } 92 | 93 | /** 94 | * @brief checks all features if they can be bootstrapped 95 | */ 96 | void bootstrapAllPossiblePatches(Patches& patches, const ImageBuffer::iterator& image_it); 97 | /** 98 | * @brief bootstrapping features: Uses first two frames to initialize feature translation and optical flow. 99 | */ 100 | void bootstrapFeatureKLT(Patch& patch, const cv::Mat& last_image, const cv::Mat& current_image); 101 | /** 102 | * @brief bootstrapping features: Uses first event frame to solve for the best optical flow, given 0 translation. 103 | */ 104 | void bootstrapFeatureEvents(Patch& patch, const cv::Mat& event_frame); 105 | /** 106 | * @brief add new features 107 | */ 108 | void addFeatures(std::vector& lost_indices, const ImageBuffer::iterator& image_it); 109 | /** 110 | * @brief update a patch with the new event 111 | */ 112 | void updatePatch(Patch& patch, const dvs_msgs::Event &event); 113 | /** 114 | * @brief reset patches that have been lost. 115 | */ 116 | void resetPatches(Patches& new_patches, std::vector& lost_indices, const ImageBuffer::iterator& image_it); 117 | 118 | /** 119 | * @brief initialize corners on an image 120 | */ 121 | void initPatches(Patches& patches, std::vector& lost_indices, const int& corners, const ImageBuffer::iterator& image_it); 122 | 123 | /** 124 | * @brief extract patches 125 | */ 126 | void extractPatches(Patches &patches, const int& num_patches, const ImageBuffer::iterator& image_it); 127 | 128 | inline void padBorders(const cv::Mat& in, cv::Mat& out, int p) 129 | { 130 | out = cv::Mat(in.rows + p*2, in.cols + p*2, in.depth()); 131 | cv::Mat gray(out, cv::Rect(p, p, in.cols, in.rows)); 132 | copyMakeBorder(in, out, p, p, p, p, cv::BORDER_CONSTANT); 133 | } 134 | 135 | /** 136 | * @brief checks if the optimization cost is above 1.6 (as described in the paper) 137 | */ 138 | inline bool shouldDiscard(Patch& patch) 139 | { 140 | bool out_of_fov = (patch.center_.y < 0 || patch.center_.y >= sensor_size_.height || patch.center_.x < 0 || patch.center_.x >= sensor_size_.width); 141 | bool exceeded_error = patch.tracking_quality_ < FLAGS_tracking_quality; 142 | 143 | return exceeded_error || out_of_fov; 144 | } 145 | 146 | /** 147 | * @brief sets the number of events to process adaptively according to equation (15) in the paper 148 | */ 149 | void setBatchSize(Patch& patch, const cv::Mat& I_x, const cv::Mat& I_y, const double& d); 150 | /** 151 | * @brief ros callbacks for images and events 152 | */ 153 | void eventsCallback(const dvs_msgs::EventArray::ConstPtr& msg); 154 | void imageCallback(const sensor_msgs::Image::ConstPtr& msg); 155 | /** 156 | * @brief Insert an event in the buffer while keeping the buffer sorted 157 | * This uses insertion sort as the events already come almost always sorted 158 | */ 159 | inline void insertEventInSortedBuffer(const dvs_msgs::Event& e) 160 | { 161 | std::unique_lock lock(events_mutex_); 162 | events_.push_back(e); 163 | // insertion sort to keep the buffer sorted 164 | // in practice, the events come almost always sorted, 165 | // so the number of iterations of this loop is almost always 0 166 | int j = (events_.size() - 1) - 1; // second to last element 167 | while(j >= 0 && events_[j].ts > e.ts) 168 | { 169 | events_[j+1] = events_[j]; 170 | j--; 171 | } 172 | events_[j+1] = e; 173 | } 174 | 175 | cv::Size sensor_size_; 176 | 177 | // image flags 178 | bool got_first_image_; 179 | 180 | // pointers to most recent image and time 181 | ImageBuffer::iterator current_image_it_; 182 | ros::Time most_current_time_; 183 | 184 | // buffers for images and events 185 | EventBuffer events_; 186 | ImageBuffer images_; 187 | 188 | // ros 189 | ros::Subscriber event_sub_; 190 | image_transport::Subscriber image_sub_; 191 | image_transport::ImageTransport it_; 192 | ros::NodeHandle nh_; 193 | 194 | // patch parameters 195 | Patches patches_; 196 | std::map> patch_gradients_; 197 | std::vector lost_indices_; 198 | 199 | // delegation 200 | viewer::Viewer* viewer_ptr_ = NULL; 201 | nlls::Optimizer optimizer_; 202 | 203 | // mutex 204 | std::mutex events_mutex_; 205 | std::mutex images_mutex_; 206 | 207 | // tracks file 208 | std::ofstream tracks_file_; 209 | }; 210 | 211 | } 212 | -------------------------------------------------------------------------------- /include/types.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | 12 | namespace tracker 13 | { 14 | 15 | struct Patch; //forward decl 16 | using Patches = std::vector; //forward decl 17 | 18 | using EventBuffer = std::deque; 19 | using ImageBuffer = std::map; 20 | 21 | } 22 | 23 | namespace viewer 24 | { 25 | 26 | struct FeatureTrackData 27 | { 28 | tracker::Patches patches; 29 | ros::Time t, t_init; 30 | cv::Mat image; 31 | }; 32 | 33 | } 34 | 35 | namespace nlls 36 | { 37 | 38 | using Grid = ceres::Grid2D; 39 | using GridPtr = std::unique_ptr; 40 | using Interpolator = ceres::BiCubicInterpolator; 41 | using InterpolatorPtr = std::unique_ptr>; 42 | 43 | struct OptimizerDatum 44 | { 45 | OptimizerDatum() {} 46 | OptimizerDatum(std::vector &grad, cv::Mat& img, int num_patches) 47 | { 48 | grad_ = grad; 49 | grad_grid_ = new nlls::Grid(grad_.data(), 0, img.rows, 0, img.cols); 50 | grad_interp_ = new nlls::Interpolator(*grad_grid_); 51 | ref_counter_ = num_patches; 52 | } 53 | 54 | void clear() 55 | { 56 | delete grad_interp_; 57 | delete grad_grid_; 58 | } 59 | 60 | std::vector grad_; 61 | nlls::Grid* grad_grid_; 62 | nlls::Interpolator* grad_interp_; 63 | int ref_counter_; 64 | }; 65 | 66 | using OptimizerData = std::map; 67 | 68 | } 69 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /include/viewer.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | #include 6 | #include 7 | #include 8 | 9 | #include "patch.h" 10 | #include "types.h" 11 | 12 | 13 | namespace viewer 14 | { 15 | /** 16 | * @brief viewer object that displays the feature tracks as they are computed. 17 | */ 18 | class Viewer 19 | { 20 | public: 21 | Viewer(ros::NodeHandle& nh); 22 | ~Viewer(); 23 | /** 24 | * @brief main running thread 25 | */ 26 | void displayTracks(); 27 | /** 28 | * @brief initializes the tracking data that is used to generate a preview 29 | */ 30 | void initViewData(ros::Time t); 31 | /** 32 | * @brief Used to set the tracking data 33 | */ 34 | void setViewData(tracker::Patches &patches, ros::Time &t, 35 | tracker::ImageBuffer::iterator image_it); 36 | private: 37 | /** 38 | * @brief function that draws on image 39 | */ 40 | void drawOnImage(FeatureTrackData& data, cv::Mat& view, cv::Mat& image); 41 | /** 42 | * @brief helper function to publish image 43 | */ 44 | void publishImage(cv::Mat image, ros::Time stamp, std::string encoding, image_transport::Publisher pub); 45 | 46 | ros::NodeHandle nh_; 47 | 48 | FeatureTrackData feature_track_data_; 49 | 50 | cv::Mat feature_track_view_; 51 | 52 | image_transport::Publisher tracks_pub_; 53 | image_transport::ImageTransport it_; 54 | 55 | std::mutex data_mutex_; 56 | 57 | bool got_first_image_; 58 | }; 59 | 60 | } 61 | -------------------------------------------------------------------------------- /launch/eklt.launch: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /package.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | eklt 4 | 0.0.0 5 | The eklt package 6 | 7 | Daniel Gehrig 8 | 9 | GPLv3 10 | 11 | catkin 12 | catkin_simple 13 | 14 | ceres_catkin 15 | eigen_catkin 16 | 17 | sensor_msgs 18 | roscpp 19 | glog_catkin 20 | gflags_catkin 21 | dvs_msgs 22 | cv_bridge 23 | image_transport 24 | image_geometry 25 | 26 | 27 | -------------------------------------------------------------------------------- /src/eklt_node.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "viewer.h" 5 | #include "tracker.h" 6 | 7 | // feature detection 8 | DEFINE_int32(max_corners, 100, \ 9 | "Maximum features allowed to be tracked."); 10 | DEFINE_int32(min_corners, 60, \ 11 | "Minimum features allowed to be tracked."); 12 | DEFINE_int32(min_distance, 30, \ 13 | "Minimum distance between detected features. Parameter passed to goodFeatureToTrack."); 14 | DEFINE_int32(block_size, 30, \ 15 | "Block size to compute Harris score. passed to harrisCorner and goodFeaturesToTrack."); 16 | 17 | DEFINE_double(k, 0.04, \ 18 | "Magic number for Harris score."); 19 | DEFINE_double(quality_level, 0.3, \ 20 | "Determines range of harris score allowed between the maximum and minimum. Passed to goodFeaturesToTrack."); 21 | DEFINE_double(log_eps, 1e-2, \ 22 | "Small constant to compute log image. To avoid numerical issues normally we compute log(img /255 + log_eps)."); 23 | DEFINE_double(first_image_t, -1, \ 24 | "If specified discards all images until this time."); 25 | DEFINE_string(tracks_file_txt, "", \ 26 | "If specified, writes feature tracks to file with format id t x y."); 27 | 28 | // tracker 29 | DEFINE_int32(lk_window_size, 15, \ 30 | "Parameter for KLT. Used for bootstrapping feature."); 31 | DEFINE_int32(num_pyramidal_layers, 2, \ 32 | "Parameter for KLT. Used for bootstrapping feature."); 33 | DEFINE_int32(batch_size, 200, \ 34 | "Determines the size of the event buffer for each patch. If a new event falls into a patch and the buffer is full, the older event in popped."); 35 | DEFINE_int32(patch_size, 25, \ 36 | "Determines size of patch around corner. All events that fall in this patch are placed into the features buffer."); 37 | DEFINE_int32(max_num_iterations, 10, \ 38 | "Maximum number of itrations allowed by the ceres solver to update optical flow direction and warp."); 39 | 40 | DEFINE_double(displacement_px, 0.6, \ 41 | "Controls scaling parameter for batch size calculation: from formula optimal batchsize == 1/Cth * sum |nabla I * v/|v||. displacement_px corresponds to factor 1/Cth"); 42 | DEFINE_double(tracking_quality, 0.4, \ 43 | "minimum tracking quality allowed for a feature to be tracked. Can be a number between 0 (bad track) and 1 (good track). Is a rescaled number computed from ECC cost via tracking_quality == 1 - ecc_cost / 4. Note that ceres returns ecc_cost / 2."); 44 | DEFINE_string(bootstrap, "", 45 | "Method for bootstrapping optical flow direction. Options are 'klt', 'events'"); 46 | 47 | // viewer 48 | DEFINE_int32(update_every_n_events, 20, \ 49 | "Updates viewer data every n events as they are tracked."); 50 | DEFINE_double(scale, 4, \ 51 | "Rescaling factor for image. Allows to see subpixel tracking."); 52 | DEFINE_double(arrow_length, 5, \ 53 | "Length of optical flow arrow."); 54 | 55 | DEFINE_bool(display_features, true, \ 56 | "Whether or not to display feature tracks."); 57 | DEFINE_bool(display_feature_id, false, \ 58 | "Whether or not to display feature ids."); 59 | DEFINE_bool(display_feature_patches, false, \ 60 | "Whether or not to display feature patches."); 61 | 62 | 63 | int main(int argc, char** argv) 64 | { 65 | google::InitGoogleLogging(argv[0]); 66 | google::ParseCommandLineFlags(&argc, &argv, true); 67 | google::InstallFailureSignalHandler(); 68 | FLAGS_alsologtostderr = true; 69 | FLAGS_colorlogtostderr = true; 70 | 71 | ros::init(argc, argv, "eklt"); 72 | ros::NodeHandle nh; 73 | 74 | viewer::Viewer viewer(nh); 75 | tracker::Tracker tracker(nh, viewer); 76 | 77 | ros::spin(); 78 | 79 | 80 | return 0; 81 | } 82 | -------------------------------------------------------------------------------- /src/optimizer.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | 4 | #include "optimizer.h" 5 | 6 | DECLARE_int32(patch_size); 7 | DECLARE_int32(max_num_iterations); 8 | DECLARE_double(log_eps); 9 | 10 | 11 | namespace nlls 12 | { 13 | 14 | Optimizer::Optimizer() : 15 | patch_size_(FLAGS_patch_size) 16 | { 17 | prob_options.cost_function_ownership = ceres::DO_NOT_TAKE_OWNERSHIP; 18 | prob_options.local_parameterization_ownership = ceres::DO_NOT_TAKE_OWNERSHIP; 19 | prob_options.loss_function_ownership = ceres::DO_NOT_TAKE_OWNERSHIP; 20 | 21 | solver_options.minimizer_progress_to_stdout = false; 22 | solver_options.num_threads = 1; 23 | solver_options.linear_solver_type = ceres::DENSE_QR; 24 | solver_options.logging_type = ceres::SILENT; 25 | solver_options.max_num_iterations = FLAGS_max_num_iterations; 26 | solver_options.use_nonmonotonic_steps = true; 27 | 28 | loss_function = NULL; 29 | } 30 | 31 | Optimizer::~Optimizer() 32 | { 33 | for (auto &it : optimizer_data_) 34 | it.second.clear(); 35 | delete cost_function_; 36 | } 37 | 38 | void Optimizer::decrementCounter(ros::Time& time) 39 | { 40 | // keep track of reference counter to release gradient data 41 | if (optimizer_data_.find(time) == optimizer_data_.end()) 42 | return; 43 | 44 | --optimizer_data_[time].ref_counter_; 45 | if (optimizer_data_[time].ref_counter_ == 0) 46 | { 47 | optimizer_data_[time].clear(); 48 | optimizer_data_.erase(time); 49 | } 50 | } 51 | 52 | void Optimizer::getLogGradients(const cv::Mat& img, cv::Mat& I_x, cv::Mat& I_y) 53 | { 54 | // compute log gradients of image 55 | const double& log_eps = FLAGS_log_eps; 56 | 57 | cv::Mat normalized_image, log_image; 58 | img.convertTo(normalized_image, CV_64F, 1.0 / 255.0); 59 | cv::log(normalized_image + log_eps, log_image); 60 | 61 | cv::Sobel( log_image / 8, I_x, CV_64F, 1, 0, 3); 62 | cv::Sobel( log_image / 8, I_y, CV_64F, 0, 1, 3); 63 | } 64 | 65 | bool Optimizer::precomputeLogImageArray(const tracker::Patches& patches, const tracker::ImageBuffer::iterator& image_it) 66 | { 67 | cv::Mat I_x, I_y; 68 | getLogGradients(image_it->second, I_x, I_y); 69 | 70 | std::vector grad; 71 | 72 | // initialize grid that is used by ceres interpolator 73 | for (int row=0; rowsecond.rows;row++) 74 | { 75 | for (int col=0; colsecond.cols;col++) 76 | { 77 | grad.push_back(I_x.at(row,col)); 78 | grad.push_back(I_y.at(row,col)); 79 | } 80 | } 81 | 82 | // store this for later use 83 | const ros::Time& t = image_it->first; 84 | optimizer_data_[t] = OptimizerDatum(grad, image_it->second, patches.size()); 85 | } 86 | 87 | void Optimizer::optimizeParameters(const cv::Mat &event_frame, tracker::Patch &patch) 88 | { 89 | double norm=0; 90 | 91 | ceres::Problem problem(prob_options); 92 | ceres::Solver::Summary summary; 93 | 94 | // for now 3 free parameters for warp, x, y translation and theta rotation 95 | double p0[3]; 96 | ErrorRotation::getP0(p0, patch.warping_); 97 | double v0[] = {patch.flow_angle_}; 98 | 99 | // create cost functor that depends on the event frame, and current and initial 100 | // patch location 101 | ErrorRotation* functor; 102 | cost_function_ = Generator::Create(patch.center_, 103 | patch.init_center_, 104 | &event_frame, 105 | optimizer_data_[patch.t_init_].grad_interp_, 106 | functor); 107 | 108 | problem.AddResidualBlock(cost_function_, NULL, p0, v0); 109 | 110 | ceres::Solve(solver_options, &problem, &summary); 111 | 112 | // update patch according to new optimizer 113 | cv::Mat camera_warp; 114 | ErrorRotation::getWarp(p0, camera_warp); 115 | 116 | delete functor; 117 | 118 | // update state of patch 119 | patch.warping_ = camera_warp.clone(); 120 | patch.flow_angle_ = fmod(v0[0] , 2 * M_PI); 121 | 122 | //remap tracking cost to 0-1 (1 is best and 0 is bad) 123 | patch.tracking_quality_ = 1 - summary.final_cost / 2; 124 | patch.warpPixel(patch.init_center_, patch.center_); 125 | } 126 | 127 | }; 128 | -------------------------------------------------------------------------------- /src/tracker.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #include "tracker.h" 9 | 10 | DECLARE_int32(patch_size); 11 | DECLARE_int32(batch_size); 12 | DECLARE_int32(min_distance); 13 | DECLARE_int32(lk_window_size); 14 | DECLARE_int32(num_pyramidal_layers); 15 | DECLARE_int32(max_corners); 16 | DECLARE_int32(min_corners); 17 | DECLARE_int32(update_every_n_events); 18 | DECLARE_int32(block_size); 19 | 20 | DECLARE_bool(display_features); 21 | 22 | DECLARE_string(tracks_file_txt); 23 | DECLARE_string(bootstrap); 24 | 25 | DECLARE_double(displacement_px); 26 | DECLARE_double(first_image_t); 27 | DECLARE_double(quality_level); 28 | DECLARE_double(k); 29 | 30 | 31 | namespace tracker 32 | { 33 | 34 | Tracker::Tracker(ros::NodeHandle &nh, viewer::Viewer &viewer) 35 | : nh_(nh), got_first_image_(false), sensor_size_(0,0), viewer_ptr_(&viewer), it_(nh) 36 | { 37 | event_sub_ = nh_.subscribe("events", 10, &Tracker::eventsCallback, this); 38 | image_sub_ = it_.subscribe("images", 1, &Tracker::imageCallback, this); 39 | 40 | std::thread eventProcessingThread(&Tracker::processEvents, this); 41 | eventProcessingThread.detach(); 42 | } 43 | 44 | void Tracker::waitForFirstImage(ImageBuffer::iterator& current_image_it) 45 | { 46 | ros::Rate r(30); 47 | while (!got_first_image_) 48 | { 49 | r.sleep(); 50 | 51 | VLOG_EVERY_N(1, 30) << "Waiting for first image."; 52 | 53 | if (images_.empty()) 54 | continue; 55 | 56 | VLOG(1) << "Found first image."; 57 | 58 | current_image_it = images_.begin(); 59 | most_current_time_ = current_image_it->first; 60 | 61 | got_first_image_ = true; 62 | } 63 | } 64 | 65 | void Tracker::initPatches(Patches& patches, std::vector& lost_indices, const int& corners, const ImageBuffer::iterator& image_it) 66 | { 67 | // extract Harris corners 68 | extractPatches(patches, corners, image_it); 69 | 70 | // fill up patches to full capacity and set all of the filled patches to lost 71 | for (int i=patches.size(); isecond, I_x, I_y); 82 | 83 | padBorders(I_x, I_x_padded, p); 84 | padBorders(I_y, I_y_padded, p); 85 | 86 | for (int i=0; ifirst 125 | if (FLAGS_display_features) 126 | viewer_ptr_->initViewData(image_it->first); 127 | } 128 | 129 | void Tracker::processEvents() 130 | { 131 | // blocks until first image arrives and sets current_image_it_ to first arrived image 132 | waitForFirstImage(current_image_it_); 133 | 134 | // initializes patches and viewer 135 | init(current_image_it_); 136 | 137 | dvs_msgs::Event ev; 138 | int prev_num_features_tracked = 0; 139 | int viewer_counter = 0; 140 | while (ros::ok()) 141 | { 142 | // blocks until first event is found 143 | waitForEvent(ev); 144 | 145 | const cv::Point2f point(ev.x, ev.y); 146 | 147 | // keep track of the most current time with latest time stamp from event 148 | if (ev.ts >= most_current_time_) 149 | most_current_time_ = ev.ts; 150 | 151 | int num_features_tracked = patches_.size(); 152 | // go through each patch and update the event frame with the new event 153 | for (Patch &patch: patches_) 154 | { 155 | updatePatch(patch, ev); 156 | // count tracked features 157 | if (patch.lost_) 158 | num_features_tracked--; 159 | } 160 | 161 | if (updateFirstImageBeforeTime(most_current_time_, current_image_it_)) // enter if new image found 162 | { 163 | // bootstrap patches that need to be due to new image 164 | if (FLAGS_bootstrap == "klt") 165 | bootstrapAllPossiblePatches(patches_, current_image_it_); 166 | 167 | // replenish features if there are too few 168 | if (lost_indices_.size() > FLAGS_max_corners - FLAGS_min_corners) 169 | addFeatures(lost_indices_, current_image_it_); 170 | 171 | // erase old image 172 | auto image_it = current_image_it_; 173 | image_it--; 174 | images_.erase(image_it); 175 | } 176 | 177 | if (prev_num_features_tracked > num_features_tracked) 178 | { 179 | VLOG(1) << "Tracking " << num_features_tracked << " features."; 180 | } 181 | prev_num_features_tracked = num_features_tracked; 182 | 183 | // update data for viewer 184 | if (FLAGS_display_features && \ 185 | ++viewer_counter % FLAGS_update_every_n_events == 0) 186 | viewer_ptr_->setViewData(patches_, most_current_time_, current_image_it_); 187 | } 188 | } 189 | 190 | void Tracker::updatePatch(Patch& patch, const dvs_msgs::Event &event) 191 | { 192 | // if patch is lost or event does not fall within patch 193 | // or the event has occurred before the most recent patch timestamp 194 | // or the patch has not been bootstrapped yet, do not process event 195 | if (patch.lost_ || 196 | (FLAGS_bootstrap == "klt" && !patch.initialized_) || 197 | !patch.contains(event.x, event.y) || 198 | patch.t_curr_>event.ts) 199 | return; 200 | 201 | patch.insert(event); 202 | 203 | // start optimization if there are update_rate new events in the patch 204 | int update_rate = std::min(patch.update_rate_, patch.batch_size_); 205 | if (patch.event_buffer_.size() < patch.batch_size_ || patch.event_counter_ < update_rate) 206 | return; 207 | 208 | // compute event frame according to equation (2) in the paper 209 | cv::Mat event_frame; 210 | patch.getEventFramesAndReset(event_frame); 211 | 212 | // bootstrap using the events 213 | ros::Time t_prev = patch.t_curr_; 214 | if (!patch.initialized_ && FLAGS_bootstrap == "events") 215 | bootstrapFeatureEvents(patch, event_frame); 216 | 217 | // update feature position and recompute the adaptive batchsize 218 | optimizer_.optimizeParameters(event_frame, patch); 219 | 220 | if (tracks_file_.is_open()) 221 | tracks_file_ << patch.id_ << " " << patch.t_curr_ << " " << patch.center_.x << " " << patch.center_.y << std::endl; 222 | 223 | setBatchSize(patch, patch_gradients_[&patch - &patches_[0]].first, patch_gradients_[&patch - &patches_[0]].second, FLAGS_displacement_px); 224 | 225 | if (!shouldDiscard(patch)) 226 | return; 227 | 228 | // if the patch has been lost record it in lost_indices_ 229 | patch.lost_ = true; 230 | lost_indices_.push_back(&patch - &patches_[0]); 231 | } 232 | 233 | void Tracker::addFeatures(std::vector& lost_indices, const ImageBuffer::iterator& image_it) 234 | { 235 | // find new patches to replace them lost features 236 | Patches patches; 237 | extractPatches(patches, lost_indices.size(), image_it); 238 | 239 | if (patches.size() != 0) 240 | { 241 | // pass the new image to the optimizer to use for future optimizations 242 | optimizer_.precomputeLogImageArray(patches, image_it); 243 | 244 | // reset all lost features with newly initialized ones 245 | resetPatches(patches, lost_indices, image_it); 246 | } 247 | } 248 | 249 | void Tracker::bootstrapAllPossiblePatches(Patches& patches, const ImageBuffer::iterator& image_it) 250 | { 251 | for (int i=0; ifirst) 257 | continue; 258 | 259 | // perform bootstrapping using KLT and the first 2 frames, and compute the adaptive batch size 260 | // with the newly found parameters 261 | bootstrapFeatureKLT(patch, images_[patch.t_init_], image_it->second); 262 | setBatchSize(patch, patch_gradients_[i].first, patch_gradients_[i].second, FLAGS_displacement_px); 263 | } 264 | } 265 | 266 | void Tracker::setBatchSize(Patch& patch, const cv::Mat& I_x, const cv::Mat& I_y, const double& d) 267 | { 268 | // implements the equation (15) of the paper 269 | cv::Mat gradient = d * std::cos(patch.flow_angle_) * I_x + d * std::sin(patch.flow_angle_) * I_y; 270 | patch.batch_size_ = std::min(cv::norm(gradient, cv::NORM_L1), FLAGS_batch_size); 271 | patch.batch_size_ = std::max(5, patch.batch_size_); 272 | } 273 | 274 | void Tracker::resetPatches(Patches& new_patches, std::vector& lost_indices, const ImageBuffer::iterator& image_it) 275 | { 276 | const int& p = (FLAGS_patch_size-1)/2; 277 | cv::Mat I_x, I_y, I_x_padded, I_y_padded; 278 | 279 | optimizer_.getLogGradients(image_it->second, I_x, I_y); 280 | padBorders(I_x, I_x_padded, p); 281 | padBorders(I_y, I_y_padded, p); 282 | 283 | for (int i=new_patches.size()-1; i>=0; i--) 284 | { 285 | int index = lost_indices[i]; 286 | // for each lost feature decrement the ref counter of the optimizer (will free image gradients when no more 287 | // features use the image with timestamp patches_[index].t_init_ 288 | optimizer_.decrementCounter(patches_[index].t_init_); 289 | 290 | // reset lost patches with new ones 291 | Patch& reset_patch = new_patches[i]; 292 | patches_[index].reset(reset_patch.center_, reset_patch.t_init_); 293 | lost_indices.erase(lost_indices.begin()+i); 294 | 295 | // reinitialize the image gradients of new features 296 | const int x_min = reset_patch.center_.x-p; 297 | const int y_min = reset_patch.center_.y-p; 298 | cv::Mat p_I_x = I_x_padded.rowRange(y_min, y_min+2*p+1).colRange(x_min, x_min+2*p+1); 299 | cv::Mat p_I_y = I_y_padded.rowRange(y_min, y_min+2*p+1).colRange(x_min, x_min+2*p+1); 300 | patch_gradients_[index] = std::make_pair(p_I_x.clone(), p_I_y.clone()); 301 | setBatchSize(reset_patch, patch_gradients_[index].first, patch_gradients_[index].second, FLAGS_displacement_px); 302 | } 303 | } 304 | 305 | void Tracker::extractPatches(Patches &patches, const int& num_patches, const ImageBuffer::iterator& image_it) 306 | { 307 | std::vector features; 308 | 309 | // mask areas which are within a distance min_distance of other features or along the border. 310 | int hp = (FLAGS_patch_size - 1 ) / 2; 311 | int h = sensor_size_.height; 312 | int w = sensor_size_.width; 313 | cv::Mat mask = cv::Mat::ones(sensor_size_, CV_8UC1); 314 | mask.rowRange(0, hp).colRange(0, w-1).setTo(0); 315 | mask.rowRange(h - hp, h - 1).colRange(0, w-1).setTo(0); 316 | mask.rowRange(0, h-1).colRange(0, hp).setTo(0); 317 | mask.rowRange(0, h-1).colRange(w - hp, w - 1).setTo(0); 318 | 319 | const int& min_distance = FLAGS_min_distance; 320 | for (Patch &patch: patches_) 321 | { 322 | if (patch.lost_) continue; 323 | 324 | double min_x = std::fmax(patch.center_.x - min_distance, 0); 325 | double max_x = std::fmin(patch.center_.x + min_distance, w-1); 326 | double min_y = std::fmax(patch.center_.y - min_distance, 0); 327 | double max_y = std::fmin(patch.center_.y + min_distance, h-1); 328 | mask.rowRange(min_y, max_y).colRange(min_x, max_x).setTo(0); 329 | } 330 | 331 | // extract harris corners which are suitable 332 | // since they correspond to strong edges which also generate alot of events. 333 | VLOG(2) << "Harris corner detector with N=" << num_patches << " quality=" << FLAGS_quality_level 334 | << " min_dist=" << FLAGS_min_distance << " block_size=" << FLAGS_block_size << " k=" << FLAGS_k 335 | << " image_depth=" << image_it->second.depth() << " mask_ratio=" << cv::sum(mask)[0]/(mask.cols*mask.rows); 336 | 337 | cv::goodFeaturesToTrack(image_it->second, features, num_patches, 338 | FLAGS_quality_level, 339 | FLAGS_min_distance, mask, 340 | FLAGS_block_size, 341 | true, 342 | FLAGS_k); 343 | 344 | // initialize patches centered at the features with an initial pixel warp 345 | VLOG(1) << "Extracted " << features.size() << " new features on image at t=" << std::setprecision(15) << image_it->first.toSec() << " s."; 346 | for (int i=0; ifirst); 350 | Patch &patch = patches[patches.size()-1]; 351 | if (tracks_file_.is_open()) 352 | tracks_file_ << patch.id_ << " " << patch.t_curr_ << " " << patch.center_.x << " " << patch.center_.y << std::endl; 353 | } 354 | } 355 | 356 | void Tracker::bootstrapFeatureKLT(Patch& patch, const cv::Mat& last_image, const cv::Mat& current_image) 357 | { 358 | // bootstrap feature by initializing its warp and optical flow with KLT on successive images 359 | std::vector points = {patch.init_center_}; 360 | std::vector next_points; 361 | 362 | // track feature for one frame 363 | std::vector error; 364 | std::vector status; 365 | cv::Size window(FLAGS_lk_window_size, FLAGS_lk_window_size); 366 | cv::calcOpticalFlowPyrLK(last_image, current_image, points, next_points, status, error, window, FLAGS_num_pyramidal_layers); 367 | 368 | // compute optical flow angle as direction where the feature moved 369 | double opt_flow_angle = std::atan2(next_points[0].y - points[0].y, next_points[0].x - points[0].x); 370 | patch.flow_angle_ = opt_flow_angle; 371 | 372 | // initialize warping as pure translation to new point 373 | patch.warping_.at(0,2) = -(next_points[0].x - points[0].x); 374 | patch.warping_.at(1,2) = -(next_points[0].y - points[0].y); 375 | patch.warpPixel(patch.init_center_, patch.center_); 376 | 377 | // check if new patch has been lost due to leaving the fov 378 | bool should_discard = bool (patch.center_.y < 0 || patch.center_.y >= sensor_size_.height || patch.center_.x < 0 || patch.center_.x >= sensor_size_.width); 379 | if (should_discard) 380 | { 381 | patch.lost_ = true; 382 | lost_indices_.push_back(&patch - &patches_[0]); 383 | } 384 | else 385 | { 386 | patch.initialized_ = true; 387 | patch.t_curr_ = current_image_it_->first; 388 | if (tracks_file_.is_open()) 389 | tracks_file_ << patch.id_ << " " << patch.t_curr_ << " " << patch.center_.x << " " << patch.center_.y << std::endl; 390 | } 391 | } 392 | 393 | void Tracker::bootstrapFeatureEvents(Patch& patch, const cv::Mat& event_frame) 394 | { 395 | // Implement a bootstrapping mechanism for computing the optical flow direction via 396 | // \nabla I \cdot v= - \Delta E --> v = - \nabla I ^ \dagger \Delta E (assuming no translation or rotation 397 | // of the feature. 398 | int index = &patch - &patches_[0]; 399 | 400 | cv::Mat& I_x = patch_gradients_[index].first; 401 | cv::Mat& I_y = patch_gradients_[index].second; 402 | 403 | double s_I_xx = cv::sum(I_x.mul(I_x))[0]; 404 | double s_I_yy = cv::sum(I_y.mul(I_y))[0]; 405 | double s_I_xy = cv::sum(I_x.mul(I_y))[0]; 406 | double s_I_xt = cv::sum(I_x.mul(event_frame))[0]; 407 | double s_I_yt = cv::sum(I_y.mul(event_frame))[0]; 408 | 409 | cv::Mat M = (cv::Mat_(2,2) << s_I_xx, s_I_xy, s_I_xy, s_I_yy); 410 | cv::Mat b = (cv::Mat_(2,1) << s_I_xt, s_I_yt); 411 | 412 | cv::Mat v = -M.inv() * b; 413 | 414 | patch.flow_angle_ = std::atan2(v.at(0,0), v.at(1,0)); 415 | patch.initialized_ = true; 416 | } 417 | 418 | void Tracker::eventsCallback(const dvs_msgs::EventArray::ConstPtr& msg) 419 | { 420 | if (!got_first_image_) 421 | { 422 | LOG_EVERY_N(INFO, 20) << "Events dropped since no image present."; 423 | return; 424 | } 425 | 426 | if (sensor_size_.width <= 0) 427 | sensor_size_ = cv::Size(msg->width, msg->height); 428 | 429 | for (const dvs_msgs::Event& e : msg->events) 430 | { 431 | insertEventInSortedBuffer(e); 432 | } 433 | 434 | } 435 | 436 | void Tracker::imageCallback(const sensor_msgs::Image::ConstPtr &msg) 437 | { 438 | if (sensor_size_.width <= 0) 439 | sensor_size_ = cv::Size(msg->width, msg->height); 440 | 441 | cv_bridge::CvImagePtr cv_ptr; 442 | 443 | try 444 | { 445 | cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::MONO8); 446 | } 447 | catch (cv_bridge::Exception& e) 448 | { 449 | ROS_ERROR("cv_bridge exception: %s", e.what()); 450 | return; 451 | } 452 | 453 | // wait for the image after FLAGS_first_image_t 454 | if (cv_ptr->header.stamp.toSec() < FLAGS_first_image_t) 455 | { 456 | return; 457 | } 458 | 459 | std::unique_lock images_lock(images_mutex_); 460 | images_.insert(std::make_pair(msg->header.stamp, cv_ptr->image.clone())); 461 | } 462 | 463 | } // namespace 464 | -------------------------------------------------------------------------------- /src/viewer.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include 4 | #include 5 | 6 | #include "viewer.h" 7 | 8 | DECLARE_int32(max_corners); 9 | 10 | DECLARE_double(scale); 11 | DECLARE_double(arrow_length); 12 | 13 | DECLARE_bool(display_features); 14 | DECLARE_bool(display_feature_id); 15 | DECLARE_bool(display_feature_patches); 16 | 17 | 18 | 19 | namespace viewer 20 | { 21 | 22 | Viewer::Viewer(ros::NodeHandle& nh) 23 | : nh_(nh), got_first_image_(false), it_(nh) 24 | { 25 | } 26 | 27 | Viewer::~Viewer() 28 | { 29 | tracks_pub_.shutdown(); 30 | } 31 | 32 | void Viewer::setViewData(tracker::Patches &patches, ros::Time &t, 33 | tracker::ImageBuffer::iterator image_it) 34 | { 35 | // copy all patches data to feature_track_data_. This is later used to generate a preview of the feature tracks. 36 | std::lock_guard lock(data_mutex_); 37 | for (int i=0; isecond; 51 | 52 | // signal that the first image has been received 53 | got_first_image_ = got_first_image_ || true; 54 | } 55 | 56 | void Viewer::initViewData(ros::Time t) 57 | { 58 | // start viewer thread and publisher and allocate memory for feature_track_data_ 59 | tracks_pub_ = it_.advertise("feature_tracks", 1); 60 | 61 | std::thread viewerThread(&Viewer::displayTracks, this); 62 | viewerThread.detach(); 63 | 64 | int num_patches = FLAGS_max_corners; 65 | feature_track_data_.patches.reserve(num_patches); 66 | feature_track_data_.t = t; 67 | feature_track_data_.t_init = t; 68 | } 69 | 70 | void Viewer::publishImage(cv::Mat image, ros::Time stamp, std::string encoding, image_transport::Publisher pub) 71 | { 72 | // helper for publishing images 73 | static cv_bridge::CvImage cv_image; 74 | 75 | cv_image.encoding = encoding; 76 | cv_image.image = image.clone(); 77 | cv_image.header.stamp = stamp; 78 | 79 | pub.publish(cv_image.toImageMsg()); 80 | } 81 | 82 | void Viewer::displayTracks() 83 | { 84 | ros::Rate r(30); 85 | 86 | while (ros::ok()) 87 | { 88 | //if the first image was not yet received do not do anything 89 | // otherwise prepare feature tracking preview 90 | r.sleep(); 91 | if (!got_first_image_ || !FLAGS_display_features) 92 | { 93 | continue; 94 | } 95 | { 96 | // generate image with features and processed rates 97 | std::lock_guard lock(data_mutex_); 98 | drawOnImage(feature_track_data_, feature_track_view_, feature_track_data_.image); 99 | publishImage(feature_track_view_, ros::Time::now(), "bgr8", tracks_pub_); 100 | } 101 | } 102 | } 103 | 104 | void Viewer::drawOnImage(FeatureTrackData& data, cv::Mat& view, cv::Mat& image) 105 | { 106 | CHECK(image.size[0] > 0); 107 | const double& scale = FLAGS_scale; 108 | const double& arrow_length = FLAGS_arrow_length; 109 | const int& patch_size = FLAGS_patch_size; 110 | 111 | view.setTo(0); 112 | 113 | //convert to grayscale to 3channel U8 114 | cv::Mat c_image; 115 | cv::cvtColor(image, c_image, CV_GRAY2BGR); 116 | 117 | cv::Size size(scale*c_image.size[1], scale*c_image.size[0]); 118 | cv::resize(c_image, view, size, 0,0,cv::INTER_NEAREST); 119 | 120 | // draw timestamp 121 | std::string time_string = "t = " + std::to_string(data.t.toSec() - data.t_init.toSec()); 122 | cv::putText(view, time_string, scale * (cv::Point(image.size[1], image.size[0]) - cv::Point(140,2)), cv::FONT_HERSHEY_COMPLEX_SMALL, scale*.7, cvScalar(0,255,255), 1, CV_AA); 123 | 124 | // draw patches 125 | for (int i=0; i corners = {scale*top_left_warped, scale*top_right_warped, scale*bottom_right_warped, scale*bottom_left_warped}; 159 | 160 | if (patch.initialized_ && FLAGS_display_feature_patches) 161 | { 162 | cv::polylines(view, corners, true, patch.color_, 2); 163 | cv::line(view, scale*patch.center_, scale*top_middle_warped, patch.color_, 2); 164 | } 165 | 166 | // draw feature ids 167 | cv::Point text_pos = cv::Point(patch.center_.x-half_patch_size+2, patch.center_.y-half_patch_size+8); 168 | if (FLAGS_display_feature_id) 169 | cv::putText(view, std::to_string(i), scale*text_pos, cv::FONT_HERSHEY_COMPLEX_SMALL, scale * 0.4, cvScalar(255,0,0), 2, CV_AA); 170 | } 171 | 172 | } 173 | 174 | } 175 | --------------------------------------------------------------------------------