参考上海交通大学代码进行修改
This commit is contained in:
38
Catalyst-MDVS2/.gitignore
vendored
Normal file
38
Catalyst-MDVS2/.gitignore
vendored
Normal file
@@ -0,0 +1,38 @@
|
||||
# ---> C++
|
||||
# Prerequisites
|
||||
*.d
|
||||
|
||||
# Compiled Object files
|
||||
*.slo
|
||||
*.lo
|
||||
*.o
|
||||
*.obj
|
||||
|
||||
# Precompiled Headers
|
||||
*.gch
|
||||
*.pch
|
||||
|
||||
# Compiled Dynamic libraries
|
||||
*.so
|
||||
*.dylib
|
||||
*.dll
|
||||
|
||||
# Fortran module files
|
||||
*.mod
|
||||
*.smod
|
||||
|
||||
# Compiled Static libraries
|
||||
*.lai
|
||||
*.la
|
||||
*.a
|
||||
*.lib
|
||||
|
||||
# Executables
|
||||
*.exe
|
||||
*.out
|
||||
*.app
|
||||
|
||||
# BUILD
|
||||
build/
|
||||
.cache/
|
||||
.vscode/
|
||||
2
Catalyst-MDVS2/.gitignore:Zone.Identifier
Normal file
2
Catalyst-MDVS2/.gitignore:Zone.Identifier
Normal file
@@ -0,0 +1,2 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
38
Catalyst-MDVS2/CMakeLists.txt
Normal file
38
Catalyst-MDVS2/CMakeLists.txt
Normal file
@@ -0,0 +1,38 @@
|
||||
cmake_minimum_required(VERSION 3.10)
|
||||
project(armor_detector_mdv)
|
||||
|
||||
# Set C++ standard
|
||||
set(CMAKE_CXX_STANDARD 23)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
|
||||
# Find OpenCV package
|
||||
find_package(OpenCV REQUIRED)
|
||||
|
||||
# Include OpenCV headers
|
||||
include_directories(${OpenCV_INCLUDE_DIRS})
|
||||
include_directories(/usr/include)
|
||||
include_directories(./inc)
|
||||
|
||||
# Add executable for MindVision version
|
||||
add_executable(armor_detector_mdv
|
||||
src/MindVisionMain.cpp
|
||||
src/MindVisionCamera.cpp
|
||||
src/ImagePreprocessor.cpp
|
||||
src/ArmorDetector.cpp
|
||||
src/KalmanFilter.cpp
|
||||
src/Visualizer.cpp
|
||||
src/BallisticPredictor.cpp
|
||||
src/TTLCommunicator.cpp
|
||||
)
|
||||
|
||||
# Link OpenCV libraries
|
||||
target_link_libraries(armor_detector_mdv ${OpenCV_LIBS} -lutil -lpthread)
|
||||
|
||||
# Link MindVision SDK library
|
||||
target_link_libraries(armor_detector_mdv MVSDK)
|
||||
|
||||
# Additional flags for better compilation
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -O3 -pthread")
|
||||
|
||||
# For serial communication on Linux, you might need to link additional libraries:
|
||||
# target_link_libraries(armor_detector_mdv ${OpenCV_LIBS} -lutil -lpthread)
|
||||
2
Catalyst-MDVS2/CMakeLists.txt:Zone.Identifier
Normal file
2
Catalyst-MDVS2/CMakeLists.txt:Zone.Identifier
Normal file
@@ -0,0 +1,2 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
235
Catalyst-MDVS2/LICENSE
Normal file
235
Catalyst-MDVS2/LICENSE
Normal file
@@ -0,0 +1,235 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 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 Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are 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.
|
||||
|
||||
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.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
|
||||
|
||||
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
|
||||
|
||||
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 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 work with which it is combined will remain governed by version 3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of the GNU Affero 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 Affero 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 Affero 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 Affero 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.
|
||||
|
||||
Catalyst-MDVS
|
||||
Copyright (C) 2025 VSAG
|
||||
|
||||
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero 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 your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
|
||||
|
||||
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 AGPL, see <http://www.gnu.org/licenses/>.
|
||||
2
Catalyst-MDVS2/LICENSE:Zone.Identifier
Normal file
2
Catalyst-MDVS2/LICENSE:Zone.Identifier
Normal file
@@ -0,0 +1,2 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
81
Catalyst-MDVS2/README.md
Normal file
81
Catalyst-MDVS2/README.md
Normal file
@@ -0,0 +1,81 @@
|
||||
# MindVision相机驱动的装甲板检测系统
|
||||
|
||||
本项目是基于MindVision相机SDK的装甲板检测系统,工业相机替代原有的OpenCV相机接口。
|
||||
|
||||
## 项目结构
|
||||
|
||||
- `MindVisionCamera.h/cpp` - MindVision相机驱动实现
|
||||
- `main.cpp` - 主程序入口(已修改为使用MindVision相机)
|
||||
- 其他 `.cpp/.h` 文件 - 原有的图像处理、装甲板检测、卡尔曼滤波等功能模块
|
||||
|
||||
## 环境准备
|
||||
|
||||
此项目需要在WSL Ubuntu环境中编译和运行,因为MindVision SDK位于WSL系统中。
|
||||
|
||||
### 1. 确保MindVision SDK已安装
|
||||
|
||||
在WSL Ubuntu中确认SDK路径:
|
||||
```bash
|
||||
ls -la /home/lld/mdv/include/CameraApi.h
|
||||
ls -la /home/lld/mdv/lib/x86/
|
||||
```
|
||||
|
||||
### 2. 安装必要的依赖
|
||||
|
||||
```bash
|
||||
sudo apt update
|
||||
sudo apt install build-essential cmake libopencv-dev
|
||||
```
|
||||
|
||||
## 编译项目
|
||||
|
||||
### 方法1:使用构建脚本
|
||||
```bash
|
||||
cd /home/lld/code/mdvs
|
||||
chmod +x build.sh
|
||||
./build.sh
|
||||
```
|
||||
|
||||
### 方法2:手动编译
|
||||
```bash
|
||||
cd /home/lld/code/mdvs
|
||||
mkdir build
|
||||
cd build
|
||||
cmake .. -DCMAKE_BUILD_TYPE=Release
|
||||
make -j$(nproc)
|
||||
```
|
||||
|
||||
## 运行程序
|
||||
|
||||
```bash
|
||||
./build/armor_detector_mdv
|
||||
```
|
||||
|
||||
## 配置说明
|
||||
|
||||
- 相机ID可在main函数中修改 `cam_id` 变量
|
||||
- 默认分辨率:640x480,帧率:30fps
|
||||
- 支持颜色切换(红色/蓝色)
|
||||
- 支持TTL通信(默认关闭)
|
||||
|
||||
## 注意事项
|
||||
|
||||
1. 此项目使用MindVision相机SDK直接驱动相机,可以获得更好的性能和相机控制能力
|
||||
2. 曝光、白平衡等参数可在`MindVisionCamera.cpp`中的`set_camera_parameters()`函数中调整
|
||||
3. 如果遇到编译错误,请检查MindVision SDK的库文件名是否正确(可能是`libMVSDK.so`或`libMVSDK.a`)
|
||||
|
||||
## 键盘控制
|
||||
|
||||
- 按 'q' 键退出程序
|
||||
- 按其他键继续运行
|
||||
|
||||
## 故障排除
|
||||
|
||||
如果相机无法打开:
|
||||
1. 检查相机是否正确连接
|
||||
2. 确认MindVision相机驱动是否正确安装
|
||||
3. 验证相机ID是否正确
|
||||
4. 检查权限(可能需要将用户添加到video组)
|
||||
|
||||
## MindVision-SDK
|
||||
`Linux`: >**wget https://www.mindvision.com.cn/wp-content/uploads/2023/08/linuxSDK_V2.1.0.37.tar.gz**
|
||||
2
Catalyst-MDVS2/README.md:Zone.Identifier
Normal file
2
Catalyst-MDVS2/README.md:Zone.Identifier
Normal file
@@ -0,0 +1,2 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
65
Catalyst-MDVS2/inc/ArmorDetector.h
Normal file
65
Catalyst-MDVS2/inc/ArmorDetector.h
Normal file
@@ -0,0 +1,65 @@
|
||||
#ifndef ARMORDETECTOR_H
|
||||
#define ARMORDETECTOR_H
|
||||
|
||||
#include <opencv2/opencv.hpp>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include "config.h"
|
||||
|
||||
struct LightBar {
|
||||
cv::Point2f center;
|
||||
cv::Size2f size;
|
||||
float angle; // in degrees
|
||||
float angle_rad; // in radians
|
||||
float area;
|
||||
std::vector<cv::Point2f> center_line; // [end1, end2]
|
||||
float center_line_length;
|
||||
std::vector<cv::Point2f> box;
|
||||
};
|
||||
|
||||
struct ArmorPlate {
|
||||
std::string color;
|
||||
cv::Point2f center;
|
||||
double confidence;
|
||||
std::pair<LightBar, LightBar> pair;
|
||||
std::vector<cv::Point2f> corners_2d; // Can be computed later for 3D pose
|
||||
|
||||
// Function to get bounding rectangle of the armor plate
|
||||
cv::Rect2d getBoundingRect() const {
|
||||
if (corners_2d.size() >= 4) {
|
||||
cv::Point2f min_pt = corners_2d[0];
|
||||
cv::Point2f max_pt = corners_2d[0];
|
||||
for (const auto& pt : corners_2d) {
|
||||
min_pt.x = std::min(min_pt.x, pt.x);
|
||||
min_pt.y = std::min(min_pt.y, pt.y);
|
||||
max_pt.x = std::max(max_pt.x, pt.x);
|
||||
max_pt.y = std::max(max_pt.y, pt.y);
|
||||
}
|
||||
return cv::Rect2d(min_pt.x, min_pt.y, max_pt.x - min_pt.x, max_pt.y - min_pt.y);
|
||||
}
|
||||
// Fallback: use center and a fixed size
|
||||
return cv::Rect2d(center.x - 30, center.y - 15, 60, 30);
|
||||
}
|
||||
};
|
||||
|
||||
class ArmorDetector {
|
||||
public:
|
||||
ArmorDetector();
|
||||
|
||||
// Main detection function
|
||||
void detect(const cv::Mat& mask, const std::string& target_color,
|
||||
std::vector<LightBar>& valid_light_bars,
|
||||
std::vector<ArmorPlate>& armor_plates);
|
||||
|
||||
private:
|
||||
float angle_threshold_rad;
|
||||
|
||||
// Helper methods
|
||||
std::vector<LightBar> extract_initial_light_bars(const cv::Mat& mask);
|
||||
std::vector<std::vector<cv::Point2f>> merge_nearby_light_bars(const std::vector<LightBar>& initial_light_bars);
|
||||
std::vector<LightBar> filter_valid_light_bars(const std::vector<std::vector<cv::Point2f>>& processed_boxes);
|
||||
std::vector<ArmorPlate> pair_light_bars_to_armor(const std::vector<LightBar>& light_bars, const std::string& target_color);
|
||||
double calculate_iou(const cv::Rect& b1, const cv::Rect& b2);
|
||||
};
|
||||
|
||||
#endif // ARMORDETECTOR_H
|
||||
29
Catalyst-MDVS2/inc/BallisticPredictor.h
Normal file
29
Catalyst-MDVS2/inc/BallisticPredictor.h
Normal file
@@ -0,0 +1,29 @@
|
||||
#ifndef BALLISTICPREDICTOR_H
|
||||
#define BALLISTICPREDICTOR_H
|
||||
|
||||
#include <opencv2/opencv.hpp>
|
||||
|
||||
class BallisticPredictor {
|
||||
public:
|
||||
BallisticPredictor(float bullet_speed = 16.0f);
|
||||
~BallisticPredictor(); // Added destructor to properly manage memory
|
||||
|
||||
// Predict ballistic point considering target movement and flight time
|
||||
cv::Point2f* predict_ballistic_point(const cv::Point2f* predicted_center,
|
||||
const cv::Point2f& img_center,
|
||||
const cv::Point2f& target_speed);
|
||||
|
||||
// Get last ballistic point
|
||||
const cv::Point2f* get_last_ballistic_point() const { return last_ballistic_point; }
|
||||
|
||||
private:
|
||||
float bullet_speed; // Bullet speed (m/s)
|
||||
float armor_half_width; // Armor half width (converted to meters)
|
||||
float armor_half_height; // Armor half height (converted to meters)
|
||||
cv::Point2f* last_ballistic_point; // Last ballistic prediction
|
||||
|
||||
// Calculate distance to target
|
||||
float calculate_distance(const cv::Point2f& armor_center, const cv::Point2f& img_center, float focal_length = 800.0f);
|
||||
};
|
||||
|
||||
#endif // BALLISTICPREDICTOR_H
|
||||
2
Catalyst-MDVS2/inc/BallisticPredictor.h:Zone.Identifier
Normal file
2
Catalyst-MDVS2/inc/BallisticPredictor.h:Zone.Identifier
Normal file
@@ -0,0 +1,2 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
25
Catalyst-MDVS2/inc/Camera.h
Normal file
25
Catalyst-MDVS2/inc/Camera.h
Normal file
@@ -0,0 +1,25 @@
|
||||
#ifndef CAMERA_H
|
||||
#define CAMERA_H
|
||||
|
||||
#include <opencv2/opencv.hpp>
|
||||
#include <string>
|
||||
|
||||
class Camera {
|
||||
public:
|
||||
cv::VideoCapture cap;
|
||||
bool is_opened;
|
||||
std::string target_color;
|
||||
|
||||
Camera(int cam_id = 0, const std::string& target_color = "red");
|
||||
~Camera();
|
||||
|
||||
void set_cam_params();
|
||||
bool read_frame(cv::Mat& frame);
|
||||
void release();
|
||||
bool switch_color(const std::string& target_color);
|
||||
|
||||
private:
|
||||
void set_camera_parameters();
|
||||
};
|
||||
|
||||
#endif // CAMERA_H
|
||||
2
Catalyst-MDVS2/inc/Camera.h:Zone.Identifier
Normal file
2
Catalyst-MDVS2/inc/Camera.h:Zone.Identifier
Normal file
@@ -0,0 +1,2 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
19
Catalyst-MDVS2/inc/ImagePreprocessor.h
Normal file
19
Catalyst-MDVS2/inc/ImagePreprocessor.h
Normal file
@@ -0,0 +1,19 @@
|
||||
#ifndef IMAGEPREPROCESSOR_H
|
||||
#define IMAGEPREPROCESSOR_H
|
||||
|
||||
#include <opencv2/opencv.hpp>
|
||||
#include <string>
|
||||
|
||||
class ImagePreprocessor {
|
||||
public:
|
||||
ImagePreprocessor();
|
||||
~ImagePreprocessor();
|
||||
|
||||
// Apply morphological operations to a mask
|
||||
void apply_morphology(const cv::Mat& input_mask, cv::Mat& output_mask);
|
||||
|
||||
// Apply Gaussian blur to reduce noise
|
||||
void apply_gaussian_blur(const cv::Mat& input, cv::Mat& output, int kernel_size = 6);
|
||||
};
|
||||
|
||||
#endif // IMAGEPREPROCESSOR_H
|
||||
2
Catalyst-MDVS2/inc/ImagePreprocessor.h:Zone.Identifier
Normal file
2
Catalyst-MDVS2/inc/ImagePreprocessor.h:Zone.Identifier
Normal file
@@ -0,0 +1,2 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
38
Catalyst-MDVS2/inc/KalmanFilter.h
Normal file
38
Catalyst-MDVS2/inc/KalmanFilter.h
Normal file
@@ -0,0 +1,38 @@
|
||||
#ifndef KALMANFILTER_H
|
||||
#define KALMANFILTER_H
|
||||
|
||||
#include <opencv2/opencv.hpp>
|
||||
|
||||
class KalmanFilter {
|
||||
public:
|
||||
KalmanFilter();
|
||||
|
||||
void update(const cv::Point2f& measurement);
|
||||
cv::Point2f predict();
|
||||
|
||||
// Method to update the process noise based on target movement characteristics
|
||||
void updateProcessNoise(const cv::Point2f& current_measurement);
|
||||
|
||||
cv::Point2f get_last_measurement() const { return last_measurement; }
|
||||
cv::Point2f get_last_prediction() const { return last_prediction; }
|
||||
cv::Point2f get_current_velocity() const; // New method to get current velocity
|
||||
bool is_initialized() const { return initialized; }
|
||||
|
||||
private:
|
||||
cv::KalmanFilter kf;
|
||||
bool initialized;
|
||||
cv::Point2f last_measurement;
|
||||
cv::Point2f last_prediction;
|
||||
cv::Point2f prev_measurement;
|
||||
bool has_prev_measurement;
|
||||
|
||||
// Store previous states for velocity and acceleration estimation
|
||||
cv::Point2f prev_velocity;
|
||||
double time_elapsed; // Time in seconds between measurements
|
||||
bool has_prev_velocity;
|
||||
|
||||
void init_params();
|
||||
cv::Point2f estimate_velocity(const cv::Point2f& current, const cv::Point2f& previous);
|
||||
};
|
||||
|
||||
#endif // KALMANFILTER_H
|
||||
2
Catalyst-MDVS2/inc/KalmanFilter.h:Zone.Identifier
Normal file
2
Catalyst-MDVS2/inc/KalmanFilter.h:Zone.Identifier
Normal file
@@ -0,0 +1,2 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
43
Catalyst-MDVS2/inc/MindVisionCamera.h
Normal file
43
Catalyst-MDVS2/inc/MindVisionCamera.h
Normal file
@@ -0,0 +1,43 @@
|
||||
#ifndef MINDVISION_CAMERA_H
|
||||
#define MINDVISION_CAMERA_H
|
||||
|
||||
#include <opencv2/opencv.hpp>
|
||||
#include <string>
|
||||
#include <memory>
|
||||
|
||||
// MindVision SDK 头文件 - 可能需要根据实际SDK文件调整
|
||||
extern "C" {
|
||||
#include "CameraApi.h" // 这是MindVision SDK的典型头文件
|
||||
}
|
||||
|
||||
class MindVisionCamera {
|
||||
public:
|
||||
CameraHandle camera_handle; // MindVision SDk中的相机句柄
|
||||
bool is_opened;
|
||||
std::string target_color;
|
||||
int width;
|
||||
int height;
|
||||
int fps;
|
||||
unsigned char* g_pRgbBuffer; // 处理后数据缓存区
|
||||
tSdkCameraCapbility capability; // 相机能力信息
|
||||
tSdkImageResolution image_resolution; // 分辨率信息
|
||||
|
||||
MindVisionCamera(int cam_id = 0, const std::string& target_color = "red");
|
||||
~MindVisionCamera();
|
||||
|
||||
bool set_cam_params();
|
||||
bool read_frame(cv::Mat& frame);
|
||||
bool read_frame_with_color_filter(cv::Mat& frame, cv::Mat& mask, const std::string& target_color);
|
||||
void release();
|
||||
bool switch_color(const std::string& target_color);
|
||||
|
||||
int get_width() const { return width; }
|
||||
int get_height() const { return height; }
|
||||
bool set_resolution(int width, int height);
|
||||
|
||||
private:
|
||||
void set_camera_parameters();
|
||||
bool initialize_camera(int cam_id);
|
||||
};
|
||||
|
||||
#endif // MINDVISION_CAMERA_H
|
||||
2
Catalyst-MDVS2/inc/MindVisionCamera.h:Zone.Identifier
Normal file
2
Catalyst-MDVS2/inc/MindVisionCamera.h:Zone.Identifier
Normal file
@@ -0,0 +1,2 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
27
Catalyst-MDVS2/inc/TTLCommunicator.h
Normal file
27
Catalyst-MDVS2/inc/TTLCommunicator.h
Normal file
@@ -0,0 +1,27 @@
|
||||
#ifndef TTLCOMMUNICATOR_H
|
||||
#define TTLCOMMUNICATOR_H
|
||||
|
||||
#include <string>
|
||||
|
||||
class TTLCommunicator {
|
||||
public:
|
||||
TTLCommunicator(const std::string& port_name = "/dev/ttyUSB0", int baudrate = 115200);
|
||||
~TTLCommunicator();
|
||||
|
||||
bool connect();
|
||||
void close();
|
||||
bool send_data(const std::string& data);
|
||||
bool is_connected() const { return connected; }
|
||||
|
||||
private:
|
||||
std::string port_name;
|
||||
int baudrate;
|
||||
bool connected;
|
||||
|
||||
int serial_fd;
|
||||
|
||||
bool open_serial_port();
|
||||
void close_serial_port();
|
||||
};
|
||||
|
||||
#endif // TTLCOMMUNICATOR_H
|
||||
2
Catalyst-MDVS2/inc/TTLCommunicator.h:Zone.Identifier
Normal file
2
Catalyst-MDVS2/inc/TTLCommunicator.h:Zone.Identifier
Normal file
@@ -0,0 +1,2 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
30
Catalyst-MDVS2/inc/Visualizer.h
Normal file
30
Catalyst-MDVS2/inc/Visualizer.h
Normal file
@@ -0,0 +1,30 @@
|
||||
#ifndef VISUALIZER_H
|
||||
#define VISUALIZER_H
|
||||
|
||||
#include <opencv2/opencv.hpp>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include "ArmorDetector.h"
|
||||
|
||||
class Visualizer {
|
||||
public:
|
||||
Visualizer();
|
||||
~Visualizer();
|
||||
|
||||
// Draw light bars on frame
|
||||
cv::Mat& draw_light_bars(cv::Mat& frame, const std::vector<LightBar>& light_bars, const std::string& target_color);
|
||||
|
||||
// Draw armor plate on frame
|
||||
cv::Mat& draw_armor_plate(cv::Mat& frame, const ArmorPlate& armor_plate);
|
||||
|
||||
// Draw offset text
|
||||
cv::Mat& draw_offset_text(cv::Mat& frame, const cv::Point2f* display_center, const std::string& target_color, bool is_predicted = false);
|
||||
|
||||
// Draw crosshair at center
|
||||
cv::Mat& draw_crosshair(cv::Mat& frame, const cv::Point2f& center, const cv::Scalar& color = cv::Scalar(0, 255, 0), int size = 10);
|
||||
|
||||
// Draw ballistic point
|
||||
cv::Mat& draw_ballistic_point(cv::Mat& frame, const cv::Point2f* ballistic_point);
|
||||
};
|
||||
|
||||
#endif // VISUALIZER_H
|
||||
2
Catalyst-MDVS2/inc/Visualizer.h:Zone.Identifier
Normal file
2
Catalyst-MDVS2/inc/Visualizer.h:Zone.Identifier
Normal file
@@ -0,0 +1,2 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
45
Catalyst-MDVS2/inc/config.h
Normal file
45
Catalyst-MDVS2/inc/config.h
Normal file
@@ -0,0 +1,45 @@
|
||||
#ifndef CONFIG_H
|
||||
#define CONFIG_H
|
||||
|
||||
#include <opencv2/opencv.hpp>
|
||||
|
||||
// Camera intrinsic parameters (need actual calibration)
|
||||
const cv::Mat CAMERA_MATRIX = (cv::Mat_<float>(3, 3) <<
|
||||
600, 0, 320,
|
||||
0, 600, 240,
|
||||
0, 0, 1);
|
||||
|
||||
const cv::Mat DIST_COEFFS = cv::Mat::zeros(5, 1, CV_32F); // Distortion coefficients (set to 0 for no distortion)
|
||||
|
||||
// Armor dimensions (in mm)
|
||||
const float ARMOR_WIDTH = 135.0f;
|
||||
const float ARMOR_HEIGHT = 125.0f;
|
||||
const float ARMOR_THICKNESS = 20.0f;
|
||||
|
||||
const cv::Mat ARMOR_3D_POINTS = (cv::Mat_<float>(4, 3) <<
|
||||
-ARMOR_WIDTH / 2, -ARMOR_HEIGHT / 2, 0,
|
||||
ARMOR_WIDTH / 2, -ARMOR_HEIGHT / 2, 0,
|
||||
ARMOR_WIDTH / 2, ARMOR_HEIGHT / 2, 0,
|
||||
-ARMOR_WIDTH / 2, ARMOR_HEIGHT / 2, 0);
|
||||
|
||||
// Detection thresholds
|
||||
const float HORIZONTAL_ANGLE_THRESHOLD = 25.0f; // Light bar horizontal angle threshold (degrees)
|
||||
const float HORIZONTAL_ANGLE_THRESHOLD_RAD = HORIZONTAL_ANGLE_THRESHOLD * CV_PI / 180.0f;
|
||||
const float NEARBY_LIGHT_BAR_THRESHOLD = 500.0f; // Light bar merging distance threshold (pixels)
|
||||
const float LIGHT_BAR_IOU_THRESHOLD = 0.05f; // Light bar merging IOU threshold
|
||||
const float ARMOR_DISTANCE_RATIO_MIN = 0.6f; // Armor light bar distance ratio range
|
||||
const float ARMOR_DISTANCE_RATIO_MAX = 4.0f;
|
||||
const float ARMOR_LENGTH_DIFF_RATIO = 0.5f; // Armor light bar length difference ratio
|
||||
const float ARMOR_ANGLE_DIFF_THRESHOLD = 15.0f * CV_PI / 180.0f; // Armor light bar angle difference threshold (radians)
|
||||
|
||||
// Kalman filter parameters
|
||||
const float KF_PROCESS_NOISE = 0.02f; // Process noise covariance
|
||||
const float KF_MEASUREMENT_NOISE = 0.5f; // Measurement noise covariance
|
||||
|
||||
// Focal length in pixels (from camera calibration)
|
||||
const double FOCAL_PIXAL = 600.0; // This should match your actual camera calibration
|
||||
|
||||
// TTL communication settings
|
||||
const int TTL_BAUDRATE = 115200;
|
||||
|
||||
#endif // CONFIG_H
|
||||
275
Catalyst-MDVS2/src/ArmorDetector.cpp
Normal file
275
Catalyst-MDVS2/src/ArmorDetector.cpp
Normal file
@@ -0,0 +1,275 @@
|
||||
#include "ArmorDetector.h"
|
||||
#include <iostream>
|
||||
#include <cmath>
|
||||
#include <algorithm>
|
||||
|
||||
ArmorDetector::ArmorDetector() {
|
||||
angle_threshold_rad = HORIZONTAL_ANGLE_THRESHOLD_RAD;
|
||||
}
|
||||
|
||||
void ArmorDetector::detect(const cv::Mat& mask, const std::string& target_color,
|
||||
std::vector<LightBar>& valid_light_bars,
|
||||
std::vector<ArmorPlate>& armor_plates) {
|
||||
std::vector<LightBar> initial_light_bars = extract_initial_light_bars(mask);
|
||||
if (initial_light_bars.empty()) {
|
||||
valid_light_bars.clear();
|
||||
armor_plates.clear();
|
||||
return;
|
||||
}
|
||||
|
||||
std::vector<std::vector<cv::Point2f>> processed_boxes = merge_nearby_light_bars(initial_light_bars);
|
||||
if (processed_boxes.empty()) {
|
||||
valid_light_bars.clear();
|
||||
armor_plates.clear();
|
||||
return;
|
||||
}
|
||||
|
||||
valid_light_bars = filter_valid_light_bars(processed_boxes);
|
||||
if (valid_light_bars.size() < 2) {
|
||||
armor_plates.clear();
|
||||
return;
|
||||
}
|
||||
|
||||
armor_plates = pair_light_bars_to_armor(valid_light_bars, target_color);
|
||||
if (armor_plates.empty()) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<LightBar> ArmorDetector::extract_initial_light_bars(const cv::Mat& mask) {
|
||||
std::vector<std::vector<cv::Point>> contours;
|
||||
std::vector<cv::Vec4i> hierarchy;
|
||||
cv::findContours(mask, contours, hierarchy, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
|
||||
|
||||
std::vector<LightBar> initial_light_bars;
|
||||
|
||||
for (size_t i = 0; i < contours.size(); i++) {
|
||||
if (contours[i].size() < 5) continue; // Need at least 5 points to fit ellipse
|
||||
|
||||
cv::RotatedRect rect = cv::minAreaRect(contours[i]);
|
||||
cv::Point2f vertices[4];
|
||||
rect.points(vertices);
|
||||
|
||||
std::vector<cv::Point2f> box;
|
||||
for (int j = 0; j < 4; j++) {
|
||||
box.push_back(vertices[j]);
|
||||
}
|
||||
|
||||
float contour_area = cv::contourArea(contours[i]);
|
||||
float rect_area = rect.size.width * rect.size.height;
|
||||
|
||||
// Filter: sufficient area + high fill ratio
|
||||
if (rect_area > 30 && rect_area > 0 && (contour_area / rect_area) > 0.4) {
|
||||
LightBar light_bar;
|
||||
light_bar.center = rect.center;
|
||||
light_bar.size = rect.size;
|
||||
light_bar.angle = rect.angle;
|
||||
light_bar.area = rect_area;
|
||||
light_bar.box = box;
|
||||
|
||||
initial_light_bars.push_back(light_bar);
|
||||
}
|
||||
}
|
||||
|
||||
return initial_light_bars;
|
||||
}
|
||||
|
||||
std::vector<std::vector<cv::Point2f>> ArmorDetector::merge_nearby_light_bars(const std::vector<LightBar>& initial_light_bars) {
|
||||
std::vector<std::vector<cv::Point2f>> processed_boxes;
|
||||
std::vector<bool> visited(initial_light_bars.size(), false);
|
||||
|
||||
for (size_t i = 0; i < initial_light_bars.size(); i++) {
|
||||
if (visited[i]) continue;
|
||||
|
||||
std::vector<int> nearby_indices = {static_cast<int>(i)};
|
||||
cv::Point2f center1 = initial_light_bars[i].center;
|
||||
|
||||
for (size_t j = i + 1; j < initial_light_bars.size(); j++) {
|
||||
if (visited[j]) continue;
|
||||
|
||||
cv::Point2f center2 = initial_light_bars[j].center;
|
||||
float distance = std::sqrt(std::pow(center2.x - center1.x, 2) + std::pow(center2.y - center1.y, 2));
|
||||
|
||||
// Distance + IOU filtering
|
||||
if (distance < NEARBY_LIGHT_BAR_THRESHOLD) {
|
||||
cv::Rect b1 = cv::boundingRect(initial_light_bars[i].box);
|
||||
cv::Rect b2 = cv::boundingRect(initial_light_bars[j].box);
|
||||
|
||||
double iou = calculate_iou(b1, b2);
|
||||
if (iou > LIGHT_BAR_IOU_THRESHOLD) {
|
||||
nearby_indices.push_back(static_cast<int>(j));
|
||||
visited[j] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Merge nearby light bar vertices to generate new rectangle
|
||||
std::vector<cv::Point2f> all_points;
|
||||
for (int k : nearby_indices) {
|
||||
for (const auto& point : initial_light_bars[k].box) {
|
||||
all_points.push_back(point);
|
||||
}
|
||||
}
|
||||
|
||||
if (!all_points.empty()) {
|
||||
cv::RotatedRect merged_rect = cv::minAreaRect(all_points);
|
||||
cv::Point2f vertices[4];
|
||||
merged_rect.points(vertices);
|
||||
|
||||
std::vector<cv::Point2f> merged_box;
|
||||
for (int k = 0; k < 4; k++) {
|
||||
merged_box.push_back(vertices[k]);
|
||||
}
|
||||
|
||||
processed_boxes.push_back(merged_box);
|
||||
visited[i] = true;
|
||||
}
|
||||
}
|
||||
|
||||
return processed_boxes;
|
||||
}
|
||||
|
||||
std::vector<LightBar> ArmorDetector::filter_valid_light_bars(const std::vector<std::vector<cv::Point2f>>& processed_boxes) {
|
||||
std::vector<LightBar> valid_light_bars;
|
||||
|
||||
for (const auto& box : processed_boxes) {
|
||||
if (box.size() < 4) continue;
|
||||
|
||||
cv::RotatedRect rect = cv::minAreaRect(box);
|
||||
cv::Point2f center = rect.center;
|
||||
float width = rect.size.width;
|
||||
float height = rect.size.height;
|
||||
|
||||
float length = width > height ? width : height;
|
||||
float bar_width = width > height ? height : width;
|
||||
|
||||
float main_angle = rect.angle;
|
||||
if (width > height) {
|
||||
// 保持原始角度不变
|
||||
} else {
|
||||
main_angle += 90;
|
||||
}
|
||||
|
||||
// Normalize angle to [-90, 90]
|
||||
main_angle = std::fmod(main_angle, 180);
|
||||
if (main_angle > 90) main_angle -= 180;
|
||||
if (main_angle < -90) main_angle += 180;
|
||||
|
||||
float main_angle_rad = main_angle * CV_PI / 180.0f;
|
||||
|
||||
cv::Point2f end1(
|
||||
center.x + (length / 2) * std::cos(main_angle_rad),
|
||||
center.y + (length / 2) * std::sin(main_angle_rad)
|
||||
);
|
||||
cv::Point2f end2(
|
||||
center.x - (length / 2) * std::cos(main_angle_rad),
|
||||
center.y - (length / 2) * std::sin(main_angle_rad)
|
||||
);
|
||||
|
||||
float rect_area = length * bar_width;
|
||||
float contour_area = cv::contourArea(box);
|
||||
float area_ratio = rect_area > 0 ? contour_area / rect_area : 0;
|
||||
|
||||
// Filter: sufficient area + high fill ratio + non-horizontal
|
||||
if (rect_area > 40 && area_ratio > 0.4 && std::abs(main_angle_rad) > angle_threshold_rad) {
|
||||
LightBar light_bar;
|
||||
light_bar.center = center;
|
||||
light_bar.size = cv::Size2f(length, bar_width);
|
||||
light_bar.angle = main_angle;
|
||||
light_bar.angle_rad = main_angle_rad;
|
||||
light_bar.area = rect_area;
|
||||
light_bar.center_line = {end1, end2};
|
||||
light_bar.center_line_length = length;
|
||||
light_bar.box = box;
|
||||
|
||||
valid_light_bars.push_back(light_bar);
|
||||
}
|
||||
}
|
||||
|
||||
return valid_light_bars;
|
||||
}
|
||||
|
||||
std::vector<ArmorPlate> ArmorDetector::pair_light_bars_to_armor(const std::vector<LightBar>& light_bars, const std::string& target_color) {
|
||||
std::vector<ArmorPlate> armor_plates;
|
||||
std::vector<bool> used(light_bars.size(), false);
|
||||
|
||||
for (size_t i = 0; i < light_bars.size(); i++) {
|
||||
if (used[i]) continue;
|
||||
const LightBar& lb1 = light_bars[i];
|
||||
|
||||
for (size_t j = i + 1; j < light_bars.size(); j++) {
|
||||
if (used[j]) continue;
|
||||
const LightBar& lb2 = light_bars[j];
|
||||
|
||||
// Angle difference filtering
|
||||
float angle_diff = std::abs(lb1.angle_rad - lb2.angle_rad);
|
||||
float angle_diff_2 = 2.0f * CV_PI - angle_diff;
|
||||
angle_diff = std::min(angle_diff, angle_diff_2);
|
||||
if (angle_diff > ARMOR_ANGLE_DIFF_THRESHOLD) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Distance ratio filtering
|
||||
float dx = lb2.center.x - lb1.center.x;
|
||||
float dy = lb2.center.y - lb1.center.y;
|
||||
float distance = std::sqrt(dx * dx + dy * dy);
|
||||
float avg_length = (lb1.center_line_length + lb2.center_line_length) / 2;
|
||||
float distance_ratio = avg_length > 0 ? distance / avg_length : 0;
|
||||
if (distance_ratio <= ARMOR_DISTANCE_RATIO_MIN || distance_ratio >= ARMOR_DISTANCE_RATIO_MAX) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Length difference filtering
|
||||
float length_diff_ratio = avg_length > 0 ?
|
||||
std::abs(lb1.center_line_length - lb2.center_line_length) / avg_length : 0;
|
||||
if (length_diff_ratio > ARMOR_LENGTH_DIFF_RATIO) {
|
||||
continue;
|
||||
}
|
||||
|
||||
cv::Point2f armor_center(
|
||||
(lb1.center.x + lb2.center.x) / 2,
|
||||
(lb1.center.y + lb2.center.y) / 2
|
||||
);
|
||||
|
||||
double confidence = (lb1.area + lb2.area) / (distance + 1);
|
||||
|
||||
ArmorPlate armor_plate;
|
||||
armor_plate.color = target_color;
|
||||
armor_plate.center = armor_center;
|
||||
armor_plate.confidence = confidence;
|
||||
armor_plate.pair = std::make_pair(lb1, lb2);
|
||||
armor_plate.corners_2d = std::vector<cv::Point2f>(); // Will be computed later if needed
|
||||
|
||||
armor_plates.push_back(armor_plate);
|
||||
|
||||
used[i] = true;
|
||||
used[j] = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by confidence in descending order
|
||||
std::sort(armor_plates.begin(), armor_plates.end(),
|
||||
[](const ArmorPlate& a, const ArmorPlate& b) {
|
||||
return a.confidence > b.confidence;
|
||||
});
|
||||
|
||||
return armor_plates;
|
||||
}
|
||||
|
||||
double ArmorDetector::calculate_iou(const cv::Rect& b1, const cv::Rect& b2) {
|
||||
cv::Point2f inter_tl(std::max(b1.x, b2.x), std::max(b1.y, b2.y));
|
||||
cv::Point2f inter_br(std::min(b1.x + b1.width, b2.x + b2.width),
|
||||
std::min(b1.y + b1.height, b2.y + b2.height));
|
||||
|
||||
if (inter_br.x <= inter_tl.x || inter_br.y <= inter_tl.y) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
float inter_area = (inter_br.x - inter_tl.x) * (inter_br.y - inter_tl.y);
|
||||
float b1_area = b1.width * b1.height;
|
||||
float b2_area = b2.width * b2.height;
|
||||
float union_area = b1_area + b2_area - inter_area;
|
||||
|
||||
return union_area > 0 ? inter_area / union_area : 0.0;
|
||||
}
|
||||
2
Catalyst-MDVS2/src/ArmorDetector.cpp:Zone.Identifier
Normal file
2
Catalyst-MDVS2/src/ArmorDetector.cpp:Zone.Identifier
Normal file
@@ -0,0 +1,2 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
67
Catalyst-MDVS2/src/BallisticPredictor.cpp
Normal file
67
Catalyst-MDVS2/src/BallisticPredictor.cpp
Normal file
@@ -0,0 +1,67 @@
|
||||
#include "BallisticPredictor.h"
|
||||
#include "config.h"
|
||||
#include <cmath>
|
||||
|
||||
BallisticPredictor::BallisticPredictor(float bullet_speed)
|
||||
: bullet_speed(bullet_speed), last_ballistic_point(nullptr) {
|
||||
armor_half_width = ARMOR_WIDTH / 2000.0f; // Convert to meters
|
||||
armor_half_height = ARMOR_HEIGHT / 2000.0f; // Convert to meters
|
||||
}
|
||||
|
||||
BallisticPredictor::~BallisticPredictor() {
|
||||
if (last_ballistic_point != nullptr) {
|
||||
delete last_ballistic_point;
|
||||
last_ballistic_point = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
cv::Point2f* BallisticPredictor::predict_ballistic_point(const cv::Point2f* predicted_center,
|
||||
const cv::Point2f& img_center,
|
||||
const cv::Point2f& target_speed) {
|
||||
// Clean up the last ballistic point before creating a new one
|
||||
if (last_ballistic_point != nullptr) {
|
||||
delete last_ballistic_point;
|
||||
last_ballistic_point = nullptr;
|
||||
}
|
||||
|
||||
if (predicted_center == nullptr) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// 1. Estimate target distance (meters)
|
||||
float distance = calculate_distance(*predicted_center, img_center);
|
||||
|
||||
// 2. Calculate bullet flight time (seconds): distance / bullet speed
|
||||
float flight_time = bullet_speed > 0 ? distance / bullet_speed : 0.0f;
|
||||
|
||||
// 3. Calculate target movement in flight time (pixels)
|
||||
// target speed (pixels/s) * flight time (s) = predicted movement in pixels
|
||||
float delta_x = target_speed.x * flight_time;
|
||||
float delta_y = target_speed.y * flight_time;
|
||||
|
||||
// 4. Ballistic prediction point = Kalman prediction center + target movement compensation
|
||||
float ballistic_x = predicted_center->x + delta_x;
|
||||
float ballistic_y = predicted_center->y + delta_y;
|
||||
cv::Point2f ballistic_point(ballistic_x, ballistic_y);
|
||||
|
||||
// Update last ballistic point
|
||||
last_ballistic_point = new cv::Point2f(ballistic_point);
|
||||
|
||||
return last_ballistic_point;
|
||||
}
|
||||
|
||||
float BallisticPredictor::calculate_distance(const cv::Point2f& armor_center, const cv::Point2f& img_center, float focal_length) {
|
||||
// Calculate the pixel distance from armor center to image center
|
||||
float dx = std::abs(armor_center.x - img_center.x);
|
||||
float dy = std::abs(armor_center.y - img_center.y);
|
||||
float pixel_distance = std::sqrt(dx * dx + dy * dy);
|
||||
|
||||
// If target is near the center, avoid division by zero
|
||||
if (pixel_distance < 10) {
|
||||
return 5.0f; // Default 5 meters (adjust based on actual scenario)
|
||||
}
|
||||
|
||||
// Distance estimation formula: (actual size * focal length) / pixel size
|
||||
float distance = (armor_half_width * focal_length) / (pixel_distance * 0.5f);
|
||||
return std::max(0.5f, distance); // Limit minimum distance to 0.5 meters
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
90
Catalyst-MDVS2/src/Camera.cpp
Normal file
90
Catalyst-MDVS2/src/Camera.cpp
Normal file
@@ -0,0 +1,90 @@
|
||||
#include "Camera.h"
|
||||
#include <iostream>
|
||||
|
||||
Camera::Camera(int cam_id, const std::string& target_color) {
|
||||
// 先设置为 MJPEG 模式再打开(某些驱动要求)
|
||||
cap.open(cam_id, cv::CAP_V4L2);
|
||||
if (!cap.isOpened()) {
|
||||
throw std::runtime_error("Cannot open camera!");
|
||||
}
|
||||
|
||||
// 必须先设 FOURCC,再设分辨率和帧率!顺序很重要
|
||||
cap.set(cv::CAP_PROP_FOURCC, cv::VideoWriter::fourcc('M', 'J', 'P', 'G'));
|
||||
cap.set(cv::CAP_PROP_FRAME_WIDTH, 640);
|
||||
cap.set(cv::CAP_PROP_FRAME_HEIGHT, 480);
|
||||
cap.set(cv::CAP_PROP_FPS, 100);
|
||||
|
||||
is_opened = true;
|
||||
this->target_color = target_color;
|
||||
if (this->target_color != "red" && this->target_color != "blue") {
|
||||
throw std::invalid_argument("Only 'red' or 'blue' colors are supported");
|
||||
}
|
||||
|
||||
set_cam_params(); // 再次应用参数(包括曝光等)
|
||||
}
|
||||
|
||||
Camera::~Camera() {
|
||||
release();
|
||||
}
|
||||
|
||||
void Camera::set_cam_params() {
|
||||
// 先设 FOURCC(顺序很重要!)
|
||||
cap.set(cv::CAP_PROP_FOURCC, cv::VideoWriter::fourcc('M', 'J', 'P', 'G'));
|
||||
|
||||
const int width = 640;
|
||||
const int height = 480;
|
||||
const int fps = 60; // 从 80 降到 60
|
||||
|
||||
cap.set(cv::CAP_PROP_FRAME_WIDTH, width);
|
||||
cap.set(cv::CAP_PROP_FRAME_HEIGHT, height);
|
||||
cap.set(cv::CAP_PROP_FPS, fps);
|
||||
|
||||
cap.set(cv::CAP_PROP_AUTOFOCUS, 1);
|
||||
cap.set(cv::CAP_PROP_AUTO_WB, 1);
|
||||
cap.set(cv::CAP_PROP_AUTO_EXPOSURE, 0); // 手动曝光
|
||||
|
||||
if (target_color == "red") {
|
||||
cap.set(cv::CAP_PROP_EXPOSURE, -50); // 可微调
|
||||
//cap.set(cv::CAP_PROP_CONTRAST,50);
|
||||
} else if (target_color == "blue") {
|
||||
cap.set(cv::CAP_PROP_EXPOSURE, -8);
|
||||
}
|
||||
cap.set(cv::CAP_PROP_WB_TEMPERATURE, 3200);
|
||||
|
||||
// 验证
|
||||
double w = cap.get(cv::CAP_PROP_FRAME_WIDTH);
|
||||
double h = cap.get(cv::CAP_PROP_FRAME_HEIGHT);
|
||||
double f = cap.get(cv::CAP_PROP_FPS);
|
||||
double fourcc = cap.get(cv::CAP_PROP_FOURCC);
|
||||
char str[5] = {0};
|
||||
memcpy(str, &fourcc, 4);
|
||||
std::cout << "Actual: " << w << "x" << h << " @ " << f << "fps, FOURCC='" << str << "'" << std::endl;
|
||||
}
|
||||
bool Camera::read_frame(cv::Mat& frame) {
|
||||
if (!is_opened) {
|
||||
return false;
|
||||
}
|
||||
return cap.read(frame);
|
||||
}
|
||||
|
||||
void Camera::release() {
|
||||
if (is_opened) {
|
||||
cap.release();
|
||||
is_opened = false;
|
||||
}
|
||||
}
|
||||
|
||||
bool Camera::switch_color(const std::string& new_color) {
|
||||
std::string lower_color = new_color;
|
||||
// Convert to lowercase manually
|
||||
for (auto& c : lower_color) {
|
||||
c = std::tolower(c);
|
||||
}
|
||||
|
||||
if ((lower_color == "red" || lower_color == "blue") && lower_color != target_color) {
|
||||
target_color = lower_color;
|
||||
set_cam_params();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
2
Catalyst-MDVS2/src/Camera.cpp:Zone.Identifier
Normal file
2
Catalyst-MDVS2/src/Camera.cpp:Zone.Identifier
Normal file
@@ -0,0 +1,2 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
25
Catalyst-MDVS2/src/ImagePreprocessor.cpp
Normal file
25
Catalyst-MDVS2/src/ImagePreprocessor.cpp
Normal file
@@ -0,0 +1,25 @@
|
||||
#include "ImagePreprocessor.h"
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
|
||||
ImagePreprocessor::ImagePreprocessor() {
|
||||
// Constructor implementation
|
||||
}
|
||||
|
||||
ImagePreprocessor::~ImagePreprocessor() {
|
||||
// Destructor implementation
|
||||
}
|
||||
|
||||
void ImagePreprocessor::apply_morphology(const cv::Mat& input_mask, cv::Mat& output_mask) {
|
||||
// Apply morphological operations to reduce noise
|
||||
cv::Mat kernel = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3));
|
||||
cv::morphologyEx(input_mask, output_mask, cv::MORPH_OPEN, kernel);
|
||||
cv::morphologyEx(output_mask, output_mask, cv::MORPH_CLOSE, kernel);
|
||||
}
|
||||
|
||||
void ImagePreprocessor::apply_gaussian_blur(const cv::Mat& input, cv::Mat& output, int kernel_size) {
|
||||
// Apply Gaussian blur to reduce noise
|
||||
// Ensure kernel size is odd for Gaussian blur
|
||||
int adjusted_kernel_size = kernel_size % 2 == 0 ? kernel_size + 1 : kernel_size;
|
||||
cv::GaussianBlur(input, output, cv::Size(adjusted_kernel_size, adjusted_kernel_size), 0);
|
||||
}
|
||||
2
Catalyst-MDVS2/src/ImagePreprocessor.cpp:Zone.Identifier
Normal file
2
Catalyst-MDVS2/src/ImagePreprocessor.cpp:Zone.Identifier
Normal file
@@ -0,0 +1,2 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
163
Catalyst-MDVS2/src/KalmanFilter.cpp
Normal file
163
Catalyst-MDVS2/src/KalmanFilter.cpp
Normal file
@@ -0,0 +1,163 @@
|
||||
#include "KalmanFilter.h"
|
||||
#include "config.h"
|
||||
#include <iostream>
|
||||
#include <chrono>
|
||||
|
||||
KalmanFilter::KalmanFilter() {
|
||||
// 6 state variables (x, y, vx, vy, ax, ay), 2 measurements (x, y)
|
||||
kf.init(6, 2, 0);
|
||||
init_params();
|
||||
initialized = false;
|
||||
has_prev_measurement = false;
|
||||
has_prev_velocity = false;
|
||||
time_elapsed = 1.0 / 100.0; // Assuming 100 FPS as default
|
||||
last_measurement = cv::Point2f(0, 0);
|
||||
last_prediction = cv::Point2f(0, 0);
|
||||
prev_measurement = cv::Point2f(0, 0);
|
||||
prev_velocity = cv::Point2f(0, 0);
|
||||
}
|
||||
|
||||
void KalmanFilter::init_params() {
|
||||
// Transition matrix for constant acceleration model
|
||||
// x(k+1) = x(k) + vx(k)*dt + 0.5*ax(k)*dt^2
|
||||
// y(k+1) = y(k) + vy(k)*dt + 0.5*ay(k)*dt^2
|
||||
// vx(k+1) = vx(k) + ax(k)*dt
|
||||
// vy(k+1) = vy(k) + ay(k)*dt
|
||||
// ax(k+1) = ax(k)
|
||||
// ay(k+1) = ay(k)
|
||||
|
||||
double dt = time_elapsed;
|
||||
kf.transitionMatrix = (cv::Mat_<float>(6, 6) <<
|
||||
1, 0, dt, 0, 0.5*dt*dt, 0,
|
||||
0, 1, 0, dt, 0, 0.5*dt*dt,
|
||||
0, 0, 1, 0, dt, 0,
|
||||
0, 0, 0, 1, 0, dt,
|
||||
0, 0, 0, 0, 1, 0,
|
||||
0, 0, 0, 0, 0, 1
|
||||
);
|
||||
|
||||
// Measurement matrix: measuring x and y only
|
||||
kf.measurementMatrix = (cv::Mat_<float>(2, 6) <<
|
||||
1, 0, 0, 0, 0, 0,
|
||||
0, 1, 0, 0, 0, 0
|
||||
);
|
||||
|
||||
// Process noise covariance - higher for acceleration components
|
||||
kf.processNoiseCov = cv::Mat::zeros(6, 6, CV_32F);
|
||||
kf.processNoiseCov.at<float>(0, 0) = 1.0f; // x position noise
|
||||
kf.processNoiseCov.at<float>(1, 1) = 1.0f; // y position noise
|
||||
kf.processNoiseCov.at<float>(2, 2) = 4.0f; // x velocity noise
|
||||
kf.processNoiseCov.at<float>(3, 3) = 4.0f; // y velocity noise
|
||||
kf.processNoiseCov.at<float>(4, 4) = 8.0f; // x acceleration noise
|
||||
kf.processNoiseCov.at<float>(5, 5) = 8.0f; // y acceleration noise
|
||||
|
||||
// Measurement noise covariance
|
||||
kf.measurementNoiseCov = cv::Mat::eye(2, 2, CV_32F) * 0.1f; // Lower measurement noise
|
||||
|
||||
// Error covariance post
|
||||
kf.errorCovPost = cv::Mat::eye(6, 6, CV_32F) * 0.1f;
|
||||
}
|
||||
|
||||
cv::Point2f KalmanFilter::estimate_velocity(const cv::Point2f& current, const cv::Point2f& previous) {
|
||||
// Calculate velocity based on position difference
|
||||
cv::Point2f velocity = current - previous;
|
||||
velocity.x /= (float)time_elapsed;
|
||||
velocity.y /= (float)time_elapsed;
|
||||
return velocity;
|
||||
}
|
||||
|
||||
void KalmanFilter::updateProcessNoise(const cv::Point2f& current_measurement) {
|
||||
if (has_prev_measurement && has_prev_velocity) {
|
||||
// Estimate current velocity
|
||||
cv::Point2f current_velocity = estimate_velocity(current_measurement, prev_measurement);
|
||||
|
||||
// Calculate acceleration based on change in velocity
|
||||
cv::Point2f acceleration = current_velocity - prev_velocity;
|
||||
acceleration.x /= (float)time_elapsed;
|
||||
acceleration.y /= (float)time_elapsed;
|
||||
|
||||
// Adjust process noise based on estimated acceleration (higher acceleration = higher uncertainty)
|
||||
float acc_magnitude = std::sqrt(acceleration.x * acceleration.x + acceleration.y * acceleration.y);
|
||||
|
||||
// Increase process noise for rapid maneuvers
|
||||
float noise_factor = 1.0f + 0.5f * acc_magnitude;
|
||||
|
||||
kf.processNoiseCov.at<float>(4, 4) = 8.0f * noise_factor; // ax noise
|
||||
kf.processNoiseCov.at<float>(5, 5) = 8.0f * noise_factor; // ay noise
|
||||
}
|
||||
}
|
||||
|
||||
void KalmanFilter::update(const cv::Point2f& measurement) {
|
||||
cv::Mat measurement_mat = (cv::Mat_<float>(2, 1) << measurement.x, measurement.y);
|
||||
|
||||
if (!initialized) {
|
||||
// Initialize state if not done yet
|
||||
kf.statePost = (cv::Mat_<float>(6, 1) <<
|
||||
measurement.x, // x position
|
||||
measurement.y, // y position
|
||||
0.0f, // x velocity
|
||||
0.0f, // y velocity
|
||||
0.0f, // x acceleration
|
||||
0.0f // y acceleration
|
||||
);
|
||||
initialized = true;
|
||||
} else {
|
||||
// Update process noise based on target movement characteristics
|
||||
updateProcessNoise(measurement);
|
||||
|
||||
// Perform correction step
|
||||
kf.correct(measurement_mat);
|
||||
}
|
||||
|
||||
// Update previous state for next iteration
|
||||
if (has_prev_measurement) {
|
||||
// Calculate velocity based on position change
|
||||
cv::Point2f current_velocity = estimate_velocity(measurement, prev_measurement);
|
||||
|
||||
if (has_prev_velocity) {
|
||||
// Estimate acceleration based on velocity change
|
||||
cv::Point2f acceleration = current_velocity - prev_velocity;
|
||||
acceleration.x /= (float)time_elapsed;
|
||||
acceleration.y /= (float)time_elapsed;
|
||||
|
||||
// Update state with estimated acceleration
|
||||
kf.statePost.at<float>(4) = acceleration.x; // x acceleration
|
||||
kf.statePost.at<float>(5) = acceleration.y; // y acceleration
|
||||
}
|
||||
|
||||
// Update previous velocity
|
||||
prev_velocity = current_velocity;
|
||||
has_prev_velocity = true;
|
||||
} else {
|
||||
// Initialize previous velocity as zero
|
||||
prev_velocity = cv::Point2f(0, 0);
|
||||
has_prev_velocity = true;
|
||||
}
|
||||
|
||||
// Update stored measurements
|
||||
prev_measurement = last_measurement;
|
||||
has_prev_measurement = true;
|
||||
last_measurement = measurement;
|
||||
}
|
||||
|
||||
cv::Point2f KalmanFilter::get_current_velocity() const {
|
||||
if (!initialized) {
|
||||
return cv::Point2f(0.0f, 0.0f);
|
||||
}
|
||||
|
||||
// Return the velocity components from the state vector
|
||||
float vx = kf.statePost.at<float>(2);
|
||||
float vy = kf.statePost.at<float>(3);
|
||||
return cv::Point2f(vx, vy);
|
||||
}
|
||||
|
||||
cv::Point2f KalmanFilter::predict() {
|
||||
if (!initialized) {
|
||||
return cv::Point2f(0, 0);
|
||||
}
|
||||
|
||||
cv::Mat prediction = kf.predict();
|
||||
cv::Point2f result(prediction.at<float>(0), prediction.at<float>(1));
|
||||
last_prediction = result;
|
||||
return result;
|
||||
}
|
||||
2
Catalyst-MDVS2/src/KalmanFilter.cpp:Zone.Identifier
Normal file
2
Catalyst-MDVS2/src/KalmanFilter.cpp:Zone.Identifier
Normal file
@@ -0,0 +1,2 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
335
Catalyst-MDVS2/src/MindVisionCamera.cpp
Normal file
335
Catalyst-MDVS2/src/MindVisionCamera.cpp
Normal file
@@ -0,0 +1,335 @@
|
||||
#include "MindVisionCamera.h"
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
|
||||
MindVisionCamera::MindVisionCamera(int cam_id, const std::string& target_color)
|
||||
: camera_handle(-1), is_opened(false), width(640), height(480), fps(100), g_pRgbBuffer(nullptr) {
|
||||
|
||||
if (!initialize_camera(cam_id)) {
|
||||
// 即使初始化失败,也要清理可能已分配的资源
|
||||
release();
|
||||
throw std::runtime_error("Cannot initialize MindVision camera!");
|
||||
}
|
||||
|
||||
is_opened = true;
|
||||
this->target_color = target_color;
|
||||
if (this->target_color != "red" && this->target_color != "blue") {
|
||||
release(); // 清理已初始化的资源
|
||||
throw std::invalid_argument("Only 'red' or 'blue' colors are supported");
|
||||
}
|
||||
|
||||
if (!set_cam_params()) { // 修改:set_cam_params现在返回bool值
|
||||
release(); // 清理已初始化的资源
|
||||
throw std::runtime_error("Failed to set camera parameters!");
|
||||
}
|
||||
}
|
||||
|
||||
bool MindVisionCamera::initialize_camera(int cam_id) {
|
||||
// 初始化SDK
|
||||
CameraSdkInit(1);
|
||||
|
||||
int iCameraCounts = 10;
|
||||
tSdkCameraDevInfo tCameraEnumList[10]; // 声明为数组而不是指针
|
||||
|
||||
// 枚举设备,并建立设备列表
|
||||
int iStatus = CameraEnumerateDevice(tCameraEnumList, &iCameraCounts);
|
||||
std::cout << "CameraEnumerateDevice returned: " << iStatus << std::endl;
|
||||
std::cout << "Found " << iCameraCounts << " cameras" << std::endl;
|
||||
|
||||
if (iCameraCounts <= 0) {
|
||||
std::cerr << "No MindVision cameras found!" << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
// 选择指定ID的相机
|
||||
if (cam_id >= iCameraCounts) {
|
||||
std::cerr << "Camera ID " << cam_id << " not found! Only " << iCameraCounts << " cameras detected." << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
std::cout << "Initializing camera " << cam_id << ": " << tCameraEnumList[cam_id].acFriendlyName << std::endl;
|
||||
|
||||
// 相机初始化
|
||||
iStatus = CameraInit(&tCameraEnumList[cam_id], -1, -1, &camera_handle);
|
||||
std::cout << "CameraInit returned: " << iStatus << std::endl;
|
||||
|
||||
if (iStatus != CAMERA_STATUS_SUCCESS) {
|
||||
std::cerr << "Failed to initialize camera! Error code: " << iStatus << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
// 获取相机能力
|
||||
iStatus = CameraGetCapability(camera_handle, &capability);
|
||||
if (iStatus != CAMERA_STATUS_SUCCESS) {
|
||||
std::cerr << "Failed to get camera capability! Error code: " << iStatus << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
// 设置输出格式 - 保持与原始工作项目一致,直接设置为BGR8格式
|
||||
CameraSetIspOutFormat(camera_handle, CAMERA_MEDIA_TYPE_BGR8);
|
||||
|
||||
// 让SDK进入工作模式 - 根据原始OpenCv项目,应该在设置格式前调用
|
||||
CameraPlay(camera_handle);
|
||||
|
||||
// 获取并设置分辨率为 640x480
|
||||
int status = CameraGetImageResolution(camera_handle, &image_resolution);
|
||||
std::cout << "Default resolution query returned: " << status << std::endl;
|
||||
|
||||
// 设置分辨率为 640x480
|
||||
image_resolution.iIndex = 0xFF; // Use custom resolution (0xFF typically indicates custom resolution)
|
||||
image_resolution.iWidth = 640;
|
||||
image_resolution.iHeight = 480;
|
||||
image_resolution.iWidthFOV = image_resolution.iWidth;
|
||||
image_resolution.iHeightFOV = image_resolution.iHeight;
|
||||
image_resolution.iHOffsetFOV = 0;
|
||||
image_resolution.iVOffsetFOV = 0;
|
||||
|
||||
status = CameraSetImageResolution(camera_handle, &image_resolution);
|
||||
if (status != CAMERA_STATUS_SUCCESS) {
|
||||
std::cout << "Failed to set resolution to 640x480, using default settings" << std::endl;
|
||||
// Try to get the current resolution after failed set
|
||||
CameraGetImageResolution(camera_handle, &image_resolution);
|
||||
} else {
|
||||
std::cout << "Successfully set camera resolution to: " << image_resolution.iWidth << "x" << image_resolution.iHeight << std::endl;
|
||||
}
|
||||
|
||||
width = image_resolution.iWidth;
|
||||
height = image_resolution.iHeight;
|
||||
|
||||
// 分配处理后的数据缓存区 - 使用最大分辨率,与原始项目一致
|
||||
g_pRgbBuffer = (unsigned char *)malloc(capability.sResolutionRange.iHeightMax *
|
||||
capability.sResolutionRange.iWidthMax * 3);
|
||||
|
||||
// 设置帧率(虽然稍后 set_cam_params 会再次设置,但这里先设定)
|
||||
CameraSetFrameSpeed(camera_handle, 2); // 设置为较高帧率
|
||||
|
||||
std::cout << "Initialized camera with resolution: " << width << "x" << height << std::endl;
|
||||
|
||||
if (!g_pRgbBuffer) {
|
||||
std::cerr << "Failed to allocate global RGB buffer" << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
MindVisionCamera::~MindVisionCamera() {
|
||||
try {
|
||||
if (g_pRgbBuffer) {
|
||||
free(g_pRgbBuffer);
|
||||
g_pRgbBuffer = nullptr;
|
||||
}
|
||||
release();
|
||||
} catch (...) {
|
||||
// 析构函数中捕获异常但不重新抛出
|
||||
// 确保即使在异常情况下也能正确清理资源
|
||||
}
|
||||
}
|
||||
|
||||
void MindVisionCamera::set_camera_parameters() {
|
||||
// 先设置为手动曝光模式
|
||||
CameraSetAeState(camera_handle, false);
|
||||
|
||||
// 根据颜色设置曝光参数,以优化装甲板检测效果
|
||||
if (target_color == "red") {
|
||||
CameraSetExposureTime(camera_handle, 5000); // 红色目标,曝光时间5ms (5000微秒)
|
||||
} else if (target_color == "blue") {
|
||||
CameraSetExposureTime(camera_handle, 8000); // 蓝色目标,曝光时间8ms (8000微秒)
|
||||
}
|
||||
|
||||
// 设置白平衡
|
||||
CameraSetWbMode(camera_handle, false); // 关闭自动白平衡
|
||||
CameraSetOnceWB(camera_handle); // 一次性白平衡
|
||||
|
||||
// 设置其他参数
|
||||
CameraSetTriggerMode(camera_handle, 0); // 连续采集模式
|
||||
|
||||
// 设置帧率为100FPS
|
||||
CameraSetFrameSpeed(camera_handle, 2); // 2代表较高帧率,具体值可能需要调整
|
||||
}
|
||||
|
||||
bool MindVisionCamera::set_cam_params() {
|
||||
// 只设置相机参数(如曝光、白平衡等),不重新设置分辨率
|
||||
set_camera_parameters();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool MindVisionCamera::read_frame(cv::Mat& frame) {
|
||||
if (!is_opened) {
|
||||
return false;
|
||||
}
|
||||
|
||||
tSdkFrameHead sFrameInfo;
|
||||
BYTE* pbyBuffer;
|
||||
|
||||
// 获取一帧数据
|
||||
if (CameraGetImageBuffer(camera_handle, &sFrameInfo, &pbyBuffer, 1000) == CAMERA_STATUS_SUCCESS) {
|
||||
// 直接使用CameraGetImageBufferEx获取处理后的RGB数据,提高效率
|
||||
INT width, height;
|
||||
unsigned char* pData = CameraGetImageBufferEx(camera_handle, &width, &height, 2000);
|
||||
if(pData != NULL) {
|
||||
// 创建OpenCV Mat对象,直接使用获取的数据
|
||||
cv::Mat temp_mat(height, width, CV_8UC3, pData);
|
||||
frame = temp_mat.clone(); // clone()确保数据被复制,而不是共享指针
|
||||
|
||||
// CameraGetImageBufferEx方式不需要手动释放缓冲区
|
||||
return true;
|
||||
}
|
||||
|
||||
// 使用全局缓冲区处理图像数据 - 与原始项目一致
|
||||
int status = CameraImageProcess(camera_handle, pbyBuffer, g_pRgbBuffer, &sFrameInfo);
|
||||
if (status != CAMERA_STATUS_SUCCESS) {
|
||||
std::cerr << "Failed to process image: error code " << status << std::endl;
|
||||
CameraReleaseImageBuffer(camera_handle, pbyBuffer);
|
||||
return false;
|
||||
}
|
||||
|
||||
// 创建OpenCV Mat对象 - 使用全局缓冲区,固定为CV_8UC3格式
|
||||
cv::Mat temp_mat(sFrameInfo.iHeight, sFrameInfo.iWidth, CV_8UC3, g_pRgbBuffer);
|
||||
frame = temp_mat.clone(); // clone()确保数据被复制,而不是共享指针
|
||||
|
||||
// 释放原始缓冲区
|
||||
CameraReleaseImageBuffer(camera_handle, pbyBuffer);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool MindVisionCamera::read_frame_with_color_filter(cv::Mat& frame, cv::Mat& raw_mask, const std::string& target_color) {
|
||||
if (!is_opened) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 尝试使用CameraGetImageBufferEx方式获取图像
|
||||
INT width, height;
|
||||
unsigned char* pData = CameraGetImageBufferEx(camera_handle, &width, &height, 2000);
|
||||
if(pData != NULL) {
|
||||
// 创建OpenCV Mat对象,直接使用获取的数据
|
||||
cv::Mat original_img(height, width, CV_8UC3, pData);
|
||||
frame = original_img.clone(); // clone()确保数据被复制,而不是共享指针
|
||||
|
||||
// 创建HSV图像用于颜色过滤
|
||||
cv::Mat hsv_img;
|
||||
cv::cvtColor(frame, hsv_img, cv::COLOR_BGR2HSV);
|
||||
|
||||
// 根据颜色创建原始掩码
|
||||
if (target_color == "red") {
|
||||
// Red color range in HSV
|
||||
cv::Mat mask1, mask2;
|
||||
cv::inRange(hsv_img, cv::Scalar(0, 43, 49), cv::Scalar(25, 255, 255), mask1);
|
||||
cv::inRange(hsv_img, cv::Scalar(156, 46, 49), cv::Scalar(180, 255, 255), mask2);
|
||||
raw_mask = mask1 | mask2;
|
||||
} else if (target_color == "blue") {
|
||||
// Blue color range in HSV
|
||||
cv::inRange(hsv_img, cv::Scalar(83, 200, 44), cv::Scalar(130, 255, 255), raw_mask);
|
||||
} else {
|
||||
raw_mask = cv::Mat::zeros(hsv_img.size(), CV_8UC1);
|
||||
}
|
||||
|
||||
// CameraGetImageBufferEx方式不需要手动释放缓冲区
|
||||
return true;
|
||||
}
|
||||
|
||||
// 如果CameraGetImageBufferEx失败,回退到原来的方式
|
||||
|
||||
tSdkFrameHead sFrameInfo;
|
||||
BYTE* pbyBuffer;
|
||||
|
||||
// 获取一帧数据
|
||||
if (CameraGetImageBuffer(camera_handle, &sFrameInfo, &pbyBuffer, 1000) == CAMERA_STATUS_SUCCESS) {
|
||||
// 使用全局缓冲区处理图像数据 - 与原始项目一致
|
||||
int status = CameraImageProcess(camera_handle, pbyBuffer, g_pRgbBuffer, &sFrameInfo);
|
||||
if (status != CAMERA_STATUS_SUCCESS) {
|
||||
std::cerr << "Failed to process image: error code " << status << std::endl;
|
||||
CameraReleaseImageBuffer(camera_handle, pbyBuffer);
|
||||
return false;
|
||||
}
|
||||
|
||||
// 创建原始RGB图像 - 使用全局缓冲区,固定为CV_8UC3格式
|
||||
cv::Mat original_img(sFrameInfo.iHeight, sFrameInfo.iWidth, CV_8UC3, g_pRgbBuffer);
|
||||
|
||||
// 复制图像数据,确保原始数据不会被后续操作影响
|
||||
frame = original_img.clone();
|
||||
|
||||
// 创建HSV图像用于颜色过滤
|
||||
cv::Mat hsv_img;
|
||||
cv::cvtColor(frame, hsv_img, cv::COLOR_BGR2HSV);
|
||||
|
||||
// 根据颜色创建原始掩码
|
||||
if (target_color == "red") {
|
||||
// Red color range in HSV
|
||||
cv::Mat mask1, mask2;
|
||||
cv::inRange(hsv_img, cv::Scalar(0, 43, 49), cv::Scalar(25, 255, 255), mask1);
|
||||
cv::inRange(hsv_img, cv::Scalar(156, 46, 49), cv::Scalar(180, 255, 255), mask2);
|
||||
raw_mask = mask1 | mask2;
|
||||
} else if (target_color == "blue") {
|
||||
// Blue color range in HSV
|
||||
cv::inRange(hsv_img, cv::Scalar(83, 200, 44), cv::Scalar(130, 255, 255), raw_mask);
|
||||
} else {
|
||||
raw_mask = cv::Mat::zeros(hsv_img.size(), CV_8UC1);
|
||||
}
|
||||
|
||||
// 释放相机缓冲区
|
||||
CameraReleaseImageBuffer(camera_handle, pbyBuffer);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void MindVisionCamera::release() {
|
||||
if (camera_handle != 0) {
|
||||
// 停止采集,不管is_opened状态如何都尝试释放
|
||||
CameraPause(camera_handle);
|
||||
CameraUnInit(camera_handle);
|
||||
camera_handle = -1;
|
||||
}
|
||||
if(g_pRgbBuffer) {
|
||||
free(g_pRgbBuffer);
|
||||
g_pRgbBuffer = nullptr;
|
||||
}
|
||||
is_opened = false;
|
||||
}
|
||||
|
||||
bool MindVisionCamera::switch_color(const std::string& new_color) {
|
||||
std::string lower_color = new_color;
|
||||
// Convert to lowercase manually
|
||||
for (auto& c : lower_color) {
|
||||
c = std::tolower(c);
|
||||
}
|
||||
|
||||
if ((lower_color == "red" || lower_color == "blue") && lower_color != target_color) {
|
||||
target_color = lower_color;
|
||||
return set_cam_params(); // 返回set_cam_params的结果
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool MindVisionCamera::set_resolution(int width, int height){
|
||||
if (!is_opened) {
|
||||
return false;
|
||||
}
|
||||
|
||||
tSdkImageResolution res;
|
||||
int status = CameraGetImageResolution(camera_handle, &res);
|
||||
|
||||
res.iIndex = 0xFF;
|
||||
res.iWidth = width;
|
||||
res.iHeight = height;
|
||||
res.iWidthFOV = capability.sResolutionRange.iWidthMax;
|
||||
res.iHeightFOV = capability.sResolutionRange.iHeightMax;
|
||||
res.iHOffsetFOV = 0;
|
||||
res.iVOffsetFOV = 0;
|
||||
|
||||
status = CameraSetImageResolution(camera_handle, &res);
|
||||
if (status == CAMERA_STATUS_SUCCESS) {
|
||||
this->width = width;
|
||||
this->height = height;
|
||||
image_resolution = res;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
2
Catalyst-MDVS2/src/MindVisionCamera.cpp:Zone.Identifier
Normal file
2
Catalyst-MDVS2/src/MindVisionCamera.cpp:Zone.Identifier
Normal file
@@ -0,0 +1,2 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
354
Catalyst-MDVS2/src/MindVisionMain.cpp
Normal file
354
Catalyst-MDVS2/src/MindVisionMain.cpp
Normal file
@@ -0,0 +1,354 @@
|
||||
#include <cstdlib>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <chrono>
|
||||
#include <thread>
|
||||
#include <memory>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <opencv2/opencv.hpp>
|
||||
#include <opencv2/tracking.hpp>
|
||||
|
||||
#include "config.h"
|
||||
#include "MindVisionCamera.h" // 使用MindVision相机
|
||||
#include "ImagePreprocessor.h"
|
||||
#include "ArmorDetector.h"
|
||||
#include "KalmanFilter.h"
|
||||
#include "Visualizer.h"
|
||||
#include "BallisticPredictor.h"
|
||||
#include "TTLCommunicator.h"
|
||||
|
||||
// Function to output control data to TTL device (with enable control)
|
||||
void output_control_data(const cv::Point2f* ballistic_point,
|
||||
const std::string& target_color,
|
||||
TTLCommunicator* ttl_communicator,
|
||||
const cv::Point2f& img_center,
|
||||
bool use_ttl) {
|
||||
// Only send data when TTL is enabled and has valid target
|
||||
if (use_ttl && ballistic_point != nullptr) {
|
||||
std::ostringstream send_str;
|
||||
|
||||
// Calculate offset (based on actual image center)
|
||||
int ballistic_offset_x = -static_cast<int>(ballistic_point->x - img_center.x);
|
||||
if ( abs(ballistic_offset_x) > 320){
|
||||
ballistic_offset_x = ( ballistic_offset_x / abs( ballistic_offset_x ) ) * 320 ;
|
||||
}
|
||||
int ballistic_offset_y = -static_cast<int>(img_center.y - ballistic_point->y);
|
||||
if ( abs(ballistic_offset_y) > 180 ) {
|
||||
ballistic_offset_y = ( ballistic_offset_x / abs( ballistic_offset_x ) ) * 180 ;
|
||||
}
|
||||
|
||||
// Color simplification mapping
|
||||
std::string simplified_color = target_color;
|
||||
if (target_color == "red") simplified_color = "r";
|
||||
else if (target_color == "blue") simplified_color = "b";
|
||||
|
||||
// Construct send string (original format)
|
||||
send_str << "#s " << simplified_color << " " << std::to_string(ballistic_offset_x) << " " << std::to_string(ballistic_offset_y) << "*\n";
|
||||
|
||||
// Send data
|
||||
if (ttl_communicator != nullptr) {
|
||||
ttl_communicator->send_data(send_str.str());
|
||||
}else{
|
||||
std::cerr << "Error: TTLCommunicator is a null pointer!" << std::endl;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void set_camera_resolution(MindVisionCamera& camera, int width, int height) {
|
||||
// The resolution is set during camera initialization in MindVision
|
||||
// We need to implement a method in MindVisionCamera to change resolution
|
||||
// For now, we'll just log the intended change
|
||||
if (camera.set_resolution(width, height)){
|
||||
std::cout << "Successfully set camera resolution to: " << width << "x" << height << std::endl;
|
||||
} else {
|
||||
std::cerr << "Failed to set camera resolution to: " << width << "x" << height << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
int main(int /*argc*/, char* /*argv*/[]) {
|
||||
static int Numbe = 0;
|
||||
std::string target_color = "red";
|
||||
int cam_id = 0;
|
||||
cv::Size default_resolution(640, 480); // Changed to 640x480 for consistency with SJTU project
|
||||
bool use_ttl = false; // Set to false to disable TTL communication
|
||||
|
||||
|
||||
if (Numbe == 0) {
|
||||
// 执行 shell 命令(注意安全风险!)
|
||||
std::system("sudo chmod 777 /dev/tty*");
|
||||
Numbe++;
|
||||
}
|
||||
|
||||
// Define optional resolution list (adjust based on camera support)
|
||||
std::vector<cv::Size> resolutions = {
|
||||
cv::Size(320, 240), // Low resolution, high frame rate
|
||||
cv::Size(640, 480), // Standard resolution
|
||||
cv::Size(1280, 720), // HD resolution
|
||||
cv::Size(1920, 1080) // Full HD resolution
|
||||
};
|
||||
|
||||
// Find the index of default resolution
|
||||
int res_index = 1; // Default to index 1 (640x480)
|
||||
for (size_t i = 0; i < resolutions.size(); i++) {
|
||||
if (resolutions[i] == default_resolution) {
|
||||
res_index = static_cast<int>(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize TTL communication (only when enabled)
|
||||
TTLCommunicator* ttl = nullptr;
|
||||
if (use_ttl) {
|
||||
// On Linux, the port would typically be /dev/ttyUSB0, /dev/ttyACM0, etc.
|
||||
ttl = new TTLCommunicator("/dev/ttyUSB0", TTL_BAUDRATE);
|
||||
if (ttl != nullptr) {
|
||||
if (!ttl->connect()) {
|
||||
std::cout << "Warning: Cannot establish TTL connection, will continue running but not send data" << std::endl;
|
||||
}
|
||||
} else {
|
||||
std::cout << "Error: Failed to create TTL communicator instance" << std::endl;
|
||||
}
|
||||
} else {
|
||||
std::cout << "TTL communication disabled" << std::endl;
|
||||
}
|
||||
|
||||
// Initialize visual processing modules with MindVision camera
|
||||
MindVisionCamera camera(cam_id, target_color);
|
||||
if (!camera.is_opened) {
|
||||
std::cerr << "Cannot open MindVision camera!" << std::endl;
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Initialize ballistic predictor (adjustable bullet speed, e.g., 16m/s)
|
||||
BallisticPredictor ballistic_predictor(16.0f);
|
||||
// Record target speed (obtained from Kalman filter)
|
||||
cv::Point2f target_speed(0.0f, 0.0f);
|
||||
|
||||
// Set initial resolution
|
||||
set_camera_resolution(camera, resolutions[res_index].width, resolutions[res_index].height);
|
||||
std::cout << "Initial camera resolution: " << resolutions[res_index].width << "x" << resolutions[res_index].height << std::endl;
|
||||
|
||||
ImagePreprocessor preprocessor;
|
||||
ArmorDetector detector;
|
||||
KalmanFilter kalman_tracker;
|
||||
Visualizer visualizer;
|
||||
|
||||
// Initialize KCF tracker
|
||||
cv::Ptr<cv::Tracker> tracker = cv::TrackerKCF::create();
|
||||
bool is_tracking = false;
|
||||
cv::Rect2d tracking_roi;
|
||||
int tracking_frame_count = 0;
|
||||
const int MAX_TRACKING_FRAMES = 100; // Maximum frames to track before returning to search
|
||||
|
||||
int frame_counter = 0; // Counter to control output frequency
|
||||
int max_consecutive_predicts = 20; // Maximum consecutive prediction times
|
||||
int consecutive_predicts = 0; // Current consecutive prediction count
|
||||
|
||||
cv::Mat frame;
|
||||
try {
|
||||
while (true) {
|
||||
// 使用新的颜色过滤方法同时获取图像和原始掩码
|
||||
|
||||
cv::Mat raw_mask;
|
||||
if (!camera.read_frame_with_color_filter(frame, raw_mask, target_color)) {
|
||||
std::cout << "Cannot read from MindVision camera, exiting!,HERERER" << std::endl;
|
||||
break;
|
||||
}
|
||||
|
||||
// Get actual image size and calculate center
|
||||
cv::Point2f img_center(frame.cols / 2.0f, frame.rows / 2.0f);
|
||||
|
||||
// 使用OpenCV进行形态学处理
|
||||
cv::Mat mask;
|
||||
preprocessor.apply_morphology(raw_mask, mask);
|
||||
|
||||
// 生成彩色图像(仅显示目标颜色)
|
||||
cv::Mat color_only_frame;
|
||||
frame.copyTo(color_only_frame, raw_mask);
|
||||
|
||||
// Initialize tracking center
|
||||
cv::Point2f* tracking_center = nullptr;
|
||||
std::unique_ptr<cv::Point2f> tracking_point = nullptr;
|
||||
|
||||
if (is_tracking) {
|
||||
// Update tracker
|
||||
bool success = tracker->update(frame, tracking_roi);
|
||||
if (success && tracking_roi.area() > 0) {
|
||||
// Calculate center of tracked ROI
|
||||
tracking_point = std::make_unique<cv::Point2f>(
|
||||
tracking_roi.x + tracking_roi.width / 2.0f,
|
||||
tracking_roi.y + tracking_roi.height / 2.0f
|
||||
);
|
||||
tracking_center = tracking_point.get();
|
||||
tracking_frame_count++;
|
||||
|
||||
// If tracking for too long or detection is available, search for armor again
|
||||
if (tracking_frame_count > MAX_TRACKING_FRAMES) {
|
||||
is_tracking = false;
|
||||
tracking_frame_count = 0;
|
||||
}
|
||||
} else {
|
||||
// Tracking failed, return to detection mode
|
||||
is_tracking = false;
|
||||
tracking_frame_count = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Armor plate detection - only when not tracking or need to verify tracking
|
||||
std::vector<LightBar> valid_light_bars;
|
||||
std::vector<ArmorPlate> armor_plates;
|
||||
|
||||
if (!is_tracking || tracking_frame_count % 10 == 0) { // Detect every 10 frames when tracking
|
||||
detector.detect(mask, target_color, valid_light_bars, armor_plates);
|
||||
}
|
||||
|
||||
// Kalman filter tracking (modified part: get target speed)
|
||||
cv::Point2f* detection_center = nullptr;
|
||||
if (!armor_plates.empty()) {
|
||||
detection_center = &(armor_plates[0].center);
|
||||
}
|
||||
|
||||
// Use smart pointer for safer memory management
|
||||
std::unique_ptr<cv::Point2f> predicted_center = nullptr;
|
||||
|
||||
// Priority: detection -> tracking -> Kalman prediction
|
||||
if (detection_center != nullptr) {
|
||||
// Has detection result: update Kalman filter, reset consecutive prediction count
|
||||
kalman_tracker.update(*detection_center);
|
||||
predicted_center = std::make_unique<cv::Point2f>(kalman_tracker.predict());
|
||||
|
||||
// Start tracking if successfully detected
|
||||
if (!is_tracking && !armor_plates.empty()) {
|
||||
cv::Rect2d armor_rect = cv::boundingRect(std::vector<cv::Point2f>{
|
||||
armor_plates[0].corners_2d[0],
|
||||
armor_plates[0].corners_2d[1],
|
||||
armor_plates[0].corners_2d[2],
|
||||
armor_plates[0].corners_2d[3]
|
||||
});
|
||||
// Expand the bounding box slightly for better tracking
|
||||
cv::Rect2d expanded_rect = cv::Rect2d(
|
||||
armor_rect.x - armor_rect.width * 0.1,
|
||||
armor_rect.y - armor_rect.height * 0.1,
|
||||
armor_rect.width * 1.2,
|
||||
armor_rect.height * 1.2
|
||||
);
|
||||
// Ensure the rectangle is within frame bounds
|
||||
expanded_rect = expanded_rect & cv::Rect2d(0, 0, frame.cols, frame.rows);
|
||||
|
||||
tracker = cv::TrackerKCF::create(); // Create new tracker instance
|
||||
tracker->init(frame, expanded_rect);
|
||||
tracking_roi = expanded_rect;
|
||||
is_tracking = true;
|
||||
tracking_frame_count = 0;
|
||||
}
|
||||
|
||||
consecutive_predicts = 0;
|
||||
} else if (is_tracking && tracking_center != nullptr) {
|
||||
// Use tracking result
|
||||
kalman_tracker.update(*tracking_center);
|
||||
predicted_center = std::make_unique<cv::Point2f>(kalman_tracker.predict());
|
||||
consecutive_predicts = 0;
|
||||
} else {
|
||||
// No detection or tracking result: only use Kalman prediction, limit consecutive predictions
|
||||
consecutive_predicts++;
|
||||
if (consecutive_predicts < max_consecutive_predicts) {
|
||||
cv::Point2f temp_pred = kalman_tracker.predict();
|
||||
if (temp_pred.x != 0 || temp_pred.y != 0) { // Check if prediction is valid
|
||||
predicted_center = std::make_unique<cv::Point2f>(temp_pred);
|
||||
}
|
||||
} else {
|
||||
predicted_center = nullptr;
|
||||
target_speed = cv::Point2f(0.0f, 0.0f);
|
||||
}
|
||||
}
|
||||
|
||||
// Determine display center
|
||||
cv::Point2f* display_center = detection_center; // Give priority to detection results
|
||||
if (display_center == nullptr && is_tracking && tracking_center != nullptr) {
|
||||
display_center = tracking_center;
|
||||
}
|
||||
if (display_center == nullptr && predicted_center != nullptr) {
|
||||
display_center = predicted_center.get();
|
||||
}
|
||||
bool is_predicted = (display_center != nullptr) && (detection_center == nullptr && (!is_tracking || tracking_center == nullptr));
|
||||
|
||||
// Calculate ballistic prediction point
|
||||
cv::Point2f* ballistic_point = ballistic_predictor.predict_ballistic_point(
|
||||
predicted_center.get(), img_center, target_speed
|
||||
);
|
||||
|
||||
auto current_time = std::chrono::high_resolution_clock::now();
|
||||
|
||||
// Visualization
|
||||
visualizer.draw_light_bars(frame, valid_light_bars, target_color);
|
||||
if (!armor_plates.empty()) {
|
||||
visualizer.draw_armor_plate(frame, armor_plates[0]);
|
||||
}
|
||||
// Draw tracking rectangle if tracking
|
||||
if (is_tracking) {
|
||||
cv::rectangle(frame, tracking_roi, cv::Scalar(0, 255, 0), 2);
|
||||
}
|
||||
visualizer.draw_offset_text(frame, display_center, target_color, is_predicted);
|
||||
visualizer.draw_ballistic_point(frame, ballistic_point);
|
||||
|
||||
// Output control data to TTL (passing use_ttl to control whether to send)
|
||||
// Now sending on every frame for smoother control
|
||||
output_control_data(display_center, target_color, ttl, img_center, use_ttl);
|
||||
|
||||
// Display windows
|
||||
cv::imshow("Armor Detection", frame);
|
||||
cv::imshow(target_color + " Mask", mask);
|
||||
cv::imshow(target_color + " Only", color_only_frame);
|
||||
|
||||
// Exit on 'q' key press
|
||||
if (cv::waitKey(1) == 'q') {
|
||||
break;
|
||||
}
|
||||
|
||||
frame_counter++;
|
||||
|
||||
// Control max frame rate (100 FPS)
|
||||
auto end_time = std::chrono::high_resolution_clock::now();
|
||||
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - current_time).count();
|
||||
if (elapsed < 10) { // 100 FPS = 10ms per frame
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(10 - elapsed));
|
||||
}
|
||||
|
||||
// Smart pointers automatically handle memory cleanup
|
||||
}
|
||||
}
|
||||
catch (const std::exception& e) {
|
||||
std::cerr << "Error in main loop: " << e.what() << std::endl;
|
||||
}
|
||||
catch (...) {
|
||||
std::cerr << "Unknown error occurred in main loop" << std::endl;
|
||||
}
|
||||
|
||||
// Cleanup
|
||||
try {
|
||||
camera.release();
|
||||
} catch (...) {
|
||||
std::cerr << "Error during camera release" << std::endl;
|
||||
}
|
||||
|
||||
try {
|
||||
cv::destroyAllWindows();
|
||||
} catch (...) {
|
||||
std::cerr << "Error during window destruction" << std::endl;
|
||||
}
|
||||
|
||||
// Only close TTL connection when enabled and initialized
|
||||
if (use_ttl && ttl != nullptr) {
|
||||
try {
|
||||
ttl->close();
|
||||
} catch (...) {
|
||||
std::cerr << "Error during TTL close" << std::endl;
|
||||
}
|
||||
delete ttl;
|
||||
ttl = nullptr;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
144
Catalyst-MDVS2/src/TTLCommunicator.cpp
Normal file
144
Catalyst-MDVS2/src/TTLCommunicator.cpp
Normal file
@@ -0,0 +1,144 @@
|
||||
#include "TTLCommunicator.h"
|
||||
#include <iostream>
|
||||
|
||||
#include <sys/types.h>
|
||||
#include <sys/stat.h>
|
||||
#include <fcntl.h>
|
||||
#include <termios.h>
|
||||
#include <unistd.h>
|
||||
#include <errno.h>
|
||||
#include <string.h>
|
||||
|
||||
TTLCommunicator::TTLCommunicator(const std::string& port, int baudrate)
|
||||
: port_name(port), baudrate(baudrate), connected(false) {
|
||||
serial_fd = -1;
|
||||
}
|
||||
|
||||
TTLCommunicator::~TTLCommunicator() {
|
||||
close();
|
||||
}
|
||||
|
||||
bool TTLCommunicator::connect() {
|
||||
std::cout << "Attempting to connect to TTL device on port: " << port_name << " at baud rate: " << baudrate << std::endl;
|
||||
|
||||
connected = open_serial_port();
|
||||
|
||||
if (connected) {
|
||||
std::cout << "TTL connection established." << std::endl;
|
||||
} else {
|
||||
std::cout << "Warning: Failed to establish TTL connection." << std::endl;
|
||||
}
|
||||
|
||||
return connected;
|
||||
}
|
||||
|
||||
void TTLCommunicator::close() {
|
||||
if (connected) {
|
||||
close_serial_port();
|
||||
connected = false;
|
||||
std::cout << "TTL connection closed." << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
bool TTLCommunicator::send_data(const std::string& data) {
|
||||
if (!connected) {
|
||||
std::cerr << "Error: Cannot send data, TTL not connected." << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (serial_fd != -1) {
|
||||
ssize_t bytes_written = write(serial_fd, data.c_str(), data.length());
|
||||
if (bytes_written == -1) {
|
||||
std::cerr << "Error writing to serial port: " << strerror(errno) << std::endl;
|
||||
return false;
|
||||
} else {
|
||||
std::cout << "Sent " << bytes_written << " bytes: " << data;
|
||||
fsync(serial_fd); // Ensure data is sent
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool TTLCommunicator::open_serial_port() {
|
||||
// Open the serial port
|
||||
serial_fd = open(port_name.c_str(), O_RDWR | O_NOCTTY);
|
||||
if (serial_fd == -1) {
|
||||
std::cerr << "Error opening serial port " << port_name << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
struct termios tty;
|
||||
|
||||
// Get current attributes
|
||||
if (tcgetattr(serial_fd, &tty) != 0) {
|
||||
std::cerr << "Error getting serial attributes" << std::endl;
|
||||
::close(serial_fd);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Set baud rate
|
||||
speed_t baud_rate;
|
||||
switch(baudrate) {
|
||||
case 9600: baud_rate = B9600; break;
|
||||
case 19200: baud_rate = B19200; break;
|
||||
case 38400: baud_rate = B38400; break;
|
||||
case 57600: baud_rate = B57600; break;
|
||||
case 115200: baud_rate = B115200; break;
|
||||
case 230400: baud_rate = B230400; break;
|
||||
case 460800: baud_rate = B460800; break;
|
||||
case 921600: baud_rate = B921600; break;
|
||||
default:
|
||||
std::cerr << "Unsupported baud rate: " << baudrate << std::endl;
|
||||
::close(serial_fd);
|
||||
return false;
|
||||
}
|
||||
|
||||
cfsetispeed(&tty, baud_rate);
|
||||
cfsetospeed(&tty, baud_rate);
|
||||
|
||||
// 8N1: 8 data bits, no parity, 1 stop bit
|
||||
tty.c_cflag &= ~PARENB; // No parity
|
||||
tty.c_cflag &= ~CSTOPB; // 1 stop bit
|
||||
tty.c_cflag &= ~CSIZE; // Clear data bits
|
||||
tty.c_cflag |= CS8; // 8 data bits
|
||||
tty.c_cflag &= ~CRTSCTS; // No flow control
|
||||
tty.c_cflag |= CREAD | CLOCAL; // Enable reading, ignore control lines
|
||||
|
||||
// Non-canonical mode
|
||||
tty.c_lflag &= ~ICANON; // Non-canonical mode
|
||||
tty.c_lflag &= ~ECHO; // No echo
|
||||
tty.c_lflag &= ~ECHOE; // No erasure
|
||||
tty.c_lflag &= ~ISIG; // No signal handling
|
||||
|
||||
// No software flow control
|
||||
tty.c_iflag &= ~(IXON | IXOFF | IXANY);
|
||||
|
||||
// No output processing
|
||||
tty.c_oflag &= ~OPOST;
|
||||
|
||||
// Timeouts
|
||||
tty.c_cc[VMIN] = 0; // Non-blocking read
|
||||
tty.c_cc[VTIME] = 5; // 0.5 second timeout
|
||||
|
||||
// Apply settings
|
||||
if (tcsetattr(serial_fd, TCSANOW, &tty) != 0) {
|
||||
std::cerr << "Error setting serial attributes" << std::endl;
|
||||
::close(serial_fd);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Flush port
|
||||
tcflush(serial_fd, TCIOFLUSH);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void TTLCommunicator::close_serial_port() {
|
||||
if (serial_fd != -1) {
|
||||
::close(serial_fd);
|
||||
serial_fd = -1;
|
||||
}
|
||||
connected = false;
|
||||
}
|
||||
2
Catalyst-MDVS2/src/TTLCommunicator.cpp:Zone.Identifier
Normal file
2
Catalyst-MDVS2/src/TTLCommunicator.cpp:Zone.Identifier
Normal file
@@ -0,0 +1,2 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
93
Catalyst-MDVS2/src/Visualizer.cpp
Normal file
93
Catalyst-MDVS2/src/Visualizer.cpp
Normal file
@@ -0,0 +1,93 @@
|
||||
#include "Visualizer.h"
|
||||
#include <sstream>
|
||||
|
||||
Visualizer::Visualizer() {
|
||||
// Constructor implementation
|
||||
}
|
||||
|
||||
Visualizer::~Visualizer() {
|
||||
// Destructor implementation
|
||||
}
|
||||
|
||||
cv::Mat& Visualizer::draw_light_bars(cv::Mat& frame, const std::vector<LightBar>& light_bars, const std::string& target_color) {
|
||||
cv::Scalar color = (target_color == "red") ? cv::Scalar(0, 0, 255) : cv::Scalar(255, 0, 0); // Red or Blue in BGR
|
||||
|
||||
for (const auto& light_bar : light_bars) {
|
||||
// Draw rotated rectangle for each light bar
|
||||
for (size_t i = 0; i < light_bar.box.size(); i++) {
|
||||
cv::Point2f pt1 = light_bar.box[i];
|
||||
cv::Point2f pt2 = light_bar.box[(i + 1) % light_bar.box.size()];
|
||||
cv::line(frame, pt1, pt2, color, 2);
|
||||
}
|
||||
}
|
||||
|
||||
return frame;
|
||||
}
|
||||
|
||||
cv::Mat& Visualizer::draw_armor_plate(cv::Mat& frame, const ArmorPlate& armor_plate) {
|
||||
cv::circle(frame, armor_plate.center, 10, cv::Scalar(0, 255, 0), 2); // Green circle around armor center
|
||||
|
||||
// Draw confidence text
|
||||
std::stringstream ss;
|
||||
ss << "Conf: " << std::fixed << std::setprecision(2) << armor_plate.confidence;
|
||||
cv::putText(frame, ss.str(), cv::Point(armor_plate.center.x + 15, armor_plate.center.y - 15),
|
||||
cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 255, 0), 1);
|
||||
|
||||
return frame;
|
||||
}
|
||||
|
||||
cv::Mat& Visualizer::draw_offset_text(cv::Mat& frame, const cv::Point2f* display_center, const std::string& /*target_color*/, bool is_predicted) {
|
||||
if (display_center == nullptr) {
|
||||
return frame;
|
||||
}
|
||||
|
||||
cv::Point2f img_center(frame.cols / 2.0f, frame.rows / 2.0f);
|
||||
int offset_x = static_cast<int>(display_center->x - img_center.x);
|
||||
int offset_y = static_cast<int>(img_center.y - display_center->y);
|
||||
|
||||
std::stringstream ss;
|
||||
ss << "Offset: (" << offset_x << ", " << offset_y << ")";
|
||||
|
||||
// Use different color based on whether it's predicted or actual
|
||||
cv::Scalar color = is_predicted ? cv::Scalar(0, 255, 255) : cv::Scalar(0, 255, 0); // Yellow for predicted, Green for actual
|
||||
cv::putText(frame, ss.str(), cv::Point(20, 30), cv::FONT_HERSHEY_SIMPLEX, 0.7, color, 2);
|
||||
|
||||
return frame;
|
||||
}
|
||||
|
||||
cv::Mat& Visualizer::draw_crosshair(cv::Mat& frame, const cv::Point2f& center, const cv::Scalar& color, int size) {
|
||||
// Draw horizontal line
|
||||
cv::line(frame,
|
||||
cv::Point(static_cast<int>(center.x - size), static_cast<int>(center.y)),
|
||||
cv::Point(static_cast<int>(center.x + size), static_cast<int>(center.y)),
|
||||
color, 2);
|
||||
|
||||
// Draw vertical line
|
||||
cv::line(frame,
|
||||
cv::Point(static_cast<int>(center.x), static_cast<int>(center.y - size)),
|
||||
cv::Point(static_cast<int>(center.x), static_cast<int>(center.y + size)),
|
||||
color, 2);
|
||||
|
||||
return frame;
|
||||
}
|
||||
|
||||
cv::Mat& Visualizer::draw_ballistic_point(cv::Mat& frame, const cv::Point2f* ballistic_point) {
|
||||
if (ballistic_point != nullptr) {
|
||||
// Draw a red crosshair at the ballistic prediction point
|
||||
cv::circle(frame, *ballistic_point, 8, cv::Scalar(0, 0, 255), 2); // Red circle
|
||||
cv::line(frame,
|
||||
cv::Point(static_cast<int>(ballistic_point->x - 10), static_cast<int>(ballistic_point->y)),
|
||||
cv::Point(static_cast<int>(ballistic_point->x + 10), static_cast<int>(ballistic_point->y)),
|
||||
cv::Scalar(0, 0, 255), 2); // Red horizontal line
|
||||
cv::line(frame,
|
||||
cv::Point(static_cast<int>(ballistic_point->x), static_cast<int>(ballistic_point->y - 10)),
|
||||
cv::Point(static_cast<int>(ballistic_point->x), static_cast<int>(ballistic_point->y + 10)),
|
||||
cv::Scalar(0, 0, 255), 2); // Red vertical line
|
||||
|
||||
// Label as ballistic point
|
||||
cv::putText(frame, "BP", cv::Point(static_cast<int>(ballistic_point->x + 15), static_cast<int>(ballistic_point->y - 15)),
|
||||
cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 255), 1);
|
||||
}
|
||||
|
||||
return frame;
|
||||
}
|
||||
2
Catalyst-MDVS2/src/Visualizer.cpp:Zone.Identifier
Normal file
2
Catalyst-MDVS2/src/Visualizer.cpp:Zone.Identifier
Normal file
@@ -0,0 +1,2 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
Reference in New Issue
Block a user