diff --git a/.gitignore b/.gitignore index 96e8f20..1dffd57 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,7 @@ install # Log artifacts log + +# VSCode database +.vscode/browse.vc.db* + diff --git a/.vscode/c_cpp_properties.json b/.vscode/c_cpp_properties.json new file mode 100644 index 0000000..753ea31 --- /dev/null +++ b/.vscode/c_cpp_properties.json @@ -0,0 +1,26 @@ +{ + "configurations": [ + { + "browse": { + "databaseFilename": "${workspaceFolder}/.vscode/browse.vc.db", + "limitSymbolsToIncludedHeaders": false + }, + "includePath": [ + "/home/sunrise/yiliao_ws/install/origincar_base/include/**", + "/home/sunrise/yiliao_ws/install/origincar_msg/include/**", + "/home/sunrise/yiliao_ws/install/lslidar_msgs/include/**", + "/opt/ros/humble/include/**", + "/home/sunrise/yiliao_ws/src/LSLIDAR_X_ROS2-20240228/src/lslidar_driver/include/**", + "/home/sunrise/yiliao_ws/src/ground_slam/include/**", + "/home/sunrise/yiliao_ws/src/origincar_base/include/**", + "/usr/include/**" + ], + "name": "ros2", + "intelliSenseMode": "gcc-arm64", + "compilerPath": "/usr/bin/gcc", + "cStandard": "gnu11", + "cppStandard": "c++17" + } + ], + "version": 4 +} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json index 9e65d7e..1124fb9 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,5 +1,20 @@ { "yaml.schemas": { "https://www.schemastore.org/package.json": "file:///home/guoch/test_ws/src/gc_navigation2_slamtoolbox/config/mapper_params_localization.yaml" - } + }, + "ROS2.distro": "humble", + "python.autoComplete.extraPaths": [ + "/home/sunrise/yiliao_ws/install/origincar_base/local/lib/python3.10/dist-packages", + "/home/sunrise/yiliao_ws/install/origincar_msg/local/lib/python3.10/dist-packages", + "/home/sunrise/yiliao_ws/install/lslidar_msgs/local/lib/python3.10/dist-packages", + "/opt/ros/humble/lib/python3.10/site-packages", + "/opt/ros/humble/local/lib/python3.10/dist-packages" + ], + "python.analysis.extraPaths": [ + "/home/sunrise/yiliao_ws/install/origincar_base/local/lib/python3.10/dist-packages", + "/home/sunrise/yiliao_ws/install/origincar_msg/local/lib/python3.10/dist-packages", + "/home/sunrise/yiliao_ws/install/lslidar_msgs/local/lib/python3.10/dist-packages", + "/opt/ros/humble/lib/python3.10/site-packages", + "/opt/ros/humble/local/lib/python3.10/dist-packages" + ] } \ No newline at end of file diff --git a/src/ground_slam/.gitignore b/src/ground_slam/.gitignore new file mode 100755 index 0000000..f89770e --- /dev/null +++ b/src/ground_slam/.gitignore @@ -0,0 +1,51 @@ +build/ +bin/ +lib/ +debug/ +msg_gen/ +srv_gen/ +msg/*Action.msg +msg/*ActionFeedback.msg +msg/*ActionGoal.msg +msg/*ActionResult.msg +msg/*Feedback.msg +msg/*Goal.msg +msg/*Result.msg +msg/_*.py + +# Generated by dynamic reconfigure +*.cfgc +/cfg/cpp/ +/cfg/*.py + +# Ignore generated docs +*.dox +*.wikidoc + +# eclipse stuff +.project +.cproject + +# qcreator stuff +CMakeLists.txt.user + +srv/_*.py +*.pcd +*.pyc +qtcreator-* +*.user + +*~ + +# Emacs +.#* + +# Catkin custom files +CATKIN_IGNORE +bag + +.vscode/* +log/* +saving/* +debug/* +test/* \ No newline at end of file diff --git a/src/ground_slam/CMakeLists.txt b/src/ground_slam/CMakeLists.txt new file mode 100755 index 0000000..369b352 --- /dev/null +++ b/src/ground_slam/CMakeLists.txt @@ -0,0 +1,118 @@ +cmake_minimum_required(VERSION 3.8) +project(ground_slam) + +# Default to C++17 (ROS2 Humble standard) +if(NOT CMAKE_CXX_STANDARD) + set(CMAKE_CXX_STANDARD 17) +endif() +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +set(CMAKE_BUILD_TYPE Release) +set(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake) + +# ── ROS2 packages ────────────────────────────────────── +find_package(ament_cmake REQUIRED) +find_package(rclcpp REQUIRED) +find_package(geometry_msgs REQUIRED) +find_package(nav_msgs REQUIRED) +find_package(std_msgs REQUIRED) +find_package(sensor_msgs REQUIRED) +find_package(cv_bridge REQUIRED) +find_package(tf2 REQUIRED) +find_package(tf2_geometry_msgs REQUIRED) +find_package(tf2_ros REQUIRED) +find_package(visualization_msgs REQUIRED) + +# ── System dependencies ──────────────────────────────── +find_package(OpenCV 4.2 REQUIRED) +find_package(OpenMP REQUIRED) +find_package(Eigen3 REQUIRED) +find_package(FFTW3 REQUIRED) +find_package(Ceres REQUIRED) +find_package(yaml-cpp REQUIRED) +find_package(Boost REQUIRED) +find_package(VTK REQUIRED) + +# ── Compiler flags ───────────────────────────────────── +set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -O3 -march=native") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -O3 -march=native -Wno-reorder") +if(OPENMP_FOUND) + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}") +endif() + +# ── Include directories ──────────────────────────────── +include_directories( + ${PROJECT_SOURCE_DIR}/include + ${OpenCV_INCLUDE_DIRS} + ${EIGEN3_INCLUDE_DIR} + ${FFTW3_INCLUDE_DIRS} + ${YAML_CPP_INCLUDE_DIR} + ${CERES_INCLUDE_DIRS} + ${Boost_INCLUDE_DIRS} + ${VTK_INCLUDE_DIRS} +) + +# ── Core library ─────────────────────────────────────── +add_library(${PROJECT_NAME}_lib SHARED + src/optimization_2d/pose_graph_2d.cc + src/utils.cc + src/dataset.cc + src/camera.cc + src/frame.cc + src/edge.cc + src/correlation_flow.cc + src/loop_closure.cc + src/map.cc + src/map_builder.cc + src/thread_publisher.cc + src/map_stitcher.cc + src/visualization.cc + src/timer.cc +) + +target_link_libraries(${PROJECT_NAME}_lib + -lfftw3 + -lfftw3f + ${OpenCV_LIBS} + ${EIGEN3_LIBS} + ${CERES_LIBRARIES} + yaml-cpp + ${Boost_LIBRARIES} + ${VTK_LIBRARIES} +) + +# ROS2 deps (header-only via include_directories above, link where needed) +ament_target_dependencies(${PROJECT_NAME}_lib + rclcpp + geometry_msgs + nav_msgs + std_msgs + sensor_msgs + cv_bridge + tf2 + tf2_geometry_msgs + tf2_ros + visualization_msgs +) + +# ── Executable ───────────────────────────────────────── +add_executable(${PROJECT_NAME} main.cpp) +target_link_libraries(${PROJECT_NAME} ${PROJECT_NAME}_lib) + +ament_target_dependencies(${PROJECT_NAME} + rclcpp +) + +# ── Install ──────────────────────────────────────────── +install(TARGETS ${PROJECT_NAME} ${PROJECT_NAME}_lib + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib + RUNTIME DESTINATION lib/${PROJECT_NAME} +) + +install(DIRECTORY configs/ + DESTINATION share/${PROJECT_NAME}/configs +) + +ament_package() diff --git a/src/ground_slam/LICENSE.md b/src/ground_slam/LICENSE.md new file mode 100644 index 0000000..1b0ab18 --- /dev/null +++ b/src/ground_slam/LICENSE.md @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + {one line to give the program's name and a brief idea of what it does.} + Copyright (C) {year} {name of author} + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + {project} Copyright (C) {year} {fullname} + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. \ No newline at end of file diff --git a/src/ground_slam/README.md b/src/ground_slam/README.md new file mode 100644 index 0000000..9c4fee8 --- /dev/null +++ b/src/ground_slam/README.md @@ -0,0 +1,138 @@ +

GroundSLAM: A Robust Visual SLAM System for Warehouse Robots Using Ground Textures

+ Kuan Xu1, + Zheng Yang1, + Lihua Xie1, + Chen Wang2 +

+ +

+ 1: Centre for Advanced Robotics Technology Innovation (CARTIN), Nanyang Technological University
+ 2: Spatial AI & Robotics (SAIR) Lab, Computer Science and Engineering, University at Buffalo
+

+ + +

+ + 🎥 [Youtube] | + 🎥 [Bilibili] + 📊 [Supplementary] + +

+ + +pipeline + +GroundSLAM is a novel **feature-free** and **ground-texture-based** SLAM system for **the warehouse robot**. Our system can provide robust pose estimation and localization in environments with many **dynamic** objects or **open spaces**, such as warehouses, which is very challenging for localization systems with a forward-facing camera or LiDAR. GroundSLAM consists of three components: feature-free visual odometry, ground-texture-based loop detection and map optimization, and map reuse. Specifically, we introduce a kernel cross-correlator for **image-level pose tracking**, loop detection, and map reuse to improve localization accuracy and robustness, and incorporate adaptive pruning strategies to enhance efficiency. Due to these specific designs, GroundSLAM more **robust** and **accurate** when dealing with ground images with **few textures** or with many **repetitive patterns** than the feature-based methods. + + + +**Video:** + + +

+ +

+ +## Test Environment +### Dependencies +* OpenCV 4.2 +* Eigen 3 +* Ceres 2.0.0 +* FFTW3 +* ROS noetic +* Boost +* yaml-cpp +* VTK + +## Build +``` + cd ~/catkin_ws/src + git clone https://github.com/sair-lab/GroundSLAM.git + cd ../ + catkin_make + source ~/catkin_ws/devel/setup.bash +``` + +## Run + +Modify the configuration file in [configs](configs) and then run + +``` +rosrun ground_slam ground_slam src/GroundSLAM/configs/your_config.yaml +``` + +## Data + +### PathTex Dataset + + pathtex_dataset + + +Our data collection platform is a modified Weston SCOUT Robot. The robot is equipped with an IDS uEye monocular camera, which is positioned at the bottom and facing downward, placed at a height of 0.1m above the ground. To ensure constant illumination, a set of LED lights are arranged around the camera. For ground truth, a prism is installed on the top of the robot, and its position is tracked by a Leica Nova MS60 MultiStation laser tracker. + +We collect the data of 10 common ground textures, including 6 $\color{lightblue}{outdoor}$ textures and 4 $\color{red}{indoor}$ textures. The table below provides detailed information and download links for each sequence. The **camera parameters** can be found [here](https://entuedu-my.sharepoint.com/:u:/g/personal/kuan_xu_staff_main_ntu_edu_sg/EQqXW2eDcXNAkBWlSGgq6bgBe2yYdjdcuSJ8HEFey3haGg?e=nOg2ym). + + + + +Sequence Name|Total Size|Total Images|Download Link +:--:|:--:|:--:|:--: +Brick_seq1|1.0g|3119|[Link](https://entuedu-my.sharepoint.com/:u:/g/personal/kuan_xu_staff_main_ntu_edu_sg/EUMENxrPbQBFmzAQmfhMw4YB4df6_uq6ua7H1fo9A7NC7g?e=5Mzy9Q) +Brick_seq2|0.9g|5328|[Link](https://entuedu-my.sharepoint.com/:u:/g/personal/kuan_xu_staff_main_ntu_edu_sg/EY1-hFr2taZJqjxE4k6-W6oB-XenzRAk_RW8DME6VvqUmg?e=PSQEi6) +Carpet1_seq1|1.7g|8458|[Link](https://entuedu-my.sharepoint.com/:u:/g/personal/kuan_xu_staff_main_ntu_edu_sg/ETuQX1ePORdKmQJ_wFXT1mUBS6MqJ3LoZ-eeUsDhhXouug?e=AmMgBX) +Carpet1_seq2|1.7g|8499|[Link](https://entuedu-my.sharepoint.com/:u:/g/personal/kuan_xu_staff_main_ntu_edu_sg/EQwzCVxFMT1Hh9BMMNljwSgBM27RXd7v8gdM3KMNWm5mDQ?e=aSoH1v) +Carpet2_seq1|3.0g|15481|[Link](https://entuedu-my.sharepoint.com/:u:/g/personal/kuan_xu_staff_main_ntu_edu_sg/EZ6Y6xsmk6xBjkkU7JNrVQIB_zTovWY8-AOPdW7AN7XJLw?e=GvlK03) +Carpet3_seq1|0.7g|4500|[Link](https://entuedu-my.sharepoint.com/:u:/g/personal/kuan_xu_staff_main_ntu_edu_sg/EXxxHyPOvsFBh8judFQqhtEB-kI6uBzFmKcCiNDZZBzBIw?e=917b5c) +Carpet3_seq2|0.7g|4385|[Link](https://entuedu-my.sharepoint.com/:u:/g/personal/kuan_xu_staff_main_ntu_edu_sg/EQHoNL0xtpdKj6e6mhBBLyEBl-7s5N0cJ6U47jzT1tJheg?e=ot4hSH) +Carpet3_seq3|1.0g|6428|[Link](https://entuedu-my.sharepoint.com/:u:/g/personal/kuan_xu_staff_main_ntu_edu_sg/EcE3o-HN0UJEpc57_EJM3kcBSVSIQ8M7oCjkWsZlUQRKLw?e=qG8MUM) +Coarse_asphalt_seq1|1.2g|5897|[Link](https://entuedu-my.sharepoint.com/:u:/g/personal/kuan_xu_staff_main_ntu_edu_sg/EQbDBVemPH9Cp7bqV2ZwfFIBD_gsHQ-d3atPfSY8__6DKQ?e=ASludI) +Concrete_seq1|1.0g|5850|[Link](https://entuedu-my.sharepoint.com/:u:/g/personal/kuan_xu_staff_main_ntu_edu_sg/EcIYh8RIhClKs7ogwgFmS_QBlflxcx-eR33BwRVerNXFgg?e=8McLDA) +Concrete_seq2|0.9g|5975|[Link](https://entuedu-my.sharepoint.com/:u:/g/personal/kuan_xu_staff_main_ntu_edu_sg/EbNJ5FdpQSJMqK-2zyoEPNoBNCO4ZzhuzjzTL2m1AYZQKQ?e=feQNUX) +Fine_asphalt_seq1|1.1g|5119|[Link](https://entuedu-my.sharepoint.com/:u:/g/personal/kuan_xu_staff_main_ntu_edu_sg/EY22RWOcM89ApAYEr0E5I5EB6QhINnL5iGsbgli8INjuXg?e=HArfqb) +Fine_asphalt_seq2|1.3g|11897|[Link](https://entuedu-my.sharepoint.com/:u:/g/personal/kuan_xu_staff_main_ntu_edu_sg/ERBTClOvkpBHgNeAEc5co4sBI5E-ubQ2MqNFwlfys07mbQ?e=WDd0uP) +Granite_tiles_seq1|1.2g|7194|[Link](https://entuedu-my.sharepoint.com/:u:/g/personal/kuan_xu_staff_main_ntu_edu_sg/ERNkKMy_nvFFmORT7LU_MxEB7TDzhAsNKEEfBf_cNG4Zbg?e=sjDkYW) +Granite_tiles_seq2|1.6g|10633|[Link](https://entuedu-my.sharepoint.com/:u:/g/personal/kuan_xu_staff_main_ntu_edu_sg/EU-8ocb82WZDpErJuOGfR6oBbQwXEpAzR-nykA6wXk9zeg?e=Vx4P1t) +Gravel_road1_seq1|0.8g|4883|[Link](https://entuedu-my.sharepoint.com/:u:/g/personal/kuan_xu_staff_main_ntu_edu_sg/ERRQQR0VTCVEqSdo9pM85zwBNMQFRBcgev4VVIZtjg68Vg?e=KFxJST) +Gravel_road2_seq1|2.1g|11776|[Link](https://entuedu-my.sharepoint.com/:u:/g/personal/kuan_xu_staff_main_ntu_edu_sg/EZS9BNL-ct1Nu3_Ag1Z0YuIBt6ah02i8vojro4eHexs4ww?e=hQOLIF) + + +### Run with Your Data + +The data should be organized in the following format: +``` +dataroot +├── image_names.txt +├── rgb +│   ├── 00001.png +│   ├── 00002.png +│   ├── 00003.png +│   └── ...... +└── times.txt +``` +where `image_names.txt` contains the image names in `/dataroot/rgb` and `times.txt` contains the corresponding double type timestamps. + +## Experiments + +### Data Association + + data_association + +We compare the data association of our system with ORB and SIFT on the HD Ground dataset. The numbers of features and matching inliers are given. For our method, the correction results are projected to three coordinate axes and represent the estimation of the 3-DOF movement. The vertical axis is the confidence of estimated movement on the horizontal axis. The higher the value of the peak relative to other positions, the greater the confidence of motion estimation. The results show that the data association of our system is more stable for various ground texture images. + +### Visual Odometry +
+ + +
+ +This experiment is conducted on our PathTex dataset. The left figure shows the trajectories produced by our system and GT-SLAM on 4 sequences. The right figure provides the comparison of error distributions of different systems on the Gravel_road2_seq1 sequence, where the vertical axis is the proportion of pose errors that are less than the given error threshold on the horizontal axis. + +### Loop Closure + +
+ + +
+ +These two figures show the performance difference of GroundSLAM with and without loop correction on the Fine_asphalt_seq2 sequence. It is seen that the pose errors are significantly decreased after the loop correction. diff --git a/src/ground_slam/cmake/FindEigen3.cmake b/src/ground_slam/cmake/FindEigen3.cmake new file mode 100755 index 0000000..0bb8c71 --- /dev/null +++ b/src/ground_slam/cmake/FindEigen3.cmake @@ -0,0 +1,94 @@ +# - Try to find Eigen3 lib +# +# This module supports requiring a minimum version, e.g. you can do +# find_package(Eigen3 3.1.2) +# to require version 3.1.2 or newer of Eigen3. +# +# Once done this will define +# +# EIGEN3_FOUND - system has eigen lib with correct version +# EIGEN3_INCLUDE_DIR - the eigen include directory +# EIGEN3_VERSION - eigen version + +# Copyright (c) 2006, 2007 Montel Laurent, +# Copyright (c) 2008, 2009 Gael Guennebaud, +# Copyright (c) 2009 Benoit Jacob +# Redistribution and use is allowed according to the terms of the 2-clause BSD license. + + +if(NOT Eigen3_FIND_VERSION) + if(NOT Eigen3_FIND_VERSION_MAJOR) + set(Eigen3_FIND_VERSION_MAJOR 2) + endif(NOT Eigen3_FIND_VERSION_MAJOR) + if(NOT Eigen3_FIND_VERSION_MINOR) + set(Eigen3_FIND_VERSION_MINOR 91) + endif(NOT Eigen3_FIND_VERSION_MINOR) + if(NOT Eigen3_FIND_VERSION_PATCH) + set(Eigen3_FIND_VERSION_PATCH 0) + endif(NOT Eigen3_FIND_VERSION_PATCH) + + set(Eigen3_FIND_VERSION "${Eigen3_FIND_VERSION_MAJOR}.${Eigen3_FIND_VERSION_MINOR}.${Eigen3_FIND_VERSION_PATCH}") +endif(NOT Eigen3_FIND_VERSION) + +macro(_eigen3_check_version) + file(READ "${EIGEN3_INCLUDE_DIR}/Eigen/src/Core/util/Macros.h" _eigen3_version_header) + + string(REGEX MATCH "define[ \t]+EIGEN_WORLD_VERSION[ \t]+([0-9]+)" _eigen3_world_version_match "${_eigen3_version_header}") + set(EIGEN3_WORLD_VERSION "${CMAKE_MATCH_1}") + string(REGEX MATCH "define[ \t]+EIGEN_MAJOR_VERSION[ \t]+([0-9]+)" _eigen3_major_version_match "${_eigen3_version_header}") + set(EIGEN3_MAJOR_VERSION "${CMAKE_MATCH_1}") + string(REGEX MATCH "define[ \t]+EIGEN_MINOR_VERSION[ \t]+([0-9]+)" _eigen3_minor_version_match "${_eigen3_version_header}") + set(EIGEN3_MINOR_VERSION "${CMAKE_MATCH_1}") + + set(EIGEN3_VERSION ${EIGEN3_WORLD_VERSION}.${EIGEN3_MAJOR_VERSION}.${EIGEN3_MINOR_VERSION}) + if(${EIGEN3_VERSION} VERSION_LESS ${Eigen3_FIND_VERSION}) + set(EIGEN3_VERSION_OK FALSE) + else(${EIGEN3_VERSION} VERSION_LESS ${Eigen3_FIND_VERSION}) + set(EIGEN3_VERSION_OK TRUE) + endif(${EIGEN3_VERSION} VERSION_LESS ${Eigen3_FIND_VERSION}) + + if(NOT EIGEN3_VERSION_OK) + + message(STATUS "Eigen3 version ${EIGEN3_VERSION} found in ${EIGEN3_INCLUDE_DIR}, " + "but at least version ${Eigen3_FIND_VERSION} is required") + endif(NOT EIGEN3_VERSION_OK) +endmacro(_eigen3_check_version) + +if (EIGEN3_INCLUDE_DIR) + + # in cache already + _eigen3_check_version() + set(EIGEN3_FOUND ${EIGEN3_VERSION_OK}) + +else (EIGEN3_INCLUDE_DIR) + + # specific additional paths for some OS + if (WIN32) + set(EIGEN_ADDITIONAL_SEARCH_PATHS ${EIGEN_ADDITIONAL_SEARCH_PATHS} "C:/Program Files/Eigen/include" "C:/Program Files (x86)/Eigen/include") + endif(WIN32) + + find_path(EIGEN3_INCLUDE_DIR NAMES signature_of_eigen3_matrix_library + PATHS + ${CMAKE_INSTALL_PREFIX}/include + ${EIGEN_ADDITIONAL_SEARCH_PATHS} + ${KDE4_INCLUDE_DIR} + PATH_SUFFIXES eigen3 eigen + ) + + if(EIGEN3_INCLUDE_DIR) + _eigen3_check_version() + endif(EIGEN3_INCLUDE_DIR) + + include(FindPackageHandleStandardArgs) + find_package_handle_standard_args(Eigen3 DEFAULT_MSG EIGEN3_INCLUDE_DIR EIGEN3_VERSION_OK) + + mark_as_advanced(EIGEN3_INCLUDE_DIR) + +endif(EIGEN3_INCLUDE_DIR) + +if(EIGEN3_FOUND) + include_directories(${EIGEN3_INCLUDE_DIR}) + link_directories(${EIGEN3_LIBRARIES}) +else(EIGEN3_FOUND) + MESSAGE(FATAL_ERROR "Eigen3 library not found") +endif(EIGEN3_FOUND) \ No newline at end of file diff --git a/src/ground_slam/cmake/FindFFTW3.cmake b/src/ground_slam/cmake/FindFFTW3.cmake new file mode 100755 index 0000000..ff45261 --- /dev/null +++ b/src/ground_slam/cmake/FindFFTW3.cmake @@ -0,0 +1,18 @@ +# - Find FFTW3 +# Find the native FFTW3 includes and library +# +# FFTW3_INCLUDE_DIRS - where to find fftw3.h +# FFTW3_LIBRARIES - List of libraries when using FFTW3. +# FFTW3_FOUND - True if FFTW3 found. + +if (FFTW3_INCLUDE_DIRS) + set(FFTW3_FIND_QUIETLY TRUE) +endif() + +find_path(FFTW3_INCLUDE_DIRS fftw3.h) +find_library(FFTW3_LIBRARIES NAMES fftw3) + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(FFTW3 DEFAULT_MSG FFTW3_LIBRARIES FFTW3_INCLUDE_DIRS) + +mark_as_advanced(FFTW3_LIBRARIES FFTW3_INCLUDE_DIRS) diff --git a/src/ground_slam/configs/config_HD.yaml b/src/ground_slam/configs/config_HD.yaml new file mode 100644 index 0000000..9749322 --- /dev/null +++ b/src/ground_slam/configs/config_HD.yaml @@ -0,0 +1,49 @@ +dataset: + camera_config: /media/zheng/xukuanssd/NTU/ground_texture/HD_ground/camera.yaml + dataroot: /media/zheng/xukuanssd/NTU/ground_texture/HD_ground/ramp_rubber/database/seq0033 + image_dir_name: rgb + +correlation_flow: + gaussian: + sigma: 0.2 + height: 1200 + kernel: 0 # {0: "polynomial", 1: "gaussian"} + lambda: 0.1 + polynomial: + offset: 0.1 + power: 3 + rotation_channel: 480 + rotation_divisor: 720 + width: 1600 + +keyframe_selection: + lower_response_thr: 30 + max_angle: 6.3 + max_distance: 0.01 + upper_response_thr: 90 + +map: + grid_scale: 0.1 # the true size of one grid + +loop_closure: + to_find_loop: true + angle_response_thr: 60 + distance_thr: 5 + frame_gap_thr: 100 + position_response_thr: 60 + +map_sticther: + cell_size: 1000 + stitch_map: true + +visualization: + frame_id: map + topic: + image: /kcc_slam/image + frame_pose: /kcc_slam/frame_pose + kcc_pose: /kcc_slam/kcc_pose + map: /kcc_slam/occupancy_map + +saving: + save_pose: true + saving_root: /home/xukuan/debug/kcc diff --git a/src/ground_slam/configs/config_geekplus.yaml b/src/ground_slam/configs/config_geekplus.yaml new file mode 100644 index 0000000..ff333d3 --- /dev/null +++ b/src/ground_slam/configs/config_geekplus.yaml @@ -0,0 +1,50 @@ +dataset: + dataroot: "/home/zheng/datasets/loopclosure/" + camera_config: "/home/zheng/datasets/loopclosure/camera.yaml" + image_dir_name: "" + +correlation_flow: + width: 448 + height: 448 + rotation_divisor: 720 #720 # Higher means higher resolution, but slower + rotation_channel: 480 #480 # Lower means faster. Too lower, e.g., less than 10, may produce error about 1/rotation_divisor*360 degrees. 64 may work well. + lambda: 0.1 # For regularization + kernel: 0 #1 # {0: "polynomial", 1: "gaussian"} + polynomial: # (X^T Y + offset).pow(power) + offset: 0.1 + power: 3 + gaussian: # exp(-(|X-Y|^2/(2*sigma^2))) + sigma: 0.2 # For Gaussian Kernel + +keyframe_selection: + to_find_loop: true + max_distance: 0.2 # in normalized plane, real size equal max_distance*camera_height + max_angle: 0.5 # rad + lower_response_thr: 30 + upper_response_thr: 60 + +map: + grid_scale: 0.1 # the true size of one grid + +loop_closure: + to_find_loop: true + position_response_thr: 60 # this should be tuned together with width and height: higher width*height -> higher threshold + angle_response_thr: 60 # this should be tuned together with rotation_divisor and rotation_channel: higher divisor*channel -> higher threshold + frame_gap_thr: 100 + distance_thr: 5 # in normalized plane, real size equal distance_thr*camera_height + +map_sticther: + stitch_map: true # whether to stitch map + cell_size: 1000 + +visualization: + frame_id: "map" + topic: + image: /kcc_slam/undistort_image + kcc_pose: "/kcc_slam/kcc_pose" + frame_pose: "/kcc_slam/frame_pose" + map: "/kcc_slam/occupancy_map" + +saving: + save_pose: true + saving_root: "/home/zheng/projects/ros_ws/src/kcc_slam/saving/experiments" \ No newline at end of file diff --git a/src/ground_slam/configs/config_ntu.yaml b/src/ground_slam/configs/config_ntu.yaml new file mode 100644 index 0000000..0678a70 --- /dev/null +++ b/src/ground_slam/configs/config_ntu.yaml @@ -0,0 +1,49 @@ +dataset: + camera_config: /media/data/datasets/ntu/NTU_Ground_Texture_Dataset/camera.yaml + dataroot: /media/data/datasets/ntu/NTU_Ground_Texture_Dataset/brick-V3 + image_dir_name: rgb + +correlation_flow: + gaussian: + sigma: 0.2 + height: 480 + kernel: 0 # {0: "polynomial", 1: "gaussian"} + lambda: 0.1 + polynomial: + offset: 0.1 + power: 3 + rotation_channel: 480 + rotation_divisor: 720 + width: 640 + +keyframe_selection: + lower_response_thr: 30 + max_angle: 0.052359877 + max_distance: 0.4 + upper_response_thr: 90 + +map: + grid_scale: 0.1 # the true size of one grid + +loop_closure: + to_find_loop: true + angle_response_thr: 60 + distance_thr: 5 + frame_gap_thr: 100 + position_response_thr: 60 + +map_sticther: + cell_size: 1000 + stitch_map: true + +visualization: + frame_id: map + topic: + image: /kcc_slam/image + frame_pose: /kcc_slam/frame_pose + kcc_pose: /kcc_slam/kcc_pose + map: /kcc_slam/occupancy_map + +saving: + save_pose: true + saving_root: /home/xukuan/debug/kcc diff --git a/src/ground_slam/figures/data_association.jpg b/src/ground_slam/figures/data_association.jpg new file mode 100644 index 0000000..b59c5b5 Binary files /dev/null and b/src/ground_slam/figures/data_association.jpg differ diff --git a/src/ground_slam/figures/features_small.jpg b/src/ground_slam/figures/features_small.jpg new file mode 100644 index 0000000..32efc20 Binary files /dev/null and b/src/ground_slam/figures/features_small.jpg differ diff --git a/src/ground_slam/figures/fig1.jpg b/src/ground_slam/figures/fig1.jpg new file mode 100644 index 0000000..c61fbe2 Binary files /dev/null and b/src/ground_slam/figures/fig1.jpg differ diff --git a/src/ground_slam/figures/loop_error.jpg b/src/ground_slam/figures/loop_error.jpg new file mode 100644 index 0000000..8a9b23e Binary files /dev/null and b/src/ground_slam/figures/loop_error.jpg differ diff --git a/src/ground_slam/figures/loop_trajectory.jpg b/src/ground_slam/figures/loop_trajectory.jpg new file mode 100644 index 0000000..e911c72 Binary files /dev/null and b/src/ground_slam/figures/loop_trajectory.jpg differ diff --git a/src/ground_slam/figures/pipeline.png b/src/ground_slam/figures/pipeline.png new file mode 100644 index 0000000..d0cb802 Binary files /dev/null and b/src/ground_slam/figures/pipeline.png differ diff --git a/src/ground_slam/figures/rmse_curve.jpg b/src/ground_slam/figures/rmse_curve.jpg new file mode 100644 index 0000000..6197e4d Binary files /dev/null and b/src/ground_slam/figures/rmse_curve.jpg differ diff --git a/src/ground_slam/figures/sample_images.jpg b/src/ground_slam/figures/sample_images.jpg new file mode 100644 index 0000000..d5caa81 Binary files /dev/null and b/src/ground_slam/figures/sample_images.jpg differ diff --git a/src/ground_slam/figures/trajectory.jpg b/src/ground_slam/figures/trajectory.jpg new file mode 100644 index 0000000..85f7585 Binary files /dev/null and b/src/ground_slam/figures/trajectory.jpg differ diff --git a/src/ground_slam/figures/video.png b/src/ground_slam/figures/video.png new file mode 100644 index 0000000..9a3b242 Binary files /dev/null and b/src/ground_slam/figures/video.png differ diff --git a/src/ground_slam/include/camera.h b/src/ground_slam/include/camera.h new file mode 100644 index 0000000..b8447b2 --- /dev/null +++ b/src/ground_slam/include/camera.h @@ -0,0 +1,59 @@ +#ifndef CAMERA_H_ +#define CAMERA_H_ + +#include +#include +#include +#include +#include +#include +#include + +class Camera{ +public: + Camera(); + Camera(const std::string& camera_file); + Camera& operator=(const Camera& camera); + + void UndistortImage(cv::Mat& image, cv::Mat& undistort_image); + void GetNewCameraMatrix(cv::Mat& camera_matrix); + double GetImageHeight(); + double GetImageWidth(); + double GetHeight(); + bool HeightIsAccurate(); + void GetExtrinsics(Eigen::Matrix3d& extrinsics); + double GetLengthOfPixel(); + + Eigen::Vector3d ConvertPrincipalToCenter(const Eigen::Vector3d& image_plane_pose); + Eigen::Vector3d ConvertCenterToPrincipal(const Eigen::Vector3d& image_center_pose); + + // Image plane: pixel plane, principal point on the image is the origin + // Camera: normalized plane, + // Robot: robot body coordinate system. + bool ConvertImagePlanePoseToCamera(Eigen::Vector3d& image_plane_pose, Eigen::Vector3d& camera_pose); + bool ConvertCameraPoseToImagePlane(Eigen::Vector3d& image_plane_pose, Eigen::Vector3d& camera_pose); + bool ConvertCameraPoseToRobot(Eigen::Vector3d& camera_pose, Eigen::Vector3d& robot_pose); + bool ConvertRobotPoseToCamera(Eigen::Vector3d& camera_pose, Eigen::Vector3d& robot_pose); + bool ConvertImagePlanePoseToRobot(Eigen::Vector3d& image_plane_pose, Eigen::Vector3d& robot_pose); + bool ConvertRobotPoseToImagePlane(Eigen::Vector3d& image_plane_pose, Eigen::Vector3d& robot_pose); + +private: + int _image_height; + int _image_width; + double _scale; + double _new_scale; + int _new_width; + int _new_height; + double _height; + bool _accurate_height; + cv::Mat _K; + cv::Mat _new_K; + cv::Mat _D; + cv::Mat _map1; + cv::Mat _map2; + Eigen::Matrix3d _extrinsics; +}; + +typedef std::shared_ptr CameraPtr; + +#endif // CAMERA_H_ \ No newline at end of file diff --git a/src/ground_slam/include/circ_shift.h b/src/ground_slam/include/circ_shift.h new file mode 100644 index 0000000..dd37b42 --- /dev/null +++ b/src/ground_slam/include/circ_shift.h @@ -0,0 +1,252 @@ +// circ_shift.h +// https://stackoverflow.com/questions/46077242/eigen-modifyable-custom-expression/46301503#46301503 +// this file implements circShift, fftshift, and ifftshift for Eigen vectors/matrices. +// + +#pragma once +#include + +template using bool_constant = std::integral_constant; + +namespace helper +{ +namespace detail +{ +template +constexpr std::true_type is_matrix(Eigen::MatrixBase); +std::false_type constexpr is_matrix(...); + +template +constexpr std::true_type is_array(Eigen::ArrayBase); +std::false_type constexpr is_array(...); +} + + +template +struct is_matrix : decltype(detail::is_matrix(std::declval>())) +{ +}; + +template +struct is_array : decltype(detail::is_array(std::declval>())) +{ +}; + +template +using is_matrix_or_array = bool_constant::value || is_matrix::value>; + +/* + * Index something if it's not an scalar + */ +template ::value, int>::type = 0> +auto index_if_necessary(T&& thing, Eigen::Index idx) +{ + return thing(idx); +} + +/* + * Overload for scalar. + */ +template >::value, int>::type = 0> + auto index_if_necessary(T&& thing, Eigen::Index) +{ + return thing; +} +} + +namespace Eigen +{ +template +class CircShiftedView; + +namespace internal +{ +template +struct traits> + : traits +{ + enum + { + RowsAtCompileTime = traits::RowsAtCompileTime, + ColsAtCompileTime = traits::ColsAtCompileTime, + MaxRowsAtCompileTime = (RowsAtCompileTime != Dynamic + ? int(RowsAtCompileTime) + : int(traits::MaxRowsAtCompileTime)), + MaxColsAtCompileTime = (ColsAtCompileTime != Dynamic + ? int(ColsAtCompileTime) + : int(traits::MaxColsAtCompileTime)), + XprTypeIsRowMajor = (int(traits::Flags) & RowMajorBit) != 0, + IsRowMajor = ((MaxRowsAtCompileTime == 1 && MaxColsAtCompileTime != 1) ? 1 + : (MaxColsAtCompileTime == 1 && MaxRowsAtCompileTime != 1) ? 0 + : XprTypeIsRowMajor), + FlagsRowMajorBit = IsRowMajor ? RowMajorBit : 0, + FlagsLvalueBit = is_lvalue::value ? LvalueBit : 0, + Flags = (traits::Flags & HereditaryBits) | FlagsLvalueBit | FlagsRowMajorBit + }; +}; +} + +template +class CircShiftedViewImpl; + + +template +class CircShiftedView : public CircShiftedViewImpl::StorageKind> +{ +public: + typedef typename CircShiftedViewImpl::StorageKind>::Base Base; + EIGEN_GENERIC_PUBLIC_INTERFACE(CircShiftedView) + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(CircShiftedView) + + typedef typename internal::ref_selector::non_const_type MatrixTypeNested; + typedef typename internal::remove_all::type NestedExpression; + + template + CircShiftedView(XprType& xpr, const T0& rowShift, const T1& colShift) + : m_xpr(xpr), m_rowShift(rowShift), m_colShift(colShift) + { + for (auto c = 0; c < xpr.cols(); ++c) + assert(std::abs(helper::index_if_necessary(m_rowShift, c)) < m_xpr.rows()); // row shift must be within +- rows()-1 + for (auto r = 0; r < xpr.rows(); ++r) + assert(std::abs(helper::index_if_necessary(m_colShift, r)) < m_xpr.cols()); // col shift must be within +- cols()-1 + } + + /** \returns number of rows */ + Index rows() const { return m_xpr.rows(); } + + /** \returns number of columns */ + Index cols() const { return m_xpr.cols(); } + + /** \returns the nested expression */ + const typename internal::remove_all::type& + nestedExpression() const { return m_xpr; } + + /** \returns the nested expression */ + typename internal::remove_reference::type& + nestedExpression() { return m_xpr.const_cast_derived(); } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Index getRowIdx(Index row, Index col) const + { + Index R = m_xpr.rows(); + assert(row >= 0 && row < R && col >= 0 && col < m_xpr.cols()); + Index r = row - helper::index_if_necessary(m_rowShift, col); + if (r >= R) + return r - R; + if (r < 0) + return r + R; + return r; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Index getColIdx(Index row, Index col) const + { + Index C = m_xpr.cols(); + assert(row >= 0 && row < m_xpr.rows() && col >= 0 && col < C); + Index c = col - helper::index_if_necessary(m_colShift, row); + if (c >= C) + return c - C; + if (c < 0) + return c + C; + return c; + } + +protected: + MatrixTypeNested m_xpr; + RowShift m_rowShift; + ColShift m_colShift; +}; + + +// Generic API dispatcher +template +class CircShiftedViewImpl + : public internal::generic_xpr_base>::type +{ + public: + typedef typename internal::generic_xpr_base>::type Base; +}; + +namespace internal +{ +template +struct unary_evaluator, IndexBased> + : evaluator_base> +{ + typedef CircShiftedView XprType; + + enum + { + CoeffReadCost = (evaluator::CoeffReadCost + + NumTraits::AddCost /* for comparison */ + + NumTraits::AddCost) /* for addition */, + Flags = (evaluator::Flags & HereditaryBits), + Alignment = 0 + }; + + EIGEN_DEVICE_FUNC explicit unary_evaluator(const XprType& xpr) : m_argImpl(xpr.nestedExpression()), m_xpr(xpr) + { + EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost); + } + + typedef typename XprType::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + CoeffReturnType coeff(Index row, Index col) const + { + return m_argImpl.coeff(m_xpr.getRowIdx(row, col), m_xpr.getColIdx(row, col)); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + CoeffReturnType coeff(Index idx) const + { + if (m_xpr.cols() == 1) + return m_argImpl.coeff(m_xpr.getRowIdx(idx, 1), 1); + if (m_xpr.rows() == 1) + return m_argImpl.coeff(1, m_xpr.getColIdx(1, idx)); + assert(m_xpr.cols() == 1 || m_xpr.rows() == 1); + // default no-assert case - assume col vector + return m_argImpl.coeff(m_xpr.getRowIdx(idx, 1), 1); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Scalar& coeffRef(Index row, Index col) + { + assert(row >= 0 && row < m_xpr.rows() && col >= 0 && col < m_xpr.cols()); + + return m_argImpl.coeffRef(m_xpr.getRowIdx(row, col), m_xpr.getColIdx(row, col)); + } + + protected: + + evaluator m_argImpl; + const XprType& m_xpr; +}; +} // end namespace internal +} // end namespace Eigen + +template +auto circShift(Eigen::DenseBase& x, RowShift r, ColShift c) +{ + return Eigen::CircShiftedView(x.derived(), r, c); +} + +template +auto fftshift(Eigen::DenseBase& x) +{ + Eigen::Index rs = x.rows() / 2; + Eigen::Index cs = x.cols() / 2; + return Eigen::CircShiftedView(x.derived(), rs, cs); +} + +template +auto ifftshift(Eigen::DenseBase& x) +{ + Eigen::Index rs = (x.rows() + 1) / 2; + Eigen::Index cs = (x.cols() + 1) / 2; + return Eigen::CircShiftedView(x.derived(), rs, cs); +} \ No newline at end of file diff --git a/src/ground_slam/include/correlation_flow.h b/src/ground_slam/include/correlation_flow.h new file mode 100644 index 0000000..bbe3d96 --- /dev/null +++ b/src/ground_slam/include/correlation_flow.h @@ -0,0 +1,36 @@ +#ifndef CORRELATION_FLOW_H +#define CORRELATION_FLOW_H + +#include +#include "utils.h" +#include "read_configs.h" + +class CorrelationFlow{ + +public: + CorrelationFlow(CFConfig& cf_config, double &image_height, double &image_width); + void ComputeIntermedium(const Eigen::ArrayXXf&, Eigen::ArrayXXcf&, Eigen::ArrayXXcf&); + Eigen::Vector3d ComputePose(const Eigen::ArrayXXcf&, const Eigen::ArrayXXf&, const Eigen::ArrayXXcf&, const Eigen::ArrayXXcf&, Eigen::Vector3d&, bool); + +private: + CFConfig cfg; + Eigen::ArrayXXcf target_fft; + Eigen::ArrayXXcf target_rotation_fft; + Eigen::ArrayXXcf FFT(const Eigen::ArrayXXf&); + Eigen::ArrayXXf IFFT(const Eigen::ArrayXXcf&); + Eigen::ArrayXXcf GetTargetFFT(int, int); + inline Eigen::ArrayXXf RemoveZeroComponent(const Eigen::ArrayXXf&); + inline Eigen::ArrayXXcf gaussian_kernel(const Eigen::ArrayXXcf&, int, int); + inline Eigen::ArrayXXcf gaussian_kernel(const Eigen::ArrayXXcf&, const Eigen::ArrayXXcf&, int, int); + inline Eigen::ArrayXXcf polynomial_kernel(const Eigen::ArrayXXcf&, int, int); + inline Eigen::ArrayXXcf polynomial_kernel(const Eigen::ArrayXXcf&, const Eigen::ArrayXXcf&, int, int); + float EstimateTrans(const Eigen::ArrayXXcf&, const Eigen::ArrayXXcf&, const Eigen::ArrayXXcf&, int, int, Eigen::Vector2d&); + inline Eigen::ArrayXXf polar(const Eigen::ArrayXXf&); + inline float GetInfo(const Eigen::ArrayXXf&, float); + + // void PrintArrayToFile (const Eigen::ArrayXXf target); +}; + +typedef std::shared_ptr CorrelationFlowPtr; + +#endif // CORRELATION_FLOW_H \ No newline at end of file diff --git a/src/ground_slam/include/dataset.h b/src/ground_slam/include/dataset.h new file mode 100644 index 0000000..31834f8 --- /dev/null +++ b/src/ground_slam/include/dataset.h @@ -0,0 +1,30 @@ +#ifndef DATASET_H_ +#define DATASET_H_ + +#include +#include +#include +#include +#include +#include + +#include "utils.h" + + +class Dataset{ +public: + Dataset(const std::string& dataroot, const std::string& image_dir_name); + size_t GetDatasetLength(); + bool GetImage(cv::Mat& image, size_t idx); + double GetTimestamp(size_t idx); + +private: + std::string _dataroot; + std::string _image_dir; + std::string _image_name_file_path; + std::vector _image_names; + std::string _time_file_path; + std::vector _timestamps; +}; + +#endif // DATASET_H_ \ No newline at end of file diff --git a/src/ground_slam/include/edge.h b/src/ground_slam/include/edge.h new file mode 100644 index 0000000..bf4581b --- /dev/null +++ b/src/ground_slam/include/edge.h @@ -0,0 +1,31 @@ +#ifndef EDGE_H_ +#define EDGE_H_ + +#include +#include +#include + +#include "utils.h" + +struct Edge{ + enum Type { + Odom = 0, + KCC = 1, + Loop = 2, + Others = 3, + }; + + int _edge_id; + Type _type; + int _from; + int _to; + Eigen::Vector3d _T; + Eigen::Matrix3d _information; + + Edge(); + Edge(int edge_id, Type type, int from, int to, Eigen::Vector3d& T, Eigen::Matrix3d& information); +}; + +typedef std::shared_ptr EdgePtr; + +#endif // EDGE_H_ \ No newline at end of file diff --git a/src/ground_slam/include/frame.h b/src/ground_slam/include/frame.h new file mode 100644 index 0000000..836f082 --- /dev/null +++ b/src/ground_slam/include/frame.h @@ -0,0 +1,45 @@ +#ifndef FRAME_H_ +#define FRAME_H_ + +#include +#include +#include + +#include "utils.h" + + +class Frame{ +public: + Frame(); + Frame(int frame_id); + Frame(int frame_id, double timestamp, Eigen::ArrayXXf&, Eigen::ArrayXXcf&, Eigen::ArrayXXcf&); + Frame& operator=(const Frame& other); + + void SetFrameId(int frame_id); + int GetFrameId(); + double GetTimestamp(); + Eigen::ArrayXXf GetFrame(); + void SetFFTResult(Eigen::ArrayXXcf& fft_result); + void SetFFTResult(Eigen::ArrayXXcf& fft_result, Eigen::ArrayXXcf& depth_fft_result); + void GetFFTResult(Eigen::ArrayXXcf& fft_result); + void GetFFTResult(Eigen::ArrayXXcf& fft_result, Eigen::ArrayXXcf& depth_fft_result); + void SetPose(Eigen::Vector3d& pose); + void GetPose(Eigen::Vector3d& pose); + void AddEdge(int edge_id); + void GetEdgeIds(std::vector& edge_ids); + void SaveToDisk(const std::string root_dir); + +private: + int _frame_id; + double _timestamp; + Eigen::ArrayXXf _frame; + Eigen::ArrayXXcf _fft_result; + Eigen::ArrayXXcf _fft_polar; + Eigen::ArrayXXcf _depth_fft_result; + Eigen::Vector3d _pose; + std::vector _edge_ids; +}; + +typedef std::shared_ptr FramePtr; + +#endif // FRAME_H_ \ No newline at end of file diff --git a/src/ground_slam/include/loop_closure.h b/src/ground_slam/include/loop_closure.h new file mode 100644 index 0000000..274dd9c --- /dev/null +++ b/src/ground_slam/include/loop_closure.h @@ -0,0 +1,43 @@ +#ifndef LOOP_CLOSURE_H_ +#define LOOP_CLOSURE_H_ + +#include "read_configs.h" +#include "correlation_flow.h" +#include "map.h" + + +struct LoopClosureResult{ + bool found; + Eigen::Vector3d response; + FramePtr current_frame; + FramePtr loop_frame; + Eigen::Vector3d relative_pose; + + LoopClosureResult(): found(false), response(-1.0, -1.0, -1.0) {} + LoopClosureResult(bool _found, Eigen::Vector3d _resopnse): found(_found), response(_resopnse) {} + LoopClosureResult& operator=(const LoopClosureResult& other){ + found = other.found; + response = other.response; + current_frame = other.current_frame; + loop_frame = other.loop_frame; + relative_pose = other.relative_pose; + return *this; + } +}; + +class LoopClosure{ +public: + LoopClosure(LoopClosureConfig& loop_closure_config, CorrelationFlowPtr correlation_flow, MapPtr map); + LoopClosureResult FindLoopClosure(Eigen::ArrayXXf& image, FramePtr& current_frame); + LoopClosureResult FindLoopClosure(Eigen::ArrayXXf& image, FramePtr& current_frame, Eigen::Vector3d& prior_pose); + LoopClosureResult FindLoopClosure(Eigen::ArrayXXf& image, FramePtr& current_frame, std::vector& frames); + +private: + LoopClosureConfig _loop_thr; + CorrelationFlowPtr _correlation_flow; + MapPtr _map; +}; + +typedef std::shared_ptr LoopClosurePtr; + +#endif // LOOP_CLOSURE_H_ \ No newline at end of file diff --git a/src/ground_slam/include/map.h b/src/ground_slam/include/map.h new file mode 100644 index 0000000..c501023 --- /dev/null +++ b/src/ground_slam/include/map.h @@ -0,0 +1,81 @@ +#ifndef MAP_H_ +#define MAP_H_ + +#include +#include +#include +#include + +#include "read_configs.h" +#include "camera.h" +#include "frame.h" +#include "edge.h" +#include "utils.h" + + +struct GridLocation{ + GridLocation() : x(0), y(0) {} + GridLocation(int x_, int y_) : x(x_), y(y_) {} + GridLocation& operator=(const GridLocation& other){ + x = other.x; + y = other.y; + return *this; + } + friend std::ostream & operator<<(std::ostream &out, GridLocation &loc){ + out << "(" << loc.x << ", " << loc.y << ")"; + return out; + } + + int x; + int y; +}; + +struct GridLocationHash{ + std::size_t operator() (const GridLocation& loc) const{ + return std::hash()(loc.x) ^ std::hash()(loc.y); + } +}; + +struct GridLocationEqual{ + bool operator()(const GridLocation& l1, const GridLocation& l2) const{ + return l1.x == l2.x && l1.y == l2.y; + } +}; + +typedef std::unordered_set FrameSet; +typedef std::unordered_map GridMap; + +class Map{ +public: + Map(); + Map(MapConfig& map_config); + + void AddFrame(FramePtr& frame); + void SetFrameDistance(FramePtr& frame, double distance); + void AddEdge(EdgePtr& edge); + + int GetAllFrames(std::vector& frames); + double GetFrameDistance(FramePtr& frame); + int GetAllEdges(std::vector& edges); + + void UpdatePoses(AlignedMap frame_poses); + + GridLocation ComputeGridLocation(double x, double y); + GridLocation ComputeGridLocation(Eigen::Vector3d pose); + int GetFramesInGrids(std::vector& frames, std::vector& grid_locations); + + FramePtr GetBaseframe(); + +private: + CameraPtr _camera; + std::map _frames; + std::map _frame_distanses; + std::map _edges; + double _grid_scale; + GridMap _grid_map; + FramePtr _baseframe; +}; + +typedef std::shared_ptr MapPtr; + +#endif // MAP_H_ \ No newline at end of file diff --git a/src/ground_slam/include/map_builder.h b/src/ground_slam/include/map_builder.h new file mode 100644 index 0000000..941a787 --- /dev/null +++ b/src/ground_slam/include/map_builder.h @@ -0,0 +1,83 @@ +#ifndef MAP_BUILDER_H_ +#define MAP_BUILDER_H_ + +#include "read_configs.h" +#include "camera.h" +#include "frame.h" +#include "correlation_flow.h" +#include "map.h" +#include "loop_closure.h" +#include "map_stitcher.h" + + +class MapBuilder{ +public: + MapBuilder(Configs& configs); + + bool AddNewInput(cv::Mat& image, double timestamp = -1); + void ComputeFFTResult(cv::Mat& image); + void ConstructFrame(double timestamp); + void SetCurrentFramePose(); + bool Initialize(); + void UpdateIntermedium(); + void UpdateCurrentPose(); + bool Tracking(Eigen::Vector3d& response); + void AddCFEdge(); + void AddCFEdgeToMap(Eigen::Vector3d& relative_pose, int from, int to, + int edge_id, Edge::Type edge_type, Eigen::Matrix3d& info); + Eigen::Vector2d ComputeRelativeDA(); + void SetFrameDistance(); + bool FindLoopClosure(); + void AddLoopEdges(); + bool OptimizeMap(); + void CheckAndOptimize(); + void UpdateValueAfterLoop(); + + // for visualization + bool GetCFPose(Eigen::Vector3d& pose); + bool GetFramePoses(Aligned& poses, std::vector& timestamps); + bool GetOccupancyMapOrigin( + Eigen::Vector3d& pixel_origin, Eigen::Matrix& real_origin); // [qw, qx, qy, qz, x, y, z] + double GetMapResolution(); + OccupancyData& GetMapData(); + +private: + bool _init; + int _frame_id; + int _edge_id; + bool _last_lost; + + // tmp + FramePtr _last_frame; + FramePtr _current_frame; + // image plane pose + Eigen::Vector3d _last_cf_pose; + Eigen::Vector3d _current_cf_pose; + // real scale pose + Eigen::Vector3d _last_cf_real_pose; + Eigen::Vector3d _current_cf_real_pose; + // robot pose + Eigen::Vector3d _last_pose; + Eigen::Vector3d _current_pose; + // distance + double _distance; + + // intermedium rsults + Eigen::ArrayXXf _image_array; + Eigen::ArrayXXcf _last_fft_result; + Eigen::ArrayXXcf _last_fft_polar; + Eigen::ArrayXXcf _fft_result; + Eigen::ArrayXXcf _fft_polar; + std::vector _loop_matches; + + Configs _configs; + CameraPtr _camera; + CorrelationFlowPtr _correlation_flow; + KeyframeSelectionConfig _kfs_config; + MapPtr _map; + LoopClosurePtr _loop_closure; + MapStitcherPtr _map_stitcher; +}; + + +#endif // MAP_BUILDER_H diff --git a/src/ground_slam/include/map_stitcher.h b/src/ground_slam/include/map_stitcher.h new file mode 100644 index 0000000..e16de59 --- /dev/null +++ b/src/ground_slam/include/map_stitcher.h @@ -0,0 +1,42 @@ +#ifndef MAP_STITCHER_H_ +#define MAP_STITCHER_H_ + +#include "optimization_2d/pose_graph_2d_error_term.h" +#include "camera.h" +#include "frame.h" +#include "map.h" +#include "read_configs.h" + + +struct Cell{ + int size; + Eigen::ArrayXXi data; + Eigen::ArrayXXi weight; + + Cell(): size(0) {} + Cell(int _size): size(_size), data(Eigen::ArrayXXi::Zero(_size, _size)), weight(Eigen::ArrayXXi::Zero(_size, _size)) {} +}; + +typedef std::unordered_map OccupancyData; + +class MapStitcher{ +public: + MapStitcher(MapStitcherConfig config, CameraPtr camera); + void InsertFrame(FramePtr frame, cv::Mat& image); + // input is the posion in one axis, output is the cell and the position in cell + Eigen::Vector2i ComputeCellPosition(int x); + void AddImageToOccupancy(FramePtr frame); + void RecomputeOccupancy(); + OccupancyData& GetOccupancyData(); + +private: + int _cell_size; + bool _to_stitch; + CameraPtr _camera; + std::unordered_map _raw_images; + OccupancyData _occupancy_data; +}; + +typedef std::shared_ptr MapStitcherPtr; + +#endif // MAP_STITCHER_H_ \ No newline at end of file diff --git a/src/ground_slam/include/optimization_2d/angle_local_parameterization.h b/src/ground_slam/include/optimization_2d/angle_local_parameterization.h new file mode 100644 index 0000000..ed19c15 --- /dev/null +++ b/src/ground_slam/include/optimization_2d/angle_local_parameterization.h @@ -0,0 +1,66 @@ +// Ceres Solver - A fast non-linear least squares minimizer +// Copyright 2016 Google Inc. All rights reserved. +// http://ceres-solver.org/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Google Inc. nor the names of its contributors may be +// used to endorse or promote products derived from this software without +// specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// +// Author: vitus@google.com (Michael Vitus) + +#ifndef OPTIMIZATION_2D_ANGLE_LOCAL_PARAMETERIZATION_H_ +#define OPTIMIZATION_2D_ANGLE_LOCAL_PARAMETERIZATION_H_ + +#include + +#include "normalize_angle.h" + + +namespace ceres { +namespace optimization_2d { + +// Defines a local parameterization for updating the angle to be constrained in +// [-pi to pi). +class AngleLocalParameterization { + public: + template + bool operator()(const T* theta_radians, + const T* delta_theta_radians, + T* theta_radians_plus_delta) const { + *theta_radians_plus_delta = + NormalizeAngle(*theta_radians + *delta_theta_radians); + + return true; + } + + static ceres::LocalParameterization* Create() { + return (new ceres::AutoDiffLocalParameterization); + } +}; + +} // namespace optimization_2d +} // namespace ceres + +#endif // OPTIMIZATION_2D_ANGLE_LOCAL_PARAMETERIZATION_H_ \ No newline at end of file diff --git a/src/ground_slam/include/optimization_2d/normalize_angle.h b/src/ground_slam/include/optimization_2d/normalize_angle.h new file mode 100644 index 0000000..29a9805 --- /dev/null +++ b/src/ground_slam/include/optimization_2d/normalize_angle.h @@ -0,0 +1,52 @@ +// Ceres Solver - A fast non-linear least squares minimizer +// Copyright 2016 Google Inc. All rights reserved. +// http://ceres-solver.org/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Google Inc. nor the names of its contributors may be +// used to endorse or promote products derived from this software without +// specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// +// Author: vitus@google.com (Michael Vitus) + +#ifndef OPTIMIZATION_2D_NORMALIZE_ANGLE_H_ +#define OPTIMIZATION_2D_NORMALIZE_ANGLE_H_ + +#include +#include + +namespace ceres { +namespace optimization_2d { + +// Normalizes the angle in radians between [-pi and pi). +template +inline T NormalizeAngle(const T& angle_radians) { + // Use ceres::floor because it is specialized for double and Jet types. + T two_pi(2.0 * M_PI); + return angle_radians - + two_pi * ceres::floor((angle_radians + T(M_PI)) / two_pi); +} + +} // namespace optimization_2d +} // namespace ceres + +#endif // OPTIMIZATION_2D_NORMALIZE_ANGLE_H_ \ No newline at end of file diff --git a/src/ground_slam/include/optimization_2d/pose_graph_2d.h b/src/ground_slam/include/optimization_2d/pose_graph_2d.h new file mode 100644 index 0000000..64154f1 --- /dev/null +++ b/src/ground_slam/include/optimization_2d/pose_graph_2d.h @@ -0,0 +1,33 @@ +#ifndef OPTIMIZATION_2D_POSE_GRAPH_2D_H_ +#define OPTIMIZATION_2D_POSE_GRAPH_2D_H_ + +#include +#include +#include +#include +#include +#include + +#include "angle_local_parameterization.h" +#include "pose_graph_2d_error_term.h" +#include "types.h" + +namespace ceres { +namespace optimization_2d { + +void BuildOptimizationProblem(const std::vector& constraints, + std::map* poses, + ceres::Problem* problem); + +void BuildOptimizationProblemWithScale(const std::vector& constraints, + std::vector& scale_data, + const std::vector& scale_data_idx, + std::map* poses, + ceres::Problem* problem); + +bool SolveOptimizationProblem(ceres::Problem* problem); + +} // namespace optimization_2d +} // namespace ceres + +#endif // OPTIMIZATION_2D_POSE_GRAPH_2D_H_ \ No newline at end of file diff --git a/src/ground_slam/include/optimization_2d/pose_graph_2d_error_term.h b/src/ground_slam/include/optimization_2d/pose_graph_2d_error_term.h new file mode 100644 index 0000000..9b5a35d --- /dev/null +++ b/src/ground_slam/include/optimization_2d/pose_graph_2d_error_term.h @@ -0,0 +1,183 @@ +// Ceres Solver - A fast non-linear least squares minimizer +// Copyright 2016 Google Inc. All rights reserved. +// http://ceres-solver.org/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Google Inc. nor the names of its contributors may be +// used to endorse or promote products derived from this software without +// specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// +// Author: vitus@google.com (Michael Vitus) +// +// Cost function for a 2D pose graph formulation. + +#ifndef OPTIMIZATION_2D_POSE_GRAPH_2D_ERROR_TERM_H_ +#define OPTIMIZATION_2D_POSE_GRAPH_2D_ERROR_TERM_H_ + +#include + +#include "optimization_2d/normalize_angle.h" + +namespace ceres { +namespace optimization_2d { + +template +Eigen::Matrix RotationMatrix2D(T yaw_radians) { + const T cos_yaw = ceres::cos(yaw_radians); + const T sin_yaw = ceres::sin(yaw_radians); + + Eigen::Matrix rotation; + rotation << cos_yaw, -sin_yaw, sin_yaw, cos_yaw; + return rotation; +} + +// Computes the error term for two poses that have a relative pose measurement +// between them. Let the hat variables be the measurement. +// +// residual = information^{1/2} * [ r_a^T * (p_b - p_a) - \hat{p_ab} ] +// [ Normalize(yaw_b - yaw_a - \hat{yaw_ab}) ] +// +// where r_a is the rotation matrix that rotates a vector represented in frame A +// into the global frame, and Normalize(*) ensures the angles are in the range +// [-pi, pi). +class PoseGraph2dErrorTerm { + public: + PoseGraph2dErrorTerm(double x_ab, + double y_ab, + double yaw_ab_radians, + const Eigen::Matrix3d& sqrt_information) + : p_ab_(x_ab, y_ab), + yaw_ab_radians_(yaw_ab_radians), + sqrt_information_(sqrt_information) {} + + template + bool operator()(const T* const x_a, + const T* const y_a, + const T* const yaw_a, + const T* const x_b, + const T* const y_b, + const T* const yaw_b, + T* residuals_ptr) const { + const Eigen::Matrix p_a(*x_a, *y_a); + const Eigen::Matrix p_b(*x_b, *y_b); + + Eigen::Map> residuals_map(residuals_ptr); + + residuals_map.template head<2>() = + RotationMatrix2D(*yaw_a).transpose() * (p_b - p_a) - p_ab_.cast(); + residuals_map(2) = NormalizeAngle( + (*yaw_b - *yaw_a) - static_cast(yaw_ab_radians_)); + + // Scale the residuals by the square root information matrix to account for + // the measurement uncertainty. + residuals_map = sqrt_information_.template cast() * residuals_map; + + return true; + } + + static ceres::CostFunction* Create(double x_ab, + double y_ab, + double yaw_ab_radians, + const Eigen::Matrix3d& sqrt_information) { + return (new ceres:: + AutoDiffCostFunction( + new PoseGraph2dErrorTerm( + x_ab, y_ab, yaw_ab_radians, sqrt_information))); + } + + EIGEN_MAKE_ALIGNED_OPERATOR_NEW + + private: + // The position of B relative to A in the A frame. + const Eigen::Vector2d p_ab_; + // The orientation of frame B relative to frame A. + const double yaw_ab_radians_; + // The inverse square root of the measurement covariance matrix. + const Eigen::Matrix3d sqrt_information_; +}; + + +class PoseGraph2dErrorTermWithScale { + public: + PoseGraph2dErrorTermWithScale(double x_ab, + double y_ab, + double yaw_ab_radians, + const Eigen::Matrix3d& sqrt_information) + : p_ab_(x_ab, y_ab), + yaw_ab_radians_(yaw_ab_radians), + sqrt_information_(sqrt_information) {} + + template + bool operator()(const T* const x_a, + const T* const y_a, + const T* const yaw_a, + const T* const x_b, + const T* const y_b, + const T* const yaw_b, + const T* const scale, + T* residuals_ptr) const { + const Eigen::Matrix p_a(*x_a, *y_a); + const Eigen::Matrix p_b(*x_b, *y_b); + + Eigen::Map> residuals_map(residuals_ptr); + + Eigen::Matrix scale_matrix = Eigen::Matrix::Identity(); + scale_matrix *= (*scale); + + residuals_map.template head<2>() = + RotationMatrix2D(*yaw_a).transpose() * (p_b - p_a) - scale_matrix * p_ab_.cast(); + residuals_map(2) = NormalizeAngle( + (*yaw_b - *yaw_a) - static_cast(yaw_ab_radians_)); + + // Scale the residuals by the square root information matrix to account for + // the measurement uncertainty. + residuals_map = sqrt_information_.template cast() * residuals_map; + + return true; + } + + static ceres::CostFunction* Create(double x_ab, + double y_ab, + double yaw_ab_radians, + const Eigen::Matrix3d& sqrt_information) { + return (new ceres:: + AutoDiffCostFunction( + new PoseGraph2dErrorTermWithScale( + x_ab, y_ab, yaw_ab_radians, sqrt_information))); + } + + EIGEN_MAKE_ALIGNED_OPERATOR_NEW + + private: + // The position of B relative to A in the A frame. + const Eigen::Vector2d p_ab_; + // The orientation of frame B relative to frame A. + const double yaw_ab_radians_; + // The inverse square root of the measurement covariance matrix. + const Eigen::Matrix3d sqrt_information_; +}; + + +} // namespace optimization_2d +} // namespace ceres + +#endif // OPTIMIZATION_2D_POSE_GRAPH_2D_ERROR_TERM_H_ \ No newline at end of file diff --git a/src/ground_slam/include/optimization_2d/types.h b/src/ground_slam/include/optimization_2d/types.h new file mode 100644 index 0000000..dd2bc35 --- /dev/null +++ b/src/ground_slam/include/optimization_2d/types.h @@ -0,0 +1,116 @@ +// Ceres Solver - A fast non-linear least squares minimizer +// Copyright 2016 Google Inc. All rights reserved. +// http://ceres-solver.org/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Google Inc. nor the names of its contributors may be +// used to endorse or promote products derived from this software without +// specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// +// Author: vitus@google.com (Michael Vitus) +// +// Defines the types used in the 2D pose graph SLAM formulation. Each vertex of +// the graph has a unique integer ID with a position and orientation. There are +// delta transformation constraints between two vertices. + +#ifndef OPTIMIZATION_2D_TYPES_H_ +#define OPTIMIZATION_2D_TYPES_H_ + +#include +#include + +#include "optimization_2d/normalize_angle.h" + +namespace ceres { +namespace optimization_2d { + +struct ScaleData{ + double scale; + bool fixed; + + ScaleData() {} + ScaleData(double _scale, bool _fixed): scale(_scale), fixed(_fixed) {} + +}; + +inline std::istream& operator>>(std::istream& input, ScaleData& scale_data) { + input >> scale_data.scale >> scale_data.fixed; + // Normalize the angle between -pi to pi. + return input; +} + +// The state for each vertex in the pose graph. +struct Pose2d { + double x; + double y; + double yaw_radians; + + // The name of the data type in the g2o file format. + static std::string name() { return "VERTEX_SE2"; } +}; + +inline std::istream& operator>>(std::istream& input, Pose2d& pose) { + input >> pose.x >> pose.y >> pose.yaw_radians; + // Normalize the angle between -pi to pi. + pose.yaw_radians = NormalizeAngle(pose.yaw_radians); + return input; +} + +// The constraint between two vertices in the pose graph. The constraint is the +// transformation from vertex id_begin to vertex id_end. +struct Constraint2d { + int id_begin; + int id_end; + + double x; + double y; + double yaw_radians; + + // The inverse of the covariance matrix for the measurement. The order of the + // entries are x, y, and yaw. + Eigen::Matrix3d information; + + // The name of the data type in the g2o file format. + static std::string name() { return "EDGE_SE2"; } +}; + +inline std::istream& operator>>(std::istream& input, Constraint2d& constraint) { + input >> constraint.id_begin >> constraint.id_end >> constraint.x >> + constraint.y >> constraint.yaw_radians >> constraint.information(0, 0) >> + constraint.information(0, 1) >> constraint.information(0, 2) >> + constraint.information(1, 1) >> constraint.information(1, 2) >> + constraint.information(2, 2); + + // Set the lower triangular part of the information matrix. + constraint.information(1, 0) = constraint.information(0, 1); + constraint.information(2, 0) = constraint.information(0, 2); + constraint.information(2, 1) = constraint.information(1, 2); + + // Normalize the angle between -pi to pi. + constraint.yaw_radians = NormalizeAngle(constraint.yaw_radians); + return input; +} + +} // namespace optimization_2d +} // namespace ceres + +#endif // OPTIMIZATION_2D_TYPES_H_ \ No newline at end of file diff --git a/src/ground_slam/include/read_configs.h b/src/ground_slam/include/read_configs.h new file mode 100644 index 0000000..b5e7d7a --- /dev/null +++ b/src/ground_slam/include/read_configs.h @@ -0,0 +1,137 @@ +#ifndef READ_CONFIGS_H_ +#define READ_CONFIGS_H_ + +#include +#include + +#include "utils.h" + + +struct DatasetConfig{ + std::string dataroot; + std::string image_dir_name; + std::string camera_file; +}; + +struct CFConfig{ + int width; + int height; + float lambda; + int kernel; + float sigma; + float offset; + int power; + int rotation_divisor; + int rotation_channel; +}; + +struct KeyframeSelectionConfig{ + double max_distance; + double max_angle; + double lower_response_thr; + double upper_response_thr; +}; + +struct MapConfig{ + double grid_scale; +}; + +struct LoopClosureConfig{ + bool to_find_loop; + double position_response_thr; + double angle_response_thr; + int frame_gap_thr; + double distance_thr; +}; + +struct MapStitcherConfig{ + bool stitch_map; + int cell_size; +}; + +struct VisualizationConfig{ + std::string frame_id; + std::string kcc_pose_topic; + std::string frame_pose_topic; + std::string map_topic; + std::string image_topic; +}; + +struct SavingConfig{ + std::string saving_root; + bool save_pose; +}; + +struct Configs{ + DatasetConfig dataset_config; + CFConfig cf_config; + KeyframeSelectionConfig keyframe_selection_config; + MapConfig map_config; + LoopClosureConfig loop_closure_config; + MapStitcherConfig map_stitcher_config; + VisualizationConfig visualization_config; + SavingConfig saving_config; + + Configs(const std::string& config_file){ + if(!FileExists(config_file)){ + std::cout << "config file: " << config_file << " doesn't exist" << std::endl; + return; + } + + YAML::Node file_node = YAML::LoadFile(config_file); + YAML::Node dataset_node = file_node["dataset"]; + dataset_config.dataroot = dataset_node["dataroot"].as(); + dataset_config.image_dir_name = dataset_node["image_dir_name"].as(); + dataset_config.camera_file = dataset_node["camera_config"].as(); + + YAML::Node cf_node = file_node["correlation_flow"]; + cf_config.width = cf_node["width"].as(); + cf_config.height = cf_node["height"].as(); + cf_config.lambda = cf_node["lambda"].as(); + cf_config.rotation_divisor = cf_node["rotation_divisor"].as(); + cf_config.rotation_channel = cf_node["rotation_channel"].as(); + cf_config.kernel = cf_node["kernel"].as(); + cf_config.offset = cf_node["polynomial"]["offset"].as(); + cf_config.power = cf_node["polynomial"]["power"].as(); + cf_config.sigma = cf_node["gaussian"]["sigma"].as(); + + YAML::Node kfs_node = file_node["keyframe_selection"]; + keyframe_selection_config.max_distance = kfs_node["max_distance"].as(); + keyframe_selection_config.max_angle = kfs_node["max_angle"].as(); + keyframe_selection_config.lower_response_thr = kfs_node["lower_response_thr"].as(); + keyframe_selection_config.upper_response_thr = kfs_node["upper_response_thr"].as(); + + YAML::Node map_node = file_node["map"]; + map_config.grid_scale = map_node["grid_scale"].as(); + + YAML::Node loop_closure_node = file_node["loop_closure"]; + loop_closure_config.to_find_loop = + loop_closure_node["to_find_loop"].as(); + loop_closure_config.position_response_thr = + loop_closure_node["position_response_thr"].as(); + loop_closure_config.angle_response_thr = + loop_closure_node["angle_response_thr"].as(); + loop_closure_config.frame_gap_thr = + loop_closure_node["frame_gap_thr"].as(); + loop_closure_config.distance_thr = + loop_closure_node["distance_thr"].as(); + + YAML::Node map_stitcher_node = file_node["map_sticther"]; + map_stitcher_config.stitch_map = map_stitcher_node["stitch_map"].as(); + map_stitcher_config.cell_size = map_stitcher_node["cell_size"].as(); + + YAML::Node visualization_node = file_node["visualization"]; + visualization_config.frame_id = visualization_node["frame_id"].as(); + visualization_config.kcc_pose_topic = visualization_node["topic"]["kcc_pose"].as(); + visualization_config.frame_pose_topic = visualization_node["topic"]["frame_pose"].as(); + visualization_config.map_topic = visualization_node["topic"]["map"].as(); + visualization_config.image_topic = visualization_node["topic"]["image"].as(); + + YAML::Node saving_node = file_node["saving"]; + saving_config.saving_root = saving_node["saving_root"].as(); + saving_config.save_pose = saving_node["save_pose"].as(); + } +}; + + +#endif // READ_CONFIGS_H_ \ No newline at end of file diff --git a/src/ground_slam/include/thread_publisher.h b/src/ground_slam/include/thread_publisher.h new file mode 100644 index 0000000..5b24191 --- /dev/null +++ b/src/ground_slam/include/thread_publisher.h @@ -0,0 +1,32 @@ +#ifndef THREAD_PUBLISHER_H_ +#define THREAD_PUBLISHER_H_ +#include +#include +#include +#include +#include +#include +#include + +template +class ThreadPublisher { +public: + ThreadPublisher(); + ~ThreadPublisher(); + + void Register(std::function&)> cb); + void Start(); + void Publish(const std::shared_ptr msg); + void Process(); + void ShutDown(); + +private: + std::mutex msg_mutex_; + std::condition_variable msg_cond_; + std::queue> msgs_; + std::thread publish_thread_; + std::vector&)>> callbacks_; + bool shutdown_requested_; +}; + +#endif // THREAD_PUBLISHER_H_ diff --git a/src/ground_slam/include/timer.h b/src/ground_slam/include/timer.h new file mode 100755 index 0000000..d0d84e7 --- /dev/null +++ b/src/ground_slam/include/timer.h @@ -0,0 +1,27 @@ +#ifndef _TIMER_H_ +#define _TIMER_H_ + +#include +#include + + +typedef struct{ + struct timeval start; + struct timeval stop; +}Timer; + +void startTimer(Timer *pTimer); +void stopTimer(Timer *pTimer); +double getElapsedTime(Timer *pTimer); +void writeTimeToFile(double arrTime[], int nCount, int nFrameNo, char *filename); + +#define INITIALIZE_TIMER Timer stTimer; double arrTime[100] +#define START_TIMER startTimer(&stTimer) +#define STOP_TIMER(text) stopTimer(&stTimer); printf(text); printf(": %.1f\n",getElapsedTime(&stTimer)) +#define END_TIMER(nIndex) stopTimer(&stTimer); arrTime[nIndex] = getElapsedTime(&stTimer) +#define ACC_TIMER(nIndex) stopTimer(&stTimer); arrTime[nIndex] += getElapsedTime(&stTimer) +#define WRITE_TIME_FILE(nCount, nFrameNo, filename) writeTimeToFile(arrTime, nCount, nFrameNo, (char *)filename) + +#endif//_TIMER_H_ + + diff --git a/src/ground_slam/include/utils.h b/src/ground_slam/include/utils.h new file mode 100644 index 0000000..93642b4 --- /dev/null +++ b/src/ground_slam/include/utils.h @@ -0,0 +1,82 @@ +#ifndef UTILS_H_ +#define UTILS_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +// Eigen type +template