git update

This commit is contained in:
2026-06-08 16:35:07 +08:00
parent db6686fccb
commit 8b775db45f
59 changed files with 4901 additions and 1 deletions

51
src/ground_slam/.gitignore vendored Executable file
View File

@@ -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/*

118
src/ground_slam/CMakeLists.txt Executable file
View File

@@ -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()

674
src/ground_slam/LICENSE.md Normal file
View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
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 <http://www.gnu.org/licenses/>.
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
<http://www.gnu.org/licenses/>.
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
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

138
src/ground_slam/README.md Normal file
View File

@@ -0,0 +1,138 @@
<h1 align="center">GroundSLAM: A Robust Visual SLAM System for Warehouse Robots Using Ground Textures</h1><p align="center"><strong>
<a href = "https://scholar.google.com/citations?user=-p7HvCMAAAAJ&hl=zh-CN">Kuan Xu</a><sup>1</sup>,
<a href = "https://github.com/yangzheng-yz">Zheng Yang</a><sup>1</sup>,
<a href = "https://scholar.google.com.sg/citations?user=Fmrv3J8AAAAJ&hl=en">Lihua Xie</a><sup>1</sup>,
<a href = "https://sairlab.org/team/chenw/">Chen Wang</a><sup>2</sup>
</strong></p>
<p align="center"><strong>
<a href = "https://www.ntu.edu.sg/cartin">1: Centre for Advanced Robotics Technology Innovation (CARTIN), Nanyang Technological University</a><br>
<a href = "https://sairlab.org/">2: Spatial AI & Robotics (SAIR) Lab, Computer Science and Engineering, University at Buffalo</a><br>
</strong></p>
<p align="center"><strong>
<!-- <a href = "https://arxiv.org/pdf/2408.03520">&#128196; [PDF]</a> |
<a href = "https://xukuanhit.github.io/airslam/">&#128190; [Project Site]</a> | -->
<a href = "https://youtu.be/2sI76SDptDA">&#127909; [Youtube]</a> |
<a href = "https://www.bilibili.com/video/BV1vWh8zTE77">&#127909; [Bilibili]</a>
<a href = "supplementary/GroundSLAM_Supplement_Materia.pdf">&#128202; [Supplementary]</a>
<!-- &#128214; [OpenAccess] -->
</strong></p>
<img src="figures/pipeline.png" width = "800" alt="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:**
<p align="middle">
<a href="https://youtu.be/2sI76SDptDA" target="_blank"><img src="figures/video.png" width="600" border="10"/></a>
</p>
## 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
<img src="figures/sample_images.jpg" width = "600" alt="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).
<!-- <div align=center> -->
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)
<!-- </div> -->
### 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
<img src="figures/features_small.jpg" width = "700" alt="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
<div style="display:flex; justify-content:flex-start;">
<img src="figures/trajectory.jpg" height="200" style="margin-right: 20px;" />
<img src="figures/rmse_curve.jpg" height="200" />
</div>
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
<div style="display:flex; justify-content:flex-start;">
<img src="figures/loop_trajectory.jpg" height="135" style="margin-right: 20px;" />
<img src="figures/loop_error.jpg" height="135" />
</div>
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.

View File

@@ -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, <montel@kde.org>
# Copyright (c) 2008, 2009 Gael Guennebaud, <g.gael@free.fr>
# Copyright (c) 2009 Benoit Jacob <jacob.benoit.1@gmail.com>
# 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)

View File

@@ -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)

View File

@@ -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

View File

@@ -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"

View File

@@ -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

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 883 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 297 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 775 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 381 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 115 KiB

View File

@@ -0,0 +1,59 @@
#ifndef CAMERA_H_
#define CAMERA_H_
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <Eigen/Core>
#include <Eigen/Dense>
#include <Eigen/SparseCore>
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<Camera> CameraPtr;
#endif // CAMERA_H_

View File

@@ -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 <Eigen/Core>
template <bool B> using bool_constant = std::integral_constant<bool, B>;
namespace helper
{
namespace detail
{
template <typename T>
constexpr std::true_type is_matrix(Eigen::MatrixBase<T>);
std::false_type constexpr is_matrix(...);
template <typename T>
constexpr std::true_type is_array(Eigen::ArrayBase<T>);
std::false_type constexpr is_array(...);
}
template <typename T>
struct is_matrix : decltype(detail::is_matrix(std::declval<std::remove_cv_t<T>>()))
{
};
template <typename T>
struct is_array : decltype(detail::is_array(std::declval<std::remove_cv_t<T>>()))
{
};
template <typename T>
using is_matrix_or_array = bool_constant<is_array<T>::value || is_matrix<T>::value>;
/*
* Index something if it's not an scalar
*/
template <typename T, typename std::enable_if<is_matrix_or_array<T>::value, int>::type = 0>
auto index_if_necessary(T&& thing, Eigen::Index idx)
{
return thing(idx);
}
/*
* Overload for scalar.
*/
template <typename T, typename std::enable_if<std::is_scalar<std::decay_t<T>>::value, int>::type = 0>
auto index_if_necessary(T&& thing, Eigen::Index)
{
return thing;
}
}
namespace Eigen
{
template <typename XprType, typename RowIndices, typename ColIndices>
class CircShiftedView;
namespace internal
{
template <typename XprType, typename RowIndices, typename ColIndices>
struct traits<CircShiftedView<XprType, RowIndices, ColIndices>>
: traits<XprType>
{
enum
{
RowsAtCompileTime = traits<XprType>::RowsAtCompileTime,
ColsAtCompileTime = traits<XprType>::ColsAtCompileTime,
MaxRowsAtCompileTime = (RowsAtCompileTime != Dynamic
? int(RowsAtCompileTime)
: int(traits<XprType>::MaxRowsAtCompileTime)),
MaxColsAtCompileTime = (ColsAtCompileTime != Dynamic
? int(ColsAtCompileTime)
: int(traits<XprType>::MaxColsAtCompileTime)),
XprTypeIsRowMajor = (int(traits<XprType>::Flags) & RowMajorBit) != 0,
IsRowMajor = ((MaxRowsAtCompileTime == 1 && MaxColsAtCompileTime != 1) ? 1
: (MaxColsAtCompileTime == 1 && MaxRowsAtCompileTime != 1) ? 0
: XprTypeIsRowMajor),
FlagsRowMajorBit = IsRowMajor ? RowMajorBit : 0,
FlagsLvalueBit = is_lvalue<XprType>::value ? LvalueBit : 0,
Flags = (traits<XprType>::Flags & HereditaryBits) | FlagsLvalueBit | FlagsRowMajorBit
};
};
}
template <typename XprType, typename RowShift, typename ColShift, typename StorageKind>
class CircShiftedViewImpl;
template <typename XprType, typename RowShift, typename ColShift>
class CircShiftedView : public CircShiftedViewImpl<XprType, RowShift, ColShift,
typename internal::traits<XprType>::StorageKind>
{
public:
typedef typename CircShiftedViewImpl<XprType, RowShift, ColShift,
typename internal::traits<XprType>::StorageKind>::Base Base;
EIGEN_GENERIC_PUBLIC_INTERFACE(CircShiftedView)
EIGEN_INHERIT_ASSIGNMENT_OPERATORS(CircShiftedView)
typedef typename internal::ref_selector<XprType>::non_const_type MatrixTypeNested;
typedef typename internal::remove_all<XprType>::type NestedExpression;
template <typename T0, typename T1>
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<XprType>::type&
nestedExpression() const { return m_xpr; }
/** \returns the nested expression */
typename internal::remove_reference<XprType>::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 <typename XprType, typename RowIndices, typename ColIndices, typename StorageKind>
class CircShiftedViewImpl
: public internal::generic_xpr_base<CircShiftedView<XprType, RowIndices, ColIndices>>::type
{
public:
typedef typename internal::generic_xpr_base<CircShiftedView<XprType, RowIndices, ColIndices>>::type Base;
};
namespace internal
{
template <typename ArgType, typename RowIndices, typename ColIndices>
struct unary_evaluator<CircShiftedView<ArgType, RowIndices, ColIndices>, IndexBased>
: evaluator_base<CircShiftedView<ArgType, RowIndices, ColIndices>>
{
typedef CircShiftedView<ArgType, RowIndices, ColIndices> XprType;
enum
{
CoeffReadCost = (evaluator<ArgType>::CoeffReadCost
+ NumTraits<Index>::AddCost /* for comparison */
+ NumTraits<Index>::AddCost) /* for addition */,
Flags = (evaluator<ArgType>::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<ArgType> m_argImpl;
const XprType& m_xpr;
};
} // end namespace internal
} // end namespace Eigen
template <typename XprType, typename RowShift, typename ColShift>
auto circShift(Eigen::DenseBase<XprType>& x, RowShift r, ColShift c)
{
return Eigen::CircShiftedView<XprType, RowShift, ColShift>(x.derived(), r, c);
}
template <typename XprType>
auto fftshift(Eigen::DenseBase<XprType>& x)
{
Eigen::Index rs = x.rows() / 2;
Eigen::Index cs = x.cols() / 2;
return Eigen::CircShiftedView<XprType, Eigen::Index, Eigen::Index>(x.derived(), rs, cs);
}
template <typename XprType>
auto ifftshift(Eigen::DenseBase<XprType>& x)
{
Eigen::Index rs = (x.rows() + 1) / 2;
Eigen::Index cs = (x.cols() + 1) / 2;
return Eigen::CircShiftedView<XprType, Eigen::Index, Eigen::Index>(x.derived(), rs, cs);
}

View File

@@ -0,0 +1,36 @@
#ifndef CORRELATION_FLOW_H
#define CORRELATION_FLOW_H
#include <fftw3.h>
#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<CorrelationFlow> CorrelationFlowPtr;
#endif // CORRELATION_FLOW_H

View File

@@ -0,0 +1,30 @@
#ifndef DATASET_H_
#define DATASET_H_
#include <vector>
#include <Eigen/Dense>
#include <Eigen/SparseCore>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
#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<std::string> _image_names;
std::string _time_file_path;
std::vector<double> _timestamps;
};
#endif // DATASET_H_

View File

@@ -0,0 +1,31 @@
#ifndef EDGE_H_
#define EDGE_H_
#include <string>
#include <Eigen/Dense>
#include <Eigen/SparseCore>
#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<Edge> EdgePtr;
#endif // EDGE_H_

View File

@@ -0,0 +1,45 @@
#ifndef FRAME_H_
#define FRAME_H_
#include <string>
#include <Eigen/Dense>
#include <Eigen/SparseCore>
#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<int>& 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<int> _edge_ids;
};
typedef std::shared_ptr<Frame> FramePtr;
#endif // FRAME_H_

View File

@@ -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<FramePtr>& frames);
private:
LoopClosureConfig _loop_thr;
CorrelationFlowPtr _correlation_flow;
MapPtr _map;
};
typedef std::shared_ptr<LoopClosure> LoopClosurePtr;
#endif // LOOP_CLOSURE_H_

View File

@@ -0,0 +1,81 @@
#ifndef MAP_H_
#define MAP_H_
#include <vector>
#include <map>
#include <unordered_set>
#include <unordered_map>
#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<int>()(loc.x) ^ std::hash<int>()(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<FramePtr> FrameSet;
typedef std::unordered_map<GridLocation, FrameSet, GridLocationHash, GridLocationEqual> 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<FramePtr>& frames);
double GetFrameDistance(FramePtr& frame);
int GetAllEdges(std::vector<EdgePtr>& edges);
void UpdatePoses(AlignedMap<int, Eigen::Vector3d> frame_poses);
GridLocation ComputeGridLocation(double x, double y);
GridLocation ComputeGridLocation(Eigen::Vector3d pose);
int GetFramesInGrids(std::vector<FramePtr>& frames, std::vector<GridLocation>& grid_locations);
FramePtr GetBaseframe();
private:
CameraPtr _camera;
std::map<int, FramePtr> _frames;
std::map<FramePtr, double> _frame_distanses;
std::map<int, EdgePtr> _edges;
double _grid_scale;
GridMap _grid_map;
FramePtr _baseframe;
};
typedef std::shared_ptr<Map> MapPtr;
#endif // MAP_H_

View File

@@ -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<std::vector, Eigen::Vector3d>& poses, std::vector<double>& timestamps);
bool GetOccupancyMapOrigin(
Eigen::Vector3d& pixel_origin, Eigen::Matrix<double, 7, 1>& 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<LoopClosureResult> _loop_matches;
Configs _configs;
CameraPtr _camera;
CorrelationFlowPtr _correlation_flow;
KeyframeSelectionConfig _kfs_config;
MapPtr _map;
LoopClosurePtr _loop_closure;
MapStitcherPtr _map_stitcher;
};
#endif // MAP_BUILDER_H

View File

@@ -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<GridLocation, Cell, GridLocationHash, GridLocationEqual> 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<FramePtr, Eigen::MatrixXi> _raw_images;
OccupancyData _occupancy_data;
};
typedef std::shared_ptr<MapStitcher> MapStitcherPtr;
#endif // MAP_STITCHER_H_

View File

@@ -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 <ceres/local_parameterization.h>
#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 <typename T>
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<AngleLocalParameterization,
1,
1>);
}
};
} // namespace optimization_2d
} // namespace ceres
#endif // OPTIMIZATION_2D_ANGLE_LOCAL_PARAMETERIZATION_H_

View File

@@ -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 <cmath>
#include <ceres/ceres.h>
namespace ceres {
namespace optimization_2d {
// Normalizes the angle in radians between [-pi and pi).
template <typename T>
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_

View File

@@ -0,0 +1,33 @@
#ifndef OPTIMIZATION_2D_POSE_GRAPH_2D_H_
#define OPTIMIZATION_2D_POSE_GRAPH_2D_H_
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <ceres/ceres.h>
#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<Constraint2d>& constraints,
std::map<int, Pose2d>* poses,
ceres::Problem* problem);
void BuildOptimizationProblemWithScale(const std::vector<Constraint2d>& constraints,
std::vector<ScaleData>& scale_data,
const std::vector<int>& scale_data_idx,
std::map<int, Pose2d>* poses,
ceres::Problem* problem);
bool SolveOptimizationProblem(ceres::Problem* problem);
} // namespace optimization_2d
} // namespace ceres
#endif // OPTIMIZATION_2D_POSE_GRAPH_2D_H_

View File

@@ -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 <Eigen/Core>
#include "optimization_2d/normalize_angle.h"
namespace ceres {
namespace optimization_2d {
template <typename T>
Eigen::Matrix<T, 2, 2> RotationMatrix2D(T yaw_radians) {
const T cos_yaw = ceres::cos(yaw_radians);
const T sin_yaw = ceres::sin(yaw_radians);
Eigen::Matrix<T, 2, 2> 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 <typename T>
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<T, 2, 1> p_a(*x_a, *y_a);
const Eigen::Matrix<T, 2, 1> p_b(*x_b, *y_b);
Eigen::Map<Eigen::Matrix<T, 3, 1>> residuals_map(residuals_ptr);
residuals_map.template head<2>() =
RotationMatrix2D(*yaw_a).transpose() * (p_b - p_a) - p_ab_.cast<T>();
residuals_map(2) = NormalizeAngle(
(*yaw_b - *yaw_a) - static_cast<T>(yaw_ab_radians_));
// Scale the residuals by the square root information matrix to account for
// the measurement uncertainty.
residuals_map = sqrt_information_.template cast<T>() * 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<PoseGraph2dErrorTerm, 3, 1, 1, 1, 1, 1, 1>(
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 <typename T>
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<T, 2, 1> p_a(*x_a, *y_a);
const Eigen::Matrix<T, 2, 1> p_b(*x_b, *y_b);
Eigen::Map<Eigen::Matrix<T, 3, 1>> residuals_map(residuals_ptr);
Eigen::Matrix<T, 2, 2> scale_matrix = Eigen::Matrix<T, 2, 2>::Identity();
scale_matrix *= (*scale);
residuals_map.template head<2>() =
RotationMatrix2D(*yaw_a).transpose() * (p_b - p_a) - scale_matrix * p_ab_.cast<T>();
residuals_map(2) = NormalizeAngle(
(*yaw_b - *yaw_a) - static_cast<T>(yaw_ab_radians_));
// Scale the residuals by the square root information matrix to account for
// the measurement uncertainty.
residuals_map = sqrt_information_.template cast<T>() * 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<PoseGraph2dErrorTermWithScale, 3, 1, 1, 1, 1, 1, 1, 1>(
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_

View File

@@ -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 <fstream>
#include <Eigen/Core>
#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_

View File

@@ -0,0 +1,137 @@
#ifndef READ_CONFIGS_H_
#define READ_CONFIGS_H_
#include <iostream>
#include <yaml-cpp/yaml.h>
#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<std::string>();
dataset_config.image_dir_name = dataset_node["image_dir_name"].as<std::string>();
dataset_config.camera_file = dataset_node["camera_config"].as<std::string>();
YAML::Node cf_node = file_node["correlation_flow"];
cf_config.width = cf_node["width"].as<int>();
cf_config.height = cf_node["height"].as<int>();
cf_config.lambda = cf_node["lambda"].as<float>();
cf_config.rotation_divisor = cf_node["rotation_divisor"].as<int>();
cf_config.rotation_channel = cf_node["rotation_channel"].as<int>();
cf_config.kernel = cf_node["kernel"].as<int>();
cf_config.offset = cf_node["polynomial"]["offset"].as<float>();
cf_config.power = cf_node["polynomial"]["power"].as<int>();
cf_config.sigma = cf_node["gaussian"]["sigma"].as<float>();
YAML::Node kfs_node = file_node["keyframe_selection"];
keyframe_selection_config.max_distance = kfs_node["max_distance"].as<double>();
keyframe_selection_config.max_angle = kfs_node["max_angle"].as<double>();
keyframe_selection_config.lower_response_thr = kfs_node["lower_response_thr"].as<double>();
keyframe_selection_config.upper_response_thr = kfs_node["upper_response_thr"].as<double>();
YAML::Node map_node = file_node["map"];
map_config.grid_scale = map_node["grid_scale"].as<double>();
YAML::Node loop_closure_node = file_node["loop_closure"];
loop_closure_config.to_find_loop =
loop_closure_node["to_find_loop"].as<bool>();
loop_closure_config.position_response_thr =
loop_closure_node["position_response_thr"].as<double>();
loop_closure_config.angle_response_thr =
loop_closure_node["angle_response_thr"].as<double>();
loop_closure_config.frame_gap_thr =
loop_closure_node["frame_gap_thr"].as<int>();
loop_closure_config.distance_thr =
loop_closure_node["distance_thr"].as<double>();
YAML::Node map_stitcher_node = file_node["map_sticther"];
map_stitcher_config.stitch_map = map_stitcher_node["stitch_map"].as<bool>();
map_stitcher_config.cell_size = map_stitcher_node["cell_size"].as<int>();
YAML::Node visualization_node = file_node["visualization"];
visualization_config.frame_id = visualization_node["frame_id"].as<std::string>();
visualization_config.kcc_pose_topic = visualization_node["topic"]["kcc_pose"].as<std::string>();
visualization_config.frame_pose_topic = visualization_node["topic"]["frame_pose"].as<std::string>();
visualization_config.map_topic = visualization_node["topic"]["map"].as<std::string>();
visualization_config.image_topic = visualization_node["topic"]["image"].as<std::string>();
YAML::Node saving_node = file_node["saving"];
saving_config.saving_root = saving_node["saving_root"].as<std::string>();
saving_config.save_pose = saving_node["save_pose"].as<bool>();
}
};
#endif // READ_CONFIGS_H_

View File

@@ -0,0 +1,32 @@
#ifndef THREAD_PUBLISHER_H_
#define THREAD_PUBLISHER_H_
#include <string>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <vector>
#include <queue>
#include <functional>
template <typename T>
class ThreadPublisher {
public:
ThreadPublisher();
~ThreadPublisher();
void Register(std::function<void(const std::shared_ptr<const T>&)> cb);
void Start();
void Publish(const std::shared_ptr<const T> msg);
void Process();
void ShutDown();
private:
std::mutex msg_mutex_;
std::condition_variable msg_cond_;
std::queue<std::shared_ptr<const T>> msgs_;
std::thread publish_thread_;
std::vector<std::function<void(const std::shared_ptr<const T>&)>> callbacks_;
bool shutdown_requested_;
};
#endif // THREAD_PUBLISHER_H_

27
src/ground_slam/include/timer.h Executable file
View File

@@ -0,0 +1,27 @@
#ifndef _TIMER_H_
#define _TIMER_H_
#include <sys/time.h>
#include <stdio.h>
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_

View File

@@ -0,0 +1,82 @@
#ifndef UTILS_H_
#define UTILS_H_
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sys/types.h>
#include <sys/stat.h>
#include <functional>
#include <map>
#include <limits.h>
#include <memory>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <Eigen/Core>
#include <Eigen/StdVector>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/core/eigen.hpp>
// Eigen type
template <template <typename, typename> class Container, typename Type>
using Aligned = Container<Type, Eigen::aligned_allocator<Type>>;
template <typename KeyType, typename ValueType>
using AlignedMap =
std::map<KeyType, ValueType, std::less<KeyType>,
Eigen::aligned_allocator<std::pair<const KeyType, ValueType>>>;
template <typename KeyType, typename ValueType>
using AlignedUnorderedMap = std::unordered_map<
KeyType, ValueType, std::hash<KeyType>, std::equal_to<KeyType>,
Eigen::aligned_allocator<std::pair<const KeyType, ValueType>>>;
template <typename KeyType, typename ValueType>
using AlignedUnorderedMultimap = std::unordered_multimap<
KeyType, ValueType, std::hash<KeyType>, std::equal_to<KeyType>,
Eigen::aligned_allocator<std::pair<const KeyType, ValueType>>>;
template <typename Type>
using AlignedUnorderedSet =
std::unordered_set<Type, std::hash<Type>, std::equal_to<Type>,
Eigen::aligned_allocator<Type>>;
// files
bool FileExists(const std::string& file);
bool PathExists(const std::string& path);
void ConcatenateFolderAndFileName(
const std::string& folder, const std::string& file_name,
std::string* path);
std::string ConcatenateFolderAndFileName(
const std::string& folder, const std::string& file_name);
void MakeDir(const std::string& path);
void ReadTxt(const std::string& file_path,
std::vector<std::vector<std::string> >& lines, std::string seq);
void WriteTxt(const std::string file_path,
std::vector<std::vector<std::string> >& lines, std::string seq);
// correlation flow
void ConvertMatToNormalizedArray(cv::Mat& image, Eigen::ArrayXXf& array);
Eigen::ArrayXXf ConvertMatToArray(const cv::Mat&);
cv::Mat ConvertArrayToMat(const Eigen::ArrayXXf&);
Eigen::ArrayXXf RotateArray(const Eigen::ArrayXXf&, float);
Eigen::ArrayXXf WarpArray(const Eigen::ArrayXXf&, float tx, float ty, float degree);
double NormalizeDegree(double angle_degree);
// Eigen pose
Eigen::Vector3d ComputeRelativePose(Eigen::Vector3d& pose1, Eigen::Vector3d& pose2);
Eigen::Vector3d ComputeAbsolutePose(Eigen::Vector3d& pose1, Eigen::Vector3d& relative_pose);
void ShowArray(const Eigen::ArrayXXf&, std::string window="debug", int waitKey=1);
#endif // UTILS_H_

View File

@@ -0,0 +1,65 @@
#ifndef VISUALIZATION_H_
#define VISUALIZATION_H_
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <functional>
#include <map>
#include <memory>
#include <Eigen/Core>
#include <rclcpp/rclcpp.hpp>
#include <nav_msgs/msg/path.hpp>
#include <geometry_msgs/msg/quaternion.hpp>
#include <geometry_msgs/msg/pose_stamped.hpp>
#include <nav_msgs/msg/occupancy_grid.hpp>
#include <nav_msgs/msg/odometry.hpp>
#include <sensor_msgs/msg/image.hpp>
#include <sensor_msgs/msg/point_cloud2.hpp>
#include <cv_bridge/cv_bridge.h>
#include "read_configs.h"
#include "map_stitcher.h"
#include "map_builder.h"
class Visualizer {
public:
enum class TrajectoryType {
Frame = 0,
KCC = 1,
Odom = 2,
};
Visualizer(rclcpp::Node::SharedPtr node, VisualizationConfig& config);
void AddNewPoseToPath(
Eigen::Vector3d& pose, double time_double,
nav_msgs::msg::Path& path, std::string& frame_id);
void UpdateOdomPose(Eigen::Vector3d& pose, double time_double);
void UpdateKccPose(Eigen::Vector3d& pose, double time_double);
void UpdateFramePose(Aligned<std::vector, Eigen::Vector3d>& frame_poses,
std::vector<double>& timestamps);
void ConvertMapToOccupancyMsgs(OccupancyData& map,
nav_msgs::msg::OccupancyGrid& msgs);
void UpdateMap(MapBuilder& map_builder);
void PublishImage(cv::Mat& image, double time_double);
void GetTrajectoryTxt(std::vector<std::vector<std::string>>& lines,
TrajectoryType trajectory_type);
private:
rclcpp::Node::SharedPtr node_;
std::string frame_id_;
rclcpp::Publisher<nav_msgs::msg::Path>::SharedPtr kcc_pose_pub_;
rclcpp::Publisher<nav_msgs::msg::Path>::SharedPtr frame_pose_pub_;
rclcpp::Publisher<nav_msgs::msg::OccupancyGrid>::SharedPtr map_pub_;
rclcpp::Publisher<sensor_msgs::msg::Image>::SharedPtr image_pub_;
nav_msgs::msg::Path odom_pose_msgs_;
nav_msgs::msg::Path kcc_pose_msgs_;
nav_msgs::msg::Path frame_pose_msgs_;
nav_msgs::msg::OccupancyGrid occupancy_map_msgs_;
};
#endif // VISUALIZATION_H_

110
src/ground_slam/main.cpp Executable file
View File

@@ -0,0 +1,110 @@
#include <iostream>
#include <iomanip>
#include <queue>
#include <string>
#include <unistd.h>
#include <Eigen/Dense>
#include <opencv2/highgui/highgui.hpp>
#include <rclcpp/rclcpp.hpp>
#include <cv_bridge/cv_bridge.h>
#include "read_configs.h"
#include "dataset.h"
#include "camera.h"
#include "frame.h"
#include "map_stitcher.h"
#include "map_builder.h"
#include "thread_publisher.h"
#include "visualization.h"
#include <typeinfo>
#include <time.h>
using namespace std;
class GroundSlamNode : public rclcpp::Node {
public:
GroundSlamNode(const std::string& config_file)
: Node("build_map"), configs_(config_file) {}
void run() {
DatasetConfig dataset_config = configs_.dataset_config;
Dataset dataset(dataset_config.dataroot, dataset_config.image_dir_name);
MapBuilder map_builder(configs_);
Visualizer visualizer(this->shared_from_this(), configs_.visualization_config);
Aligned<std::vector, Eigen::Vector3d> frame_poses;
std::vector<double> timestamps;
Eigen::Vector3d new_kcc_pose;
size_t dataset_length = dataset.GetDatasetLength();
for (size_t i = 0; i < dataset_length; ++i) {
if (!rclcpp::ok()) break;
std::cout << i << std::endl;
cv::Mat image;
if (!dataset.GetImage(image, i)) {
std::cout << "can not get image " << i << std::endl;
break;
}
double time_double = dataset.GetTimestamp(i);
visualizer.PublishImage(image, time_double);
auto t1 = std::chrono::high_resolution_clock::now();
bool insert_keyframe = map_builder.AddNewInput(image, time_double);
auto t2 = std::chrono::high_resolution_clock::now();
auto compute_time = std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count() / 1e3;
std::cout << "processing for one frame is " << compute_time << "ms" << std::endl;
if ((i + 1) >= dataset_length) {
map_builder.CheckAndOptimize();
} else if (!insert_keyframe) {
continue;
}
std::cout << "Insert a keyframe !" << std::endl;
if (map_builder.GetCFPose(new_kcc_pose)) {
visualizer.UpdateKccPose(new_kcc_pose, time_double);
}
if (map_builder.GetFramePoses(frame_poses, timestamps)) {
visualizer.UpdateFramePose(frame_poses, timestamps);
}
visualizer.UpdateMap(map_builder);
rclcpp::spin_some(this->shared_from_this());
}
// save trajectories
std::string saving_root = configs_.saving_config.saving_root;
MakeDir(saving_root);
std::string trajectory_KCC = saving_root + "/KCC_Keyframe.txt";
std::string trajectory_frame = saving_root + "/optimized_keyframe.txt";
std::vector<std::vector<std::string>> kcc_keyframe_lines, optimized_keyframe_lines;
visualizer.GetTrajectoryTxt(kcc_keyframe_lines, Visualizer::TrajectoryType::KCC);
visualizer.GetTrajectoryTxt(optimized_keyframe_lines, Visualizer::TrajectoryType::Frame);
WriteTxt(trajectory_KCC, kcc_keyframe_lines, " ");
WriteTxt(trajectory_frame, optimized_keyframe_lines, " ");
}
private:
Configs configs_;
};
int main(int argc, char** argv) {
rclcpp::init(argc, argv);
if (argc < 2) {
std::cerr << "Usage: ground_slam <config_yaml>" << std::endl;
rclcpp::shutdown();
return 1;
}
auto node = std::make_shared<GroundSlamNode>(argv[1]);
node->run();
rclcpp::shutdown();
return 0;
}

View File

@@ -0,0 +1,27 @@
<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
<name>ground_slam</name>
<version>0.1.0</version>
<description>GroundSLAM: Feature-free ground-texture-based visual SLAM for warehouse robots (ROS2 port)</description>
<maintainer email="sunrise@todo.todo">sunrise</maintainer>
<license>MIT</license>
<buildtool_depend>ament_cmake</buildtool_depend>
<depend>rclcpp</depend>
<depend>geometry_msgs</depend>
<depend>visualization_msgs</depend>
<depend>nav_msgs</depend>
<depend>std_msgs</depend>
<depend>sensor_msgs</depend>
<depend>cv_bridge</depend>
<depend>tf2</depend>
<depend>tf2_geometry_msgs</depend>
<depend>tf2_ros</depend>
<export>
<build_type>ament_cmake</build_type>
</export>
</package>

View File

@@ -0,0 +1,243 @@
#include <yaml-cpp/yaml.h>
#include <math.h>
#include <unistd.h>
#include <iostream>
#include "camera.h"
#include "utils.h"
#include "optimization_2d/pose_graph_2d_error_term.h"
using namespace std;
Camera::Camera(){
}
Camera::Camera(const std::string& camera_file){
if(!FileExists(camera_file)){
std::cout << "camera file: " << camera_file << " doesn't exist" << std::endl;
return;
}
YAML::Node file_node = YAML::LoadFile(camera_file);
_image_width = file_node["image_size"][0].as<int>();
_image_height = file_node["image_size"][1].as<int>();
_height = file_node["height"].as<double>();
_accurate_height = file_node["accurate_height"].as<bool>();
_new_scale = 0;
_new_width = 0;
_new_height = 0;
YAML::Node K_node = file_node["intrinsics"]["data"];
double fx = K_node[0].as<double>();
double cx = K_node[1].as<double>();
double fy = K_node[2].as<double>();
double cy = K_node[3].as<double>();
_K = (cv::Mat_<double>(3, 3) << fx, 0.0, cx, 0.0, fy, cy, 0.0, 0.0, 1.0);
YAML::Node D_node = file_node["distortion"]["data"];
double D_data[5];
for(size_t i = 0; i < 5; i++){
D_data[i] = D_node[i].as<double>();
}
_D = (cv::Mat_<double>(5, 1) << D_data[0], D_data[1], D_data[2], D_data[3], D_data[4]);
cv::Size image_size(_image_width, _image_height);
_new_K = getOptimalNewCameraMatrix(_K, _D, image_size, 0, image_size);
initUndistortRectifyMap(_K, _D, cv::Mat(), _new_K, image_size, CV_16SC2, _map1, _map2);
// // update _new_K
// if(_image_width > _image_height)
// {
// _scale = min(_new_K.at<double>(0,0), _new_K.at<double>(1,1)) / max(_new_K.at<double>(0,0), _new_K.at<double>(1,1));
// _new_width = round(_image_width * _scale);
// _new_scale = double(_new_width) / double(_image_width);
// cout << "_new width: " << _new_width << endl;
// _new_K.at<double>(0,0) = _new_K.at<double>(0,0) / _new_scale;
// _new_K.at<double>(0,2) = _new_K.at<double>(0,2) / _new_scale;
// _image_width = _new_width;
// }
// else{
// _scale = min(_new_K.at<double>(0,0), _new_K.at<double>(1,1)) / max(_new_K.at<double>(0,0), _new_K.at<double>(1,1));
// _new_height = round(_image_height * _scale);
// _new_scale = _new_height / _image_height;
// _new_K.at<double>(1,1) = _new_K.at<double>(1,1) / _new_scale;
// _new_K.at<double>(1,2) = _new_K.at<double>(1,2) / _new_scale;
// _image_height = _new_height;
// }
YAML::Node E_node = file_node["extrinsics"]["data"];
for(size_t i = 0; i < 3; i++){
for(size_t j = 0; j < 3; j++){
size_t idx = 3 * i + j;
_extrinsics(i, j) = E_node[idx].as<double>();
}
}
}
Camera& Camera::operator=(const Camera& camera){
_image_height = camera._image_height;
_image_width = camera._image_width;
_height = camera._height;
_accurate_height = camera._accurate_height;
_K = camera._K.clone();
_new_K = camera._new_K;
_D = camera._D.clone();
_map1 = camera._map1.clone();
_map2 = camera._map2.clone();
_extrinsics = camera._extrinsics;
return *this;
}
void Camera::UndistortImage(cv::Mat& image, cv::Mat& undistort_image){
remap(image, undistort_image, _map1, _map2, cv::INTER_LINEAR);
// cv::Mat _new_undistort_image;
// if(_new_height == 0 && _new_scale != 0){
// resize(undistort_image, _new_undistort_image, cv::Size(), _new_scale, 1.0, cv::INTER_LINEAR);
// }
// else if(_new_width == 0 && _new_scale != 0){
// resize(undistort_image, _new_undistort_image, cv::Size(), 1.0, _new_scale, cv::INTER_LINEAR);
// }
// _new_undistort_image.copyTo(undistort_image);
}
void Camera::GetNewCameraMatrix(cv::Mat& camera_matrix){
camera_matrix = _new_K.clone();
}
double Camera::GetImageHeight(){
return _image_height;
}
bool Camera::HeightIsAccurate(){
return _accurate_height;
}
double Camera::GetImageWidth(){
return _image_width;
}
double Camera::GetHeight(){
return _height;
}
void Camera::GetExtrinsics(Eigen::Matrix3d& extrinsics){
extrinsics = _extrinsics;
}
double Camera::GetLengthOfPixel(){
Eigen::Vector3d pixel(1.0, 1.0, 0.0);
Eigen::Vector3d real;
ConvertImagePlanePoseToRobot(pixel, real);
return (real(0) + real(1)) / 2;
}
Eigen::Vector3d Camera::ConvertPrincipalToCenter(const Eigen::Vector3d& image_plane_pose){
Eigen::Vector3d image_center_pose;
const Eigen::Matrix2d I2 = Eigen::Matrix2d::Identity();
image_center_pose(2) = image_plane_pose(2);
Eigen::Matrix2d R = ceres::optimization_2d::RotationMatrix2D(image_plane_pose(2));
Eigen::Vector2d O_bias;
O_bias << (_image_width * 0.5 - _new_K.at<double>(0, 2)), (_image_height * 0.5 - _new_K.at<double>(1, 2));
image_center_pose.head(2) = image_plane_pose.head(2) - (I2 - R) * O_bias;
return image_center_pose;
}
Eigen::Vector3d Camera::ConvertCenterToPrincipal(const Eigen::Vector3d& image_center_pose){
Eigen::Vector3d image_plane_pose;
const Eigen::Matrix2d I2 = Eigen::Matrix2d::Identity();
image_plane_pose(2) = image_center_pose(2);
Eigen::Matrix2d R = ceres::optimization_2d::RotationMatrix2D(image_center_pose(2));
Eigen::Vector2d O_bias;
O_bias << (_image_width * 0.5 - _new_K.at<double>(0, 2)), (_image_height * 0.5 - _new_K.at<double>(1, 2));
image_plane_pose.head(2) = image_center_pose.head(2) + (I2 - R) * O_bias;
return image_plane_pose;
}
bool Camera::ConvertImagePlanePoseToCamera(
Eigen::Vector3d& image_plane_pose, Eigen::Vector3d& camera_pose){
double u = image_plane_pose(0);
double v = image_plane_pose(1);
double angle = image_plane_pose(2);
double fx = _new_K.at<double>(0, 0);
// double cx = _new_K.at<double>(0, 2);
double fy = _new_K.at<double>(1, 1);
// double cy = _new_K.at<double>(1, 2);
double x = u / fx;
double y = v / fy;
camera_pose << x, y, angle;
return true;
}
bool Camera::ConvertCameraPoseToImagePlane(
Eigen::Vector3d& image_plane_pose, Eigen::Vector3d& camera_pose){
double x = camera_pose(0);
double y = camera_pose(1);
double angle = camera_pose(2);
double fx = _new_K.at<double>(0, 0);
// double cx = _new_K.at<double>(0, 2);
double fy = _new_K.at<double>(1, 1);
// double cy = _new_K.at<double>(1, 2);
double u = fx * x;
double v = fy * y;
image_plane_pose << u, v, angle;
return true;
}
bool Camera::ConvertCameraPoseToRobot(
Eigen::Vector3d& camera_pose, Eigen::Vector3d& robot_pose){
if(_height < 0){
std::cout << "camera height: " << _height << " < 0" << std::endl;
return false;
}
double x = _height * camera_pose(0);
double y = _height * camera_pose(1);
robot_pose << x, y, camera_pose(2);
robot_pose = _extrinsics * robot_pose;
return true;
}
bool Camera::ConvertRobotPoseToCamera(
Eigen::Vector3d& camera_pose, Eigen::Vector3d& robot_pose){
if(_height < 0){
std::cout << "camera height: " << _height << " < 0" << std::endl;
return false;
}
camera_pose = _extrinsics.inverse() * robot_pose;
camera_pose(0) /= _height;
camera_pose(1) /= _height;
return true;
}
bool Camera::ConvertImagePlanePoseToRobot(
Eigen::Vector3d& image_plane_pose, Eigen::Vector3d& robot_pose){
Eigen::Vector3d camera_pose;
bool c1 = ConvertImagePlanePoseToCamera(image_plane_pose, camera_pose);
bool c2 = ConvertCameraPoseToRobot(camera_pose, robot_pose);
return (c1 && c2);
}
bool Camera::ConvertRobotPoseToImagePlane(
Eigen::Vector3d& image_plane_pose, Eigen::Vector3d& robot_pose){
Eigen::Vector3d camera_pose;
bool c1 = ConvertRobotPoseToCamera(camera_pose, robot_pose);
bool c2 = ConvertCameraPoseToImagePlane(image_plane_pose, camera_pose);
return (c1 && c2);
}

View File

@@ -0,0 +1,228 @@
#include <math.h>
#include <opencv2/imgproc.hpp>
#include "correlation_flow.h"
#include "read_configs.h"
#include "circ_shift.h"
#include "optimization_2d/pose_graph_2d_error_term.h"
#include <iostream>
#include <fstream>
using namespace std;
#include "unistd.h"
#include <chrono>
using namespace std::chrono;
// // void PrintArrayToFile (const Eigen::ArrayXXf target, int rows, int cols) {
// void PrintArrayToFile (const auto& target, int rows, int cols) {
// ofstream myfile ("example.txt");
// if (myfile.is_open())
// {
// for(int count_row = 0; count_row < rows; count_row ++){
// for(int count_col = 0; count_col < cols; count_col ++){
// myfile << target(count_row, count_col) << " " ;
// if(count_col == cols - 1){
// myfile << "\n";
// }
// }
// }
// myfile.close();
// }
// else std::cout << "Unable to open file";
// }
CorrelationFlow::CorrelationFlow(CFConfig& cf_config, double &image_height, double &image_width):cfg(cf_config){
cfg.height = int(image_height);
cfg.width = int(image_width);
target_fft = GetTargetFFT(cfg.height, cfg.width);
target_rotation_fft = GetTargetFFT(cfg.rotation_divisor, cfg.rotation_channel);
}
Eigen::ArrayXXcf CorrelationFlow::GetTargetFFT(int rows, int cols){
Eigen::ArrayXXf target = Eigen::ArrayXXf::Zero(rows, cols);
target(rows/2, cols/2) = 1;
return FFT(target);
}
Eigen::ArrayXXcf CorrelationFlow::FFT(const Eigen::ArrayXXf& x){
Eigen::ArrayXXcf xf = Eigen::ArrayXXcf(x.rows()/2+1, x.cols()); // xf [225, 448]
fftwf_plan fft_plan = fftwf_plan_dft_r2c_2d(x.cols(), x.rows(), (float(*))(x.data()),
(float(*)[2])(xf.data()), FFTW_ESTIMATE); // reverse order for column major
fftwf_execute(fft_plan);
fftwf_destroy_plan(fft_plan);
fftw_cleanup();
return xf;
}
Eigen::ArrayXXf CorrelationFlow::IFFT(const Eigen::ArrayXXcf& xf){
Eigen::ArrayXXf x = Eigen::ArrayXXf((xf.rows()-1)*2, xf.cols());
Eigen::ArrayXXcf cxf = xf;
fftwf_plan fft_plan = fftwf_plan_dft_c2r_2d(xf.cols(), (xf.rows()-1)*2, (float(*)[2])(cxf.data()),
(float(*))(x.data()), FFTW_ESTIMATE);
fftwf_execute(fft_plan);
fftwf_destroy_plan(fft_plan);
fftw_cleanup();
return x/x.size();
}
inline Eigen::ArrayXXf CorrelationFlow::RemoveZeroComponent(const Eigen::ArrayXXf& x){
Eigen::ArrayXXf y(x);
unsigned int cols = x.cols();
unsigned int rows = x.rows();
y.block(0, 0, 1, cols) = (x.block(1, 0, 1, cols) + x.block(rows-1, 0, 1, cols))/2.0;
y.block(0, 0, rows, 1) = (x.block(0, 1, rows, 1) + x.block(0, cols-1, rows, 1))/2.0;
return y;
}
void CorrelationFlow::ComputeIntermedium(const Eigen::ArrayXXf& image, Eigen::ArrayXXcf& fft_result, Eigen::ArrayXXcf& fft_polar){
fft_result = FFT(image);
Eigen::ArrayXXf power = IFFT(fft_result.abs());
auto high_power = RemoveZeroComponent(power);
fft_polar = FFT(polar(fftshift(high_power)));
}
Eigen::Vector3d CorrelationFlow::ComputePose(const Eigen::ArrayXXcf& last_fft_result, const Eigen::ArrayXXf& image,
const Eigen::ArrayXXcf& last_fft_polar, const Eigen::ArrayXXcf& fft_polar,
Eigen::Vector3d& pose, bool not_large_rotation){
Eigen::Vector2d trans, trans_orig, trans_veri, rots; Eigen::Vector3d info; float info_trans;
auto info_rots = EstimateTrans(last_fft_polar, fft_polar, target_rotation_fft, cfg.rotation_divisor, cfg.rotation_channel, rots);
float degree = rots[0]*(2.0/cfg.rotation_divisor)*180;
degree = NormalizeDegree(degree);
if(not_large_rotation){
degree = std::abs(degree) > 90 ? degree - 180 : degree;
auto fft_rot_orig = FFT(RotateArray(image, -degree));
float info_trans_orig = EstimateTrans(last_fft_result, fft_rot_orig, target_fft, cfg.height, cfg.width, trans_orig);
info_trans = info_trans_orig;
trans = trans_orig;
degree = degree;
}else{
auto fft_rot_orig = FFT(RotateArray(image, -degree));
auto fft_rot_veri = FFT(RotateArray(image, -degree+180));
float info_trans_orig = EstimateTrans(last_fft_result, fft_rot_orig, target_fft, cfg.height, cfg.width, trans_orig); //error
float info_trans_veri = EstimateTrans(last_fft_result, fft_rot_veri, target_fft, cfg.height, cfg.width, trans_veri);
if (info_trans_orig > info_trans_veri)
{
info_trans = info_trans_orig;
trans = trans_orig;
degree = degree;
}
else{
info_trans = info_trans_veri;
trans = trans_veri;
degree = degree + 180;
}
}
(degree>180)? degree=degree-360 : degree=degree;
float theta = degree/180*M_PI;
info[0] = info_trans; pose[0] = trans[1];
info[1] = info_trans; pose[1] = trans[0];
info[2] = info_rots; pose[2] = theta;
std::cout<<"X, Y, \u0398: "<<pose.transpose()<<" Rad = "<< degree <<"Degree"<<std::endl;
std::cout<<"Info: "<<info.transpose()<<std::endl;
auto rectify = WarpArray(IFFT(last_fft_result),-pose[0],-pose[1], degree);
return info;
}
float CorrelationFlow::EstimateTrans(const Eigen::ArrayXXcf& last_fft_result, const Eigen::ArrayXXcf& fft_result,
const Eigen::ArrayXXcf& output_fft, int height, int width, Eigen::Vector2d& trans){
/// @brief can esrimate translation, rotation, and scale
/// @param last_fft_result fft result of key frame
/// @param fft_result current frame's fft result
/// @param output_fft target_rotation_fft generate from GetTargetFFT(720, 480)
/// @param height cfg.rotation_divisor
/// @param width cfg.rotation_channel
/// @param trans the result, ie. rotation degree, notice that the trans length is two, trans[0] is actually the degree we need
Eigen::ArrayXXcf Kzz, Kxz;
switch(cfg.kernel) {
case 0:
Kzz = polynomial_kernel(last_fft_result, height, width);
Kxz = polynomial_kernel(fft_result, last_fft_result, height, width);
break;
case 1:
Kzz = gaussian_kernel(last_fft_result, height, width);
Kxz = gaussian_kernel(fft_result, last_fft_result, height, width);
break;
default:
throw std::invalid_argument( "Received invalid kernel type" );
}
auto H = output_fft/(Kzz + cfg.lambda);
Eigen::ArrayXXcf G = H*Kxz;
Eigen::ArrayXXf g = IFFT(G);
Eigen::ArrayXXf::Index row, col;
float response = g.maxCoeff(&(row), &(col));
trans[0] = -(row-height/2);
trans[1] = -(col-width/2);
return GetInfo(g, response);
}
inline Eigen::ArrayXXcf CorrelationFlow::gaussian_kernel(const Eigen::ArrayXXcf& xf, const Eigen::ArrayXXcf& zf, int height, int width){
unsigned int N = height * width;
auto xx = xf.square().abs().sum()/N; // Parseval's Theorem
auto zz = zf.square().abs().sum()/N;
auto zfc = zf.conjugate();
Eigen::ArrayXXcf xzf = xf * zfc;
auto xz = IFFT(xzf);
auto xxzz = (xx+zz-2*xz)/N;
Eigen::ArrayXXf kernel = (-1/(cfg.sigma*cfg.sigma)*xxzz).exp();
kernel = kernel/kernel.abs().maxCoeff();
return FFT(kernel);
}
inline Eigen::ArrayXXcf CorrelationFlow::gaussian_kernel(const Eigen::ArrayXXcf& xf, int height, int width){
unsigned int N = height * width;
auto xx = xf.square().abs().sum()/N; // Parseval's Theorem
auto zfc = xf.conjugate();
Eigen::ArrayXXcf xzf = xf * zfc;
auto xz = IFFT(xzf);
auto xxzz = (xx+xx-2*xz)/N;
Eigen::ArrayXXf kernel = (-1/(cfg.sigma*cfg.sigma)*xxzz).exp();
kernel = kernel/kernel.abs().maxCoeff();
return FFT(kernel);
}
inline Eigen::ArrayXXcf CorrelationFlow::polynomial_kernel(const Eigen::ArrayXXcf& xf, const Eigen::ArrayXXcf& zf, int height, int width){
auto zfc = zf.conjugate();
Eigen::ArrayXXcf xzf = xf * zfc;
auto xz = IFFT(xzf);
Eigen::ArrayXXf kernel = (xz+cfg.offset).pow(cfg.power);
kernel = kernel/kernel.abs().maxCoeff();
return FFT(kernel);
}
inline Eigen::ArrayXXcf CorrelationFlow::polynomial_kernel(const Eigen::ArrayXXcf& xf, int height, int width){
auto zfc = xf.conjugate();
Eigen::ArrayXXcf xzf = xf * zfc;
auto xz = IFFT(xzf);
Eigen::ArrayXXf kernel = (xz+cfg.offset).pow(cfg.power);
kernel = kernel/kernel.abs().maxCoeff();
return FFT(kernel);
}
inline Eigen::ArrayXXf CorrelationFlow::polar(const Eigen::ArrayXXf& array){
cv::Mat polar_img, img=ConvertArrayToMat(array);
cv::Point2f center((float)img.cols/2, (float)img.rows/2);
double radius = (double)std::min(img.rows/2, img.cols/2);
cv::Size dsize = cv::Size(cfg.rotation_channel, cfg.rotation_divisor);
cv::warpPolar(img, polar_img, dsize, center, radius, cv::INTER_LINEAR + cv::WARP_FILL_OUTLIERS);
return ConvertMatToArray(polar_img);
}
inline float CorrelationFlow::GetInfo(const Eigen::ArrayXXf& output, float response){
float side_lobe_mean = (output.sum()-response)/(output.size()-1);
float std = sqrt((output-side_lobe_mean).square().mean());
return (response - side_lobe_mean)/(std+1e-7);
}

View File

@@ -0,0 +1,55 @@
#include "dataset.h"
#include "utils.h"
#include<iostream>
#include <unistd.h>
using namespace std;
Dataset::Dataset(const std::string& dataroot, const std::string& image_dir_name): _dataroot(dataroot){
if(!PathExists(dataroot)){
std::cout << "dataroot : " << dataroot << " doesn't exist" << std::endl;
exit(0);
}
_image_dir = ConcatenateFolderAndFileName(_dataroot, image_dir_name);
_image_name_file_path = ConcatenateFolderAndFileName(_dataroot, "image_names.txt");
_time_file_path = ConcatenateFolderAndFileName(_dataroot, "times.txt");
std::vector<std::vector<std::string> > image_names_data;
ReadTxt(_image_name_file_path, image_names_data, ",");
for(std::vector<std::string>& line : image_names_data){
_image_names.emplace_back(line[0]);
}
std::vector<std::vector<std::string> > timestamps_data;
if(FileExists(_time_file_path)){
ReadTxt(_time_file_path, timestamps_data, ",");
for(std::vector<std::string>& line : timestamps_data){
_timestamps.push_back(atof(line[0].c_str()));
}
}
}
size_t Dataset::GetDatasetLength(){
return _image_names.size();
}
bool Dataset::GetImage(cv::Mat& image, size_t idx){
if(idx >= _image_names.size()){
return false;
}
std::string image_name = _image_names[idx];
std::string image_path = ConcatenateFolderAndFileName(_image_dir, image_name);
image = cv::imread(image_path, cv::ImreadModes::IMREAD_GRAYSCALE);
return true;
}
double Dataset::GetTimestamp(size_t idx){
if(idx < _timestamps.size()){
return _timestamps[idx];
}else{
return -1.0;
}
}

View File

@@ -0,0 +1,9 @@
#include "edge.h"
Edge::Edge(){
}
Edge::Edge(int edge_id, Type type, int from, int to, Eigen::Vector3d& T, Eigen::Matrix3d& information):
_edge_id(edge_id), _type(type), _from(from), _to(to), _T(T), _information(information){
}

View File

@@ -0,0 +1,77 @@
#include "frame.h"
Frame::Frame(){
}
Frame::Frame(int frame_id): _frame_id(frame_id){
}
Frame::Frame(int frame_id, double timestamp, Eigen::ArrayXXf& frame, Eigen::ArrayXXcf& fft_result, Eigen::ArrayXXcf& fft_polar):
_frame_id(frame_id), _timestamp(timestamp), _frame(frame), _fft_result(fft_result), _fft_polar(fft_polar){
}
Frame& Frame::operator=(const Frame& other){
_frame_id = other._frame_id;
_timestamp = other._timestamp;
_fft_result = other._fft_result;
_fft_polar = other._fft_polar;
_pose = other._pose;
_edge_ids = other._edge_ids;
return *this;
}
void Frame::SetFrameId(int frame_id){
_frame_id = frame_id;
}
int Frame::GetFrameId(){
return _frame_id;
}
double Frame::GetTimestamp(){
return _timestamp;
}
Eigen::ArrayXXf Frame::GetFrame(){
return _frame;
}
void Frame::SetFFTResult(Eigen::ArrayXXcf& fft_result){
_fft_result = fft_result;
}
void Frame::SetFFTResult(Eigen::ArrayXXcf& fft_result,
Eigen::ArrayXXcf& fft_polar){
_fft_result = fft_result;
_fft_polar = fft_polar;
}
void Frame::GetFFTResult(Eigen::ArrayXXcf& fft_result){
fft_result = _fft_result;
}
void Frame::GetFFTResult(Eigen::ArrayXXcf& fft_result,
Eigen::ArrayXXcf& fft_polar){
fft_result = _fft_result;
fft_polar = _fft_polar;
}
void Frame::SetPose(Eigen::Vector3d& pose){
_pose = pose;
}
void Frame::GetPose(Eigen::Vector3d& pose){
pose = _pose;
}
void Frame::AddEdge(int edge_id){
_edge_ids.emplace_back(edge_id);
}
void Frame::GetEdgeIds(std::vector<int>& edge_ids){
edge_ids = _edge_ids;
}
void Frame::SaveToDisk(const std::string root_dir){
//TODO
}

View File

@@ -0,0 +1,74 @@
#include "loop_closure.h"
#include <cmath>
LoopClosure::LoopClosure(LoopClosureConfig& loop_closure_config,
CorrelationFlowPtr correlation_flow, MapPtr map):
_loop_thr(loop_closure_config), _correlation_flow(correlation_flow), _map(map){
}
LoopClosureResult LoopClosure::FindLoopClosure(Eigen::ArrayXXf& image, FramePtr& current_frame){
std::vector<FramePtr> frames;
_map->GetAllFrames(frames);
LoopClosureResult result = FindLoopClosure(image, current_frame, frames);
return result;
}
LoopClosureResult LoopClosure::FindLoopClosure(
Eigen::ArrayXXf& image, FramePtr& current_frame, Eigen::Vector3d& prior_pose){
std::vector<GridLocation> grid_locations;
GridLocation grid_location = _map->ComputeGridLocation(prior_pose);
for(int i = -1; i <= 1; i++){
for(int j = -1; j <= 1; j++){
GridLocation gl = grid_location;
gl.x += i;
gl.y += j;
grid_locations.emplace_back(gl);
}
}
std::vector<FramePtr> frames;
_map->GetFramesInGrids(frames, grid_locations);
LoopClosureResult result = FindLoopClosure(image, current_frame, frames);
return result;
}
LoopClosureResult LoopClosure::FindLoopClosure(
Eigen::ArrayXXf& image, FramePtr& current_frame, std::vector<FramePtr>& frames){
Eigen::ArrayXXcf current_fft_result, current_fft_polar;
current_frame->GetFFTResult(current_fft_result, current_fft_polar);
LoopClosureResult result;
result.current_frame = current_frame;
for(FramePtr frame : frames){
if(_loop_thr.frame_gap_thr > 0 &&
std::abs((current_frame->GetFrameId() - frame->GetFrameId())) < _loop_thr.frame_gap_thr){
continue;
}
if(_loop_thr.distance_thr > 0){
double d1 = _map->GetFrameDistance(current_frame); // distance is accumulation distance
double d2 = _map->GetFrameDistance(frame);
if(std::abs((d1 - d2)) < _loop_thr.distance_thr){
continue;
}
}
Eigen::ArrayXXcf fft_result, fft_polar;
frame->GetFFTResult(fft_result, fft_polar);
Eigen::Vector3d relative_pose;
Eigen::Vector3d response =
_correlation_flow->ComputePose(fft_result, image, fft_polar, current_fft_polar, relative_pose, false);
if(response.sum() > result.response.sum()){
result.response = response;
result.loop_frame = frame;
result.relative_pose = relative_pose;
}
}
bool c1 = (result.response(0) > _loop_thr.position_response_thr);
bool c2 = (result.response(2) > _loop_thr.angle_response_thr);
result.found = (c1 && c2);
return result;
}

105
src/ground_slam/src/map.cc Normal file
View File

@@ -0,0 +1,105 @@
#include <iostream>
#include <unistd.h>
#include <map>
#include <vector>
#include "map.h"
using namespace std;
Map::Map(): _grid_scale(1.0){
}
Map::Map(MapConfig& map_config): _grid_scale(map_config.grid_scale){
}
void Map::AddFrame(FramePtr& frame){
if(_frames.size() < 1){
_baseframe = frame;
frame->SetFrameId(0);
}
int frame_id = frame->GetFrameId();
_frames[frame_id] = frame;
Eigen::Vector3d pose;
frame->GetPose(pose);
GridLocation grid_location = ComputeGridLocation(pose);
_grid_map[grid_location].insert(frame);
}
void Map::SetFrameDistance(FramePtr& frame, double distance){
_frame_distanses[frame] = distance;
}
void Map::AddEdge(EdgePtr& edge){
int edge_id = edge->_edge_id;
int from = edge->_from;
int to = edge->_to;
_edges[edge_id] = edge;
if(_frames.count(from) > 0){
_frames[from]->AddEdge(edge_id);
}
if(_frames.count(to) > 0){
_frames[to]->AddEdge(edge_id);
}
}
int Map::GetAllFrames(std::vector<FramePtr>& frames){
for(auto kv : _frames){
frames.emplace_back(kv.second);
}
return frames.size();
}
double Map::GetFrameDistance(FramePtr& frame){
if(_frame_distanses.count(frame) > 0){
return _frame_distanses[frame];
}else{
return -1;
}
}
int Map::GetAllEdges(std::vector<EdgePtr>& edges){
for(auto kv : _edges){
edges.emplace_back(kv.second);
}
return edges.size();
}
void Map::UpdatePoses(AlignedMap<int, Eigen::Vector3d> frame_poses){
for(auto kv : frame_poses){
if(_frames.count(kv.first) > 0){
_frames[kv.first]->SetPose(kv.second);
}
}
}
GridLocation Map::ComputeGridLocation(double x, double y){
int grid_x = static_cast<int>((x / _grid_scale));
int grid_y = static_cast<int>((y / _grid_scale));
return GridLocation(grid_x, grid_y);
}
GridLocation Map::ComputeGridLocation(Eigen::Vector3d pose){
double x = pose(0);
double y = pose(1);
return ComputeGridLocation(x, y);
}
int Map::GetFramesInGrids(
std::vector<FramePtr>& frames, std::vector<GridLocation>& grid_locations){
for(auto grid_location : grid_locations){
if(_grid_map.count(grid_location) > 0){
frames.insert(frames.end(), _grid_map[grid_location].begin(), _grid_map[grid_location].end());
}
}
return frames.size();
}
FramePtr Map::GetBaseframe(){
return _baseframe;
}

View File

@@ -0,0 +1,334 @@
#include "map_builder.h"
#include <set>
#include <string>
#include <cmath>
#include <iostream>
#include <Eigen/Dense>
#include <Eigen/SparseCore>
#include "edge.h"
#include "utils.h"
#include "optimization_2d/types.h"
#include "optimization_2d/pose_graph_2d.h"
using namespace std;
MapBuilder::MapBuilder(Configs& configs):_init(false), _frame_id(0), _edge_id(0),
_configs(configs), _kfs_config(configs.keyframe_selection_config){
_camera = std::shared_ptr<Camera>(new Camera(configs.dataset_config.camera_file));
double _image_height = _camera->GetImageHeight();
double _image_width = _camera->GetImageWidth();
_correlation_flow = std::shared_ptr<CorrelationFlow>(new CorrelationFlow(configs.cf_config, _image_height, _image_width));
_map = std::shared_ptr<Map>(new Map(configs.map_config));
_loop_closure = std::shared_ptr<LoopClosure>(
new LoopClosure(configs.loop_closure_config, _correlation_flow, _map));
_map_stitcher = std::shared_ptr<MapStitcher>(new MapStitcher(configs.map_stitcher_config, _camera));
}
bool MapBuilder::AddNewInput(cv::Mat& image, double timestamp){
cv::Mat undistort_image;
_camera->UndistortImage(image, undistort_image);
ComputeFFTResult(undistort_image);
ConstructFrame(timestamp);
if(!_init){
Initialize();
_map_stitcher->InsertFrame(_current_frame, undistort_image);
UpdateIntermedium();
return true;
}
Eigen::Vector3d response;
bool good_tracking = Tracking(response);
if(good_tracking){
UpdateCurrentPose();
SetCurrentFramePose();
Eigen::Vector2d da = ComputeRelativeDA();
bool c1 = da(0) > _kfs_config.max_distance;
bool c2 = da(1) > _kfs_config.max_angle;
bool c3 = ((response(0) > _kfs_config.lower_response_thr) && (response(0) < _kfs_config.upper_response_thr));
bool c4 = ((response(2) > _kfs_config.lower_response_thr) && (response(2) < _kfs_config.upper_response_thr));
bool to_insert = (c1 || c2 || c3 || c4);
if(!to_insert) return false;
_distance += da(0);
}else{
return false;
}
if(good_tracking) AddCFEdge();
_map->AddFrame(_current_frame);
SetFrameDistance();
_map_stitcher->InsertFrame(_current_frame, undistort_image);
bool loop_found = _configs.loop_closure_config.to_find_loop ? FindLoopClosure() : false;
if(!loop_found){
CheckAndOptimize();
}
UpdateIntermedium();
return true;
}
void MapBuilder::ComputeFFTResult(cv::Mat& image){
ConvertMatToNormalizedArray(image, _image_array);
_correlation_flow->ComputeIntermedium(_image_array, _fft_result, _fft_polar);
}
void MapBuilder::ConstructFrame(double timestamp){
_current_frame = std::shared_ptr<Frame>(
new Frame(_frame_id++, timestamp, _image_array, _fft_result, _fft_polar));
}
void MapBuilder::SetCurrentFramePose(){
_current_frame->SetPose(_current_pose);
}
bool MapBuilder::Initialize(){
_current_cf_pose << 0.0, 0.0, 0.0;
_camera->ConvertImagePlanePoseToCamera(_current_cf_pose, _current_cf_real_pose);
_camera->ConvertCameraPoseToRobot(_current_cf_real_pose, _current_pose);
SetCurrentFramePose();
_map->AddFrame(_current_frame);
_distance = 0;
_map->SetFrameDistance(_current_frame, _distance);
_init = true;
_last_lost = false;
return true;
}
void MapBuilder::UpdateIntermedium(){
_last_frame = _current_frame;
_last_cf_pose = _current_cf_pose;
_last_cf_real_pose = _current_cf_real_pose;
_last_pose = _current_pose;
_last_fft_result = _fft_result;
_last_fft_polar = _fft_polar;
}
void MapBuilder::CheckAndOptimize(){
if(_loop_matches.size() >= 2){
AddLoopEdges();
OptimizeMap();
UpdateValueAfterLoop();
_map_stitcher->RecomputeOccupancy();
}
_loop_matches.clear();
}
void MapBuilder::UpdateCurrentPose(){
Eigen::Vector3d last_robot_pose_from_cf, current_robot_pose_from_cf;
_camera->ConvertImagePlanePoseToRobot(_last_cf_pose, last_robot_pose_from_cf);
_camera->ConvertImagePlanePoseToRobot(_current_cf_pose, current_robot_pose_from_cf);
Eigen::Vector3d relativate_pose_from_cf = ComputeRelativePose(last_robot_pose_from_cf, current_robot_pose_from_cf);
Eigen::Vector3d relative_pose = relativate_pose_from_cf;
_current_pose = ComputeAbsolutePose(_last_pose, relative_pose);
}
bool MapBuilder::Tracking(Eigen::Vector3d& response){
Eigen::Vector3d relative_pose;
response = _correlation_flow->ComputePose(
_last_fft_result, _image_array, _last_fft_polar, _fft_polar, relative_pose, true);
relative_pose = _camera->ConvertCenterToPrincipal(relative_pose);
bool good_tracking = ((response(0) > _kfs_config.lower_response_thr) && ((response(2) > _kfs_config.lower_response_thr)));
if(good_tracking){
_current_cf_pose = ComputeAbsolutePose(_last_cf_pose, relative_pose);
_camera->ConvertImagePlanePoseToCamera(_current_cf_pose, _current_cf_real_pose);
}
return good_tracking;
}
void MapBuilder::AddCFEdge(){
Eigen::Vector3d relative_cf_real_pose = ComputeRelativePose(_last_cf_real_pose, _current_cf_real_pose);
Eigen::Matrix3d info = Eigen::Matrix3d::Identity();
AddCFEdgeToMap(relative_cf_real_pose, _last_frame->GetFrameId(), _current_frame->GetFrameId(), _edge_id++, Edge::Type::KCC, info);
}
void MapBuilder::AddCFEdgeToMap(Eigen::Vector3d& relative_pose, int from, int to,
int edge_id, Edge::Type edge_type, Eigen::Matrix3d& info){
EdgePtr cf_edge = std::make_shared<Edge>();
cf_edge->_edge_id = edge_id;
cf_edge->_type = edge_type;
cf_edge->_from = from;
cf_edge->_to = to;
cf_edge->_T = relative_pose;
cf_edge->_information = info;
_map->AddEdge(cf_edge);
}
Eigen::Vector2d MapBuilder::ComputeRelativeDA(){
Eigen::Vector3d rlt_camera_pose;
Eigen::Vector3d rlt_pose = _current_cf_pose - _last_cf_pose;
_camera->ConvertImagePlanePoseToCamera(rlt_pose, rlt_camera_pose);
double d = sqrt(rlt_camera_pose.head(2).dot(rlt_camera_pose.head(2)));
Eigen::Vector2d result;
result << d, std::abs(rlt_camera_pose(2));
return result;
}
void MapBuilder::SetFrameDistance(){
_map->SetFrameDistance(_current_frame, _distance);
}
bool MapBuilder::FindLoopClosure(){
LoopClosureResult loop_closure_result = _loop_closure->FindLoopClosure(_image_array, _current_frame, _current_pose);
if(loop_closure_result.found){
loop_closure_result.relative_pose = _camera->ConvertCenterToPrincipal(loop_closure_result.relative_pose);
_loop_matches.emplace_back(loop_closure_result);
std::cout << "Find a loop edge, current frame = " << loop_closure_result.current_frame->GetFrameId()
<< ", loop frame = " << loop_closure_result.loop_frame->GetFrameId() << std::endl;
}
return loop_closure_result.found;
}
void MapBuilder::AddLoopEdges(){
for(auto loop_match : _loop_matches){ // greater than two matches
int edge_id = _edge_id++;
int from = loop_match.loop_frame->GetFrameId();
int to = loop_match.current_frame->GetFrameId();
Eigen::Vector3d relative_pose;
_camera->ConvertImagePlanePoseToCamera(loop_match.relative_pose, relative_pose);
Eigen::Matrix3d info = Eigen::Matrix3d::Identity();
AddCFEdgeToMap(relative_pose, from, to, edge_id, Edge::Type::Loop, info);
}
}
bool MapBuilder::OptimizeMap(){
std::map<int, ceres::optimization_2d::Pose2d> poses;
std::vector<ceres::optimization_2d::Constraint2d> constraints;
std::vector<FramePtr> frames;
std::set<int> frame_ids;
std::vector<EdgePtr> edges;
_map->GetAllFrames(frames);
_map->GetAllEdges(edges);
for(FramePtr& frame : frames){
int frame_id = frame->GetFrameId();
Eigen::Vector3d pose_vec;
frame->GetPose(pose_vec);
frame_ids.insert(frame_id);
ceres::optimization_2d::Pose2d pose_2d;
pose_2d.x = pose_vec(0);
pose_2d.y = pose_vec(1);
pose_2d.yaw_radians = pose_vec(2);
poses.insert(std::pair<int, ceres::optimization_2d::Pose2d>(frame_id, pose_2d));
}
std::vector<ceres::optimization_2d::ScaleData> scale_data;
ceres::optimization_2d::ScaleData cf_scale;
cf_scale.scale = _camera->GetImageHeight();
if(!_camera->HeightIsAccurate()){
cf_scale.fixed = false;
}else{
cf_scale.fixed = true;
}
scale_data.emplace_back(cf_scale);
std::vector<int> scale_data_idx;
for(EdgePtr& edge : edges){
int from = edge->_from;
int to = edge->_to;
if((frame_ids.count(from) < 1) || (frame_ids.count(to) < 1)){
continue;
}
Eigen::Vector3d relative_pose;
if(edge->_type == Edge::Type::KCC || edge->_type == Edge::Type::Loop){
scale_data_idx.emplace_back(0);
_camera->ConvertCameraPoseToRobot(edge->_T, relative_pose);
}else{
continue;
}
ceres::optimization_2d::Constraint2d constraint;
constraint.id_begin = from;
constraint.id_end = to;
constraint.x = relative_pose(0);
constraint.y = relative_pose(1);
constraint.yaw_radians = relative_pose(2);
constraint.information = edge->_information;
constraints.emplace_back(constraint);
}
ceres::Problem problem;
ceres::optimization_2d::BuildOptimizationProblem(constraints, &poses, &problem);
// ceres::optimization_2d::BuildOptimizationProblemWithScale(constraints, scale_data, scale_data_idx, &poses, &problem);
CHECK(ceres::optimization_2d::SolveOptimizationProblem(&problem))
<< "The solve was not successful, exiting.";
// copy back frame pose
AlignedMap<int, Eigen::Vector3d> frame_poses;
for(auto kv : poses){
Eigen::Vector3d frame_pose;
frame_pose << kv.second.x, kv.second.y, kv.second.yaw_radians;
frame_poses[kv.first] = frame_pose;
}
_map->UpdatePoses(frame_poses);
std::cout << "Map optimization is done !" << std::endl;
return true;
}
void MapBuilder::UpdateValueAfterLoop(){
_current_frame->GetPose(_current_pose);
_camera->ConvertRobotPoseToCamera(_current_cf_real_pose, _current_pose);
_camera->ConvertCameraPoseToImagePlane(_current_cf_pose, _current_cf_real_pose);
}
// for visualization
bool MapBuilder::GetCFPose(Eigen::Vector3d& pose){
Eigen::Vector3d cf_base_pose(0.0, 0.0, 0.0);
Eigen::Vector3d robot_base_pose;
_camera->ConvertImagePlanePoseToRobot(cf_base_pose, robot_base_pose);
Eigen::Vector3d robot_current_pose;
_camera->ConvertImagePlanePoseToRobot(_current_cf_pose, robot_current_pose);
pose = ComputeRelativePose(robot_base_pose, robot_current_pose);
return true;
}
bool MapBuilder::GetFramePoses(Aligned<std::vector, Eigen::Vector3d>& poses, std::vector<double>& timestamps){
poses.clear();
timestamps.clear();
std::vector<FramePtr> frames;
_map->GetAllFrames(frames);
for(auto frame : frames){
Eigen::Vector3d pose;
frame->GetPose(pose);
poses.emplace_back(pose);
timestamps.emplace_back(frame->GetTimestamp());
}
return true;
}
bool MapBuilder::GetOccupancyMapOrigin(
Eigen::Vector3d& pixel_origin, Eigen::Matrix<double, 7, 1>& real_origin){
Eigen::Matrix3d Rbc;
_camera->GetExtrinsics(Rbc);
Eigen::Quaterniond qbc(Rbc);
real_origin(0, 0) = qbc.w();
real_origin(1, 0) = qbc.x();
real_origin(2, 0) = qbc.y();
real_origin(3, 0) = qbc.z();
Eigen::Vector3d robot_origin;
_camera->ConvertImagePlanePoseToRobot(pixel_origin, robot_origin);
real_origin(4, 0) = robot_origin(0);
real_origin(5, 0) = robot_origin(1);
real_origin(6, 0) = robot_origin(2);
return true;
}
double MapBuilder::GetMapResolution(){
return _camera->GetLengthOfPixel();
}
OccupancyData& MapBuilder::GetMapData(){
return _map_stitcher->GetOccupancyData();
}

View File

@@ -0,0 +1,149 @@
#include "map_stitcher.h"
#include "utils.h"
#include <algorithm>
#include <iostream>
using namespace std;
MapStitcher::MapStitcher(MapStitcherConfig config, CameraPtr camera):
_cell_size(config.cell_size), _to_stitch(config.stitch_map), _camera(camera){
}
void MapStitcher::InsertFrame(FramePtr frame, cv::Mat& image){
if(!_to_stitch) return;
const double scale = 100.0 / 255.0;
cv::Mat norm_image = image * scale;
Eigen::MatrixXi matrix;
cv::cv2eigen(norm_image, matrix);
_raw_images[frame] = matrix;
AddImageToOccupancy(frame);
}
Eigen::Vector2i MapStitcher::ComputeCellPosition(int x){
Eigen::Vector2i result;
if(x >=0 ){
result(0) = x / _cell_size;
}else{
result(0) = (x - _cell_size + 1) / _cell_size;
}
result(1) = x - result(0) * _cell_size;
return result;
}
void MapStitcher::AddImageToOccupancy(FramePtr frame){
Eigen::MatrixXi& data = _raw_images[frame];
Eigen::Vector3d robot_pose, image_pose;
frame->GetPose(robot_pose);
_camera->ConvertRobotPoseToImagePlane(image_pose, robot_pose);
image_pose = _camera->ConvertPrincipalToCenter(image_pose);
int W = data.cols();
int H = data.rows();
Eigen::Matrix2d R = ceres::optimization_2d::RotationMatrix2D(image_pose(2));
Eigen::VectorXd W_idx(W);
Eigen::VectorXd H_idx(H);
Eigen::VectorXd X(W);
Eigen::VectorXd Y(W);
double cx = (double)W / 2;
double cy = (double)H / 2;
for(int i = 0; i < W; i++){
W_idx(i) = i - cx;
X(i) = image_pose(0);
Y(i) = image_pose(1);
}
for(int i = 0; i < H; i++) H_idx(i) = i - cy;
Eigen::VectorXd Wx = R(0, 0) * W_idx + X;
Eigen::VectorXd Wy = R(1, 0) * W_idx + Y;
Eigen::VectorXd Hx = R(0, 1) * H_idx;
Eigen::VectorXd Hy = R(1, 1) * H_idx;
// find which cells may be used
int x00 = static_cast<int>((Wx(0) + Hx(0)));
int y00 = static_cast<int>((Wy(0) + Hy(0)));
int x01 = static_cast<int>((Wx(0) + Hx((H-1))));
int y01 = static_cast<int>((Wy(0) + Hy((H-1))));
int x10 = static_cast<int>((Wx((W-1)) + Hx(0)));
int y10 = static_cast<int>((Wy((W-1)) + Hy(0)));
int x11 = static_cast<int>((Wx((W-1)) + Hx((H-1))));
int y11 = static_cast<int>((Wy((W-1)) + Hy((H-1))));
int min_x = std::min(x00, std::min(x01, std::min(x10, x11)));
int max_x = std::max(x00, std::max(x01, std::max(x10, x11)));
int min_y = std::min(y00, std::min(y01, std::min(y10, y11)));
int max_y = std::max(y00, std::max(y01, std::max(y10, y11)));
Eigen::Vector2i min_cell_x = ComputeCellPosition(min_x);
Eigen::Vector2i max_cell_x = ComputeCellPosition(max_x);
Eigen::Vector2i min_cell_y = ComputeCellPosition(min_y);
Eigen::Vector2i max_cell_y = ComputeCellPosition(max_y);
std::unordered_map<GridLocation, bool, GridLocationHash, GridLocationEqual> locations;
OccupancyData tmp_data;
for(int i = min_cell_x(0); i <= max_cell_x(0); i++){
for(int j = min_cell_y(0); j <= max_cell_y(0); j++){
GridLocation grid_location(i, j);
tmp_data[grid_location] = Cell(_cell_size);
locations[grid_location] = false;
}
}
for(int i = 0; i < W; i++){
for(int j = 0; j < H; j ++){
int x = static_cast<int>((Wx(i) + Hx(j)));
int y = static_cast<int>((Wy(i) + Hy(j)));
Eigen::Vector2i cell_x = ComputeCellPosition(x);
Eigen::Vector2i cell_y = ComputeCellPosition(y);
GridLocation grid_location(cell_x(0), cell_y(0));
// cout << data.size() << endl;
// sleep(1000);
tmp_data[grid_location].data(cell_y(1), cell_x(1)) += data(j, i);
tmp_data[grid_location].weight(cell_y(1), cell_x(1)) += 1;
locations[grid_location] = true;
}
}
for(auto& kv : tmp_data){
GridLocation loc = kv.first;
if(!locations[loc]) continue;
if(_occupancy_data.count(loc) > 0){
_occupancy_data[loc].size = _cell_size;
_occupancy_data[loc].data =
_occupancy_data[loc].data * _occupancy_data[loc].weight + tmp_data[loc].data * tmp_data[loc].weight;
_occupancy_data[loc].weight = _occupancy_data[loc].weight + tmp_data[loc].weight;
for(int i = 0; i < _cell_size; i++){
for(int j = 0; j < _cell_size; j++){
if(_occupancy_data[loc].weight(i, j) < 1) continue;
_occupancy_data[loc].data(i, j) = _occupancy_data[loc].data(i, j) / _occupancy_data[loc].weight(i, j);
}
}
}else{
_occupancy_data[loc].size = _cell_size;
_occupancy_data[loc].data = tmp_data[loc].data;
_occupancy_data[loc].weight = tmp_data[loc].weight;
}
}
}
void MapStitcher::RecomputeOccupancy(){
std::cout << "Recompute occupancy map ........" << std::endl;
_occupancy_data.clear();
for(auto kv : _raw_images){
AddImageToOccupancy(kv.first);
Eigen::Vector3d pose;
kv.first->GetPose(pose);
}
std::cout << "Occupancy map has been updated !" << std::endl;
}
OccupancyData& MapStitcher::GetOccupancyData(){
return _occupancy_data;
}

View File

@@ -0,0 +1,221 @@
// 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)
//
// An example of solving a graph-based formulation of Simultaneous Localization
// and Mapping (SLAM). It reads a 2D pose graph problem definition file in the
// g2o format, formulates and solves the Ceres optimization problem, and outputs
// the original and optimized poses to file for plotting.
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include "optimization_2d/pose_graph_2d.h"
namespace ceres {
namespace optimization_2d {
// Constructs the nonlinear least squares optimization problem from the pose
// graph constraints.
void BuildOptimizationProblem(const std::vector<Constraint2d>& constraints,
std::map<int, Pose2d>* poses,
ceres::Problem* problem) {
CHECK(poses != NULL);
CHECK(problem != NULL);
if (constraints.empty()) {
LOG(INFO) << "No constraints, no problem to optimize.";
return;
}
ceres::LossFunction* loss_function = NULL;
ceres::LocalParameterization* angle_local_parameterization =
AngleLocalParameterization::Create();
for (std::vector<Constraint2d>::const_iterator constraints_iter =
constraints.begin();
constraints_iter != constraints.end();
++constraints_iter) {
const Constraint2d& constraint = *constraints_iter;
std::map<int, Pose2d>::iterator pose_begin_iter =
poses->find(constraint.id_begin);
CHECK(pose_begin_iter != poses->end())
<< "Pose with ID: " << constraint.id_begin << " not found.";
std::map<int, Pose2d>::iterator pose_end_iter =
poses->find(constraint.id_end);
CHECK(pose_end_iter != poses->end())
<< "Pose with ID: " << constraint.id_end << " not found.";
const Eigen::Matrix3d sqrt_information =
constraint.information.llt().matrixL();
// Ceres will take ownership of the pointer.
ceres::CostFunction* cost_function = PoseGraph2dErrorTerm::Create(
constraint.x, constraint.y, constraint.yaw_radians, sqrt_information);
problem->AddResidualBlock(cost_function,
loss_function,
&pose_begin_iter->second.x,
&pose_begin_iter->second.y,
&pose_begin_iter->second.yaw_radians,
&pose_end_iter->second.x,
&pose_end_iter->second.y,
&pose_end_iter->second.yaw_radians);
problem->SetParameterization(&pose_begin_iter->second.yaw_radians,
angle_local_parameterization);
problem->SetParameterization(&pose_end_iter->second.yaw_radians,
angle_local_parameterization);
}
// fix base frame
std::map<int, Pose2d>::iterator baseframe_pose_iter = poses->find(0);
CHECK(baseframe_pose_iter != poses->end());
problem->SetParameterBlockConstant(&baseframe_pose_iter->second.x);
problem->SetParameterBlockConstant(&baseframe_pose_iter->second.y);
problem->SetParameterBlockConstant(&baseframe_pose_iter->second.yaw_radians);
}
void BuildOptimizationProblemWithScale(const std::vector<Constraint2d>& constraints,
std::vector<ScaleData>& scale_data,
const std::vector<int>& scale_data_idx,
std::map<int, Pose2d>* poses,
ceres::Problem* problem) {
CHECK(poses != NULL);
CHECK(problem != NULL);
CHECK_EQ(constraints.size(), scale_data_idx.size());
if (constraints.empty()) {
LOG(INFO) << "No constraints, no problem to optimize.";
return;
}
ceres::LossFunction* loss_function = NULL;
ceres::LocalParameterization* angle_local_parameterization =
AngleLocalParameterization::Create();
size_t i = 0;
for (std::vector<Constraint2d>::const_iterator constraints_iter =
constraints.begin();
constraints_iter != constraints.end();
++constraints_iter) {
const Constraint2d& constraint = *constraints_iter;
std::map<int, Pose2d>::iterator pose_begin_iter =
poses->find(constraint.id_begin);
CHECK(pose_begin_iter != poses->end())
<< "Pose with ID: " << constraint.id_begin << " not found.";
std::map<int, Pose2d>::iterator pose_end_iter =
poses->find(constraint.id_end);
CHECK(pose_end_iter != poses->end())
<< "Pose with ID: " << constraint.id_end << " not found.";
int scale_idx = scale_data_idx[i++];
const Eigen::Matrix3d sqrt_information =
constraint.information.llt().matrixL();
// Ceres will take ownership of the pointer.
ceres::CostFunction* cost_function = PoseGraph2dErrorTermWithScale::Create(
constraint.x, constraint.y, constraint.yaw_radians, sqrt_information);
problem->AddResidualBlock(cost_function,
loss_function,
&pose_begin_iter->second.x,
&pose_begin_iter->second.y,
&pose_begin_iter->second.yaw_radians,
&pose_end_iter->second.x,
&pose_end_iter->second.y,
&pose_end_iter->second.yaw_radians,
&(scale_data[scale_idx].scale));
problem->SetParameterization(&pose_begin_iter->second.yaw_radians,
angle_local_parameterization);
problem->SetParameterization(&pose_end_iter->second.yaw_radians,
angle_local_parameterization);
}
// fix some scales
for(size_t j = 0; j < scale_data.size(); j++){
if(scale_data[j].fixed){
problem->SetParameterBlockConstant(&(scale_data[j].scale));
}
}
// fix base frame
std::map<int, Pose2d>::iterator baseframe_pose_iter = poses->find(0);
CHECK(baseframe_pose_iter != poses->end());
problem->SetParameterBlockConstant(&baseframe_pose_iter->second.x);
problem->SetParameterBlockConstant(&baseframe_pose_iter->second.y);
problem->SetParameterBlockConstant(&baseframe_pose_iter->second.yaw_radians);
}
// Returns true if the solve was successful.
bool SolveOptimizationProblem(ceres::Problem* problem) {
CHECK(problem != NULL);
ceres::Solver::Options options;
options.max_num_iterations = 300;
options.linear_solver_type = ceres::SPARSE_NORMAL_CHOLESKY;
ceres::Solver::Summary summary;
ceres::Solve(options, problem, &summary);
std::cout << summary.FullReport() << '\n';
return summary.IsSolutionUsable();
}
// Output the poses to the file with format: ID x y yaw_radians.
bool OutputPoses(const std::string& filename,
const std::map<int, Pose2d>& poses) {
std::fstream outfile;
outfile.open(filename.c_str(), std::istream::out);
if (!outfile) {
std::cerr << "Error opening the file: " << filename << '\n';
return false;
}
for (std::map<int, Pose2d>::const_iterator poses_iter = poses.begin();
poses_iter != poses.end();
++poses_iter) {
const std::map<int, Pose2d>::value_type& pair = *poses_iter;
outfile << pair.first << " " << pair.second.x << " " << pair.second.y << ' '
<< pair.second.yaw_radians << '\n';
}
return true;
}
} // namespace optimization_2d
} // namespace ceres

View File

@@ -0,0 +1,68 @@
#include "thread_publisher.h"
template <typename T>
ThreadPublisher<T>::ThreadPublisher() {
shutdown_requested_ = false;
}
template <typename T>
ThreadPublisher<T>::~ThreadPublisher() {
}
template <typename T>
void ThreadPublisher<T>::Register(
std::function<void(const std::shared_ptr<const T>&)> cb) {
callbacks_.push_back(cb);
}
template <typename T>
void ThreadPublisher<T>::Start() {
publish_thread_ = std::thread(std::bind(&ThreadPublisher::Process, this));
}
template <typename T>
void ThreadPublisher<T>::Publish(const std::shared_ptr<const T> msg) {
std::unique_lock<std::mutex> locker(msg_mutex_);
msgs_.push(msg);
locker.unlock();
msg_cond_.notify_one();
}
template <typename T>
void ThreadPublisher<T>::Process() {
while (!shutdown_requested_) {
std::shared_ptr<const T> msg;
std::unique_lock<std::mutex> locker(msg_mutex_);
while (msgs_.empty()) {
if (shutdown_requested_) {
locker.unlock();
break;
} else {
msg_cond_.wait(locker);
}
}
if (shutdown_requested_) {
break;
} else {
msg = msgs_.back();
while (!msgs_.empty()) {
msgs_.pop();
}
}
locker.unlock();
for (auto callback : callbacks_) {
callback(msg);
}
}
}
template <typename T>
void ThreadPublisher<T>::ShutDown() {
shutdown_requested_ = true;
msg_cond_.notify_one();
if (publish_thread_.joinable()) {
publish_thread_.join();
}
}

35
src/ground_slam/src/timer.cc Executable file
View File

@@ -0,0 +1,35 @@
#include <stdlib.h>
#include "timer.h"
void startTimer(Timer *pTimer){
gettimeofday(&pTimer->start, NULL);
}
void stopTimer(Timer *pTimer){
gettimeofday(&pTimer->stop, NULL);
}
double getElapsedTime(Timer *pTimer){
return ((pTimer->stop.tv_sec - pTimer->start.tv_sec) * 1000.0 + (pTimer->stop.tv_usec - pTimer->start.tv_usec) / 1000.0);
}
void writeTimeToFile(double arrTime[], int nCount, int nFrameNo, char *filename){
FILE *pFile;
int i;
pFile = fopen(filename, "a+");
if(NULL == pFile)
return;
fprintf(pFile, "FrameNo, %d", nFrameNo);
for (i = 0; i < nCount; i++)
{
fprintf(pFile, ",%f", arrTime[i]);
}
fprintf(pFile, "\n");
fclose(pFile);
}

View File

@@ -0,0 +1,183 @@
#include "utils.h"
#include "optimization_2d/pose_graph_2d_error_term.h"
bool FileExists(const std::string& file) {
struct stat file_status;
if (stat(file.c_str(), &file_status) == 0 &&
(file_status.st_mode & S_IFREG)) {
return true;
}
return false;
}
bool PathExists(const std::string& path) {
struct stat file_status;
if (stat(path.c_str(), &file_status) == 0 &&
(file_status.st_mode & S_IFDIR)) {
return true;
}
return false;
}
void ConcatenateFolderAndFileName(
const std::string& folder, const std::string& file_name,
std::string* path) {
*path = folder;
if (path->back() != '/') {
*path += '/';
}
*path = *path + file_name;
}
std::string ConcatenateFolderAndFileName(
const std::string& folder, const std::string& file_name) {
std::string path;
ConcatenateFolderAndFileName(folder, file_name, &path);
return path;
}
void MakeDir(const std::string& path){
if(!PathExists(path)){
mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
}
}
void ReadTxt(const std::string& file_path,
std::vector<std::vector<std::string> >& lines, std::string seq){
if(!FileExists(file_path)){
std::cout << "file: " << file_path << " dosen't exist" << std::endl;
exit(0);
}
std::ifstream infile(file_path, std::ifstream::in);
if(!infile.is_open()){
std::cout << "open file: " << file_path << " failure" << std::endl;
exit(0);
}
std::string line;
while (getline(infile, line)){
std::string whitespaces(" \t\f\v\n\r");
std::size_t found = line.find_last_not_of(whitespaces);
if (found!=std::string::npos){
line.erase(found+1);
std::vector<std::string> line_data;
while (true){
int index = line.find(seq);
std::string sub_str = line.substr(0, index);
if (!sub_str.empty()){
line_data.push_back(sub_str);
}
line.erase(0, index + seq.size());
if (index == -1){
break;
}
}
lines.emplace_back(line_data);
}
else{
line.clear(); // str is all whitespace
}
}
}
void WriteTxt(const std::string file_path,
std::vector<std::vector<std::string> >& lines, std::string seq){
std::fstream file;
file.open(file_path.c_str(), std::ios::out|std::ios::app);
if(!file.good()){
std::cout << "Error: cannot open file " << file_path << std::endl;
exit(0);
}
for(std::vector<std::string>& line : lines){
size_t num_in_line = line.size();
if(num_in_line < 1) continue;
std::string line_txt = line[0];
for(size_t i = 1; i < num_in_line; ++i){
line_txt = line_txt + seq + line[i];
}
line_txt += "\n";
file << line_txt;
}
file.close();
}
void ConvertMatToNormalizedArray(cv::Mat& image, Eigen::ArrayXXf& array){
cv::Mat dst;
// auto clahe = cv::createCLAHE(2, cv::Size(4, 4));
// clahe->apply(image, dst);
dst = image;
Eigen::MatrixXf matrix;
cv::cv2eigen(dst, matrix);
array = matrix.array()/255.0;
}
Eigen::ArrayXXf ConvertMatToArray(const cv::Mat& image){
Eigen::MatrixXf matrix;
cv::cv2eigen(image, matrix);
return matrix.array();
}
cv::Mat ConvertArrayToMat(const Eigen::ArrayXXf& array){
cv::Mat image;
Eigen::MatrixXf matrix(array);
cv::eigen2cv(matrix, image);
return image;
}
// Eigen pose
Eigen::Vector3d ComputeRelativePose(
Eigen::Vector3d& pose1, Eigen::Vector3d& pose2){
Eigen::Vector3d result;
Eigen::Matrix2d Rw1 = ceres::optimization_2d::RotationMatrix2D(pose1(2));
result.head(2) = Rw1.transpose() * (pose2.head(2) - pose1.head(2));
result(2) = pose2(2) - pose1(2);
result(2) = ceres::optimization_2d::NormalizeAngle(result(2));
return result;
}
Eigen::Vector3d ComputeAbsolutePose(
Eigen::Vector3d& pose1, Eigen::Vector3d& relative_pose){
Eigen::Vector3d result;
Eigen::Matrix2d Rw1 = ceres::optimization_2d::RotationMatrix2D(pose1(2));
result.head(2) = pose1.head(2) + Rw1 * relative_pose.head(2);
result(2) = pose1(2) + relative_pose(2);
result(2) = ceres::optimization_2d::NormalizeAngle(result(2));
return result;
}
Eigen::ArrayXXf RotateArray(const Eigen::ArrayXXf& array, float degree)
{
cv::Mat dst, src=ConvertArrayToMat(array);
cv::Point2f pc(src.cols/2., src.rows/2.);
cv::Mat r = cv::getRotationMatrix2D(pc, degree, 1.0);
cv::warpAffine(src, dst, r, src.size(), cv::INTER_LINEAR, cv::BORDER_WRAP);
return ConvertMatToArray(dst);
}
Eigen::ArrayXXf WarpArray(const Eigen::ArrayXXf& array, float tx, float ty, float degree)
{
cv::Mat dst, src=ConvertArrayToMat(array);
float warp_values[] = {1, 0, tx, 0, 1, ty};
cv::Mat warp = cv::Mat(2, 3, CV_32F, warp_values);
cv::warpAffine(src, dst, warp, src.size(), cv::INTER_LINEAR, cv::BORDER_WRAP);
// ShowArray(ConvertMatToArray(dst), "test", 0);
return RotateArray(ConvertMatToArray(dst), degree);
}
double NormalizeDegree(double angle_degree) {
return angle_degree - 360 * floor((angle_degree + 180) / 360);
}
void ShowArray(const Eigen::ArrayXXf& array, std::string window, int waitkey)
{
auto img = ConvertArrayToMat(array);
cv::imshow(window, img);
cv::waitKey(waitkey);
}

View File

@@ -0,0 +1,201 @@
#include "visualization.h"
#include <iostream>
#include <algorithm>
#include <numeric>
#include <time.h>
#include <tf2/LinearMath/Quaternion.h>
#include <tf2_geometry_msgs/tf2_geometry_msgs.hpp>
#include "utils.h"
using namespace std;
Visualizer::Visualizer(rclcpp::Node::SharedPtr node, VisualizationConfig& config)
: node_(node), frame_id_(config.frame_id) {
kcc_pose_pub_ = node_->create_publisher<nav_msgs::msg::Path>(config.kcc_pose_topic, 10);
frame_pose_pub_ = node_->create_publisher<nav_msgs::msg::Path>(config.frame_pose_topic, 10);
map_pub_ = node_->create_publisher<nav_msgs::msg::OccupancyGrid>(config.map_topic, 1);
image_pub_ = node_->create_publisher<sensor_msgs::msg::Image>(config.image_topic, 1);
auto current_time = node_->get_clock()->now();
odom_pose_msgs_.header.stamp = current_time;
odom_pose_msgs_.header.frame_id = frame_id_;
kcc_pose_msgs_.header.stamp = current_time;
kcc_pose_msgs_.header.frame_id = frame_id_;
frame_pose_msgs_.header.stamp = current_time;
frame_pose_msgs_.header.frame_id = frame_id_;
occupancy_map_msgs_.header.stamp = current_time;
occupancy_map_msgs_.header.frame_id = frame_id_;
}
void Visualizer::AddNewPoseToPath(
Eigen::Vector3d& pose, double time_double,
nav_msgs::msg::Path& path, std::string& id) {
auto current_time = node_->get_clock()->now();
geometry_msgs::msg::PoseStamped pose_stamped;
if (time_double < 0) {
pose_stamped.header.stamp = current_time;
} else {
auto sec = static_cast<int64_t>(time_double);
auto nsec = static_cast<uint32_t>((time_double - sec) * 1e9);
pose_stamped.header.stamp = rclcpp::Time(sec, nsec);
}
pose_stamped.header.frame_id = id;
pose_stamped.pose.position.x = pose(0);
pose_stamped.pose.position.y = pose(1);
pose_stamped.pose.position.z = 0;
// tf2 equivalent of tf::createQuaternionMsgFromYaw
tf2::Quaternion q;
q.setRPY(0, 0, pose(2));
pose_stamped.pose.orientation = tf2::toMsg(q);
path.poses.push_back(pose_stamped);
}
void Visualizer::UpdateOdomPose(Eigen::Vector3d& pose, double time_double) {
AddNewPoseToPath(pose, time_double, odom_pose_msgs_, frame_id_);
// odom_pose_pub not used currently
}
void Visualizer::UpdateKccPose(Eigen::Vector3d& pose, double time_double) {
AddNewPoseToPath(pose, time_double, kcc_pose_msgs_, frame_id_);
kcc_pose_pub_->publish(kcc_pose_msgs_);
}
void Visualizer::UpdateFramePose(
Aligned<std::vector, Eigen::Vector3d>& frame_poses,
std::vector<double>& timestamps) {
frame_pose_msgs_.poses.clear();
for (size_t i = 0; i < frame_poses.size(); i++) {
AddNewPoseToPath(frame_poses[i], timestamps[i], frame_pose_msgs_, frame_id_);
}
frame_pose_pub_->publish(frame_pose_msgs_);
}
void Visualizer::ConvertMapToOccupancyMsgs(
OccupancyData& map, nav_msgs::msg::OccupancyGrid& msgs) {
if (map.size() < 1) return;
int max_x = std::numeric_limits<int>::min();
int max_y = std::numeric_limits<int>::min();
int min_x = std::numeric_limits<int>::max();
int min_y = std::numeric_limits<int>::max();
for (auto& kv : map) {
int x = kv.first.x;
int y = kv.first.y;
max_x = std::max(max_x, x);
max_y = std::max(max_y, y);
min_x = std::min(min_x, x);
min_y = std::min(min_y, y);
}
if ((min_x > max_x) || (min_y > max_y)) return;
int size = map.begin()->second.size;
msgs.info.width = (max_x - min_x + 1) * size;
msgs.info.height = (max_y - min_y + 1) * size;
msgs.info.origin.position.x = (min_x * size);
msgs.info.origin.position.y = (min_y * size);
msgs.info.origin.position.z = 0;
int num_grids = msgs.info.width * msgs.info.height;
std::vector<int8_t> data(num_grids, -1);
for (auto& kv : map) {
for (int i = 0; i < kv.second.size; i++) {
for (int j = 0; j < kv.second.size; j++) {
if (kv.second.weight(i, j) < 1) continue;
int x = (kv.first.x - min_x) * kv.second.size + j;
int y = (kv.first.y - min_y) * kv.second.size + i;
int idx = y * msgs.info.width + x;
int pixel = static_cast<int>(kv.second.data(i, j));
data[idx] = 100 - static_cast<int8_t>(pixel);
}
}
}
msgs.data = data;
}
void Visualizer::UpdateMap(MapBuilder& map_builder) {
occupancy_map_msgs_.info.resolution = map_builder.GetMapResolution();
OccupancyData map_data = map_builder.GetMapData();
if (map_data.size() < 1) return;
ConvertMapToOccupancyMsgs(map_data, occupancy_map_msgs_);
Eigen::Matrix<double, 7, 1> real_origin;
Eigen::Vector3d pixel_origin;
pixel_origin << occupancy_map_msgs_.info.origin.position.x,
occupancy_map_msgs_.info.origin.position.y,
occupancy_map_msgs_.info.origin.position.z;
map_builder.GetOccupancyMapOrigin(pixel_origin, real_origin);
occupancy_map_msgs_.info.origin.orientation.w = real_origin(0, 0);
occupancy_map_msgs_.info.origin.orientation.x = real_origin(1, 0);
occupancy_map_msgs_.info.origin.orientation.y = real_origin(2, 0);
occupancy_map_msgs_.info.origin.orientation.z = real_origin(3, 0);
occupancy_map_msgs_.info.origin.position.x = real_origin(4, 0);
occupancy_map_msgs_.info.origin.position.y = real_origin(5, 0);
occupancy_map_msgs_.info.origin.position.z = real_origin(6, 0);
map_pub_->publish(occupancy_map_msgs_);
}
void Visualizer::PublishImage(cv::Mat& image, double time_double) {
auto image_msg = cv_bridge::CvImage(std_msgs::msg::Header(), "mono8", image).toImageMsg();
if (time_double > 0) {
auto sec = static_cast<int64_t>(time_double);
auto nsec = static_cast<uint32_t>((time_double - sec) * 1e9);
image_msg->header.stamp = rclcpp::Time(sec, nsec);
}
image_pub_->publish(*image_msg);
}
void Visualizer::GetTrajectoryTxt(
std::vector<std::vector<std::string>>& lines,
TrajectoryType trajectory_type) {
nav_msgs::msg::Path* path_ptr;
switch (trajectory_type) {
case TrajectoryType::Frame:
path_ptr = &frame_pose_msgs_;
break;
case TrajectoryType::KCC:
path_ptr = &kcc_pose_msgs_;
break;
case TrajectoryType::Odom:
path_ptr = &odom_pose_msgs_;
break;
default:
std::cout << "please select trajectory_type from Frame, KCC and Odom !" << std::endl;
return;
}
for (geometry_msgs::msg::PoseStamped& pose_stamped : (*path_ptr).poses) {
std::vector<std::string> line;
double time_double = static_cast<double>(pose_stamped.header.stamp.sec) +
static_cast<double>(pose_stamped.header.stamp.nanosec) / 1e9;
std::string s_time = std::to_string(time_double);
line.emplace_back(s_time);
line.emplace_back(std::to_string(pose_stamped.pose.position.x));
line.emplace_back(std::to_string(pose_stamped.pose.position.y));
line.emplace_back(std::to_string(pose_stamped.pose.position.z));
line.emplace_back(std::to_string(pose_stamped.pose.orientation.x));
line.emplace_back(std::to_string(pose_stamped.pose.orientation.y));
line.emplace_back(std::to_string(pose_stamped.pose.orientation.z));
line.emplace_back(std::to_string(pose_stamped.pose.orientation.w));
lines.push_back(line);
}
}