├── .gitignore ├── CMakeLists.txt ├── LICENSE ├── README.md ├── assets └── yolofire.gif ├── include ├── datatype.h └── manager.hpp ├── src ├── main.cpp └── manager.cpp └── yolo ├── include ├── calibrator.h ├── common.hpp ├── cuda_utils.h ├── logging.h ├── macros.h ├── utils.h ├── yololayer.cu ├── yololayer.h └── yolov5_lib.h └── src ├── calibrator.cpp └── yolov5_lib.cpp /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Compiled Object files 5 | *.slo 6 | *.lo 7 | *.o 8 | *.obj 9 | 10 | # Precompiled Headers 11 | *.gch 12 | *.pch 13 | 14 | # Compiled Dynamic libraries 15 | *.so 16 | *.dylib 17 | *.dll 18 | 19 | # Fortran module files 20 | *.mod 21 | *.smod 22 | 23 | # Compiled Static libraries 24 | *.lai 25 | *.la 26 | *.a 27 | *.lib 28 | 29 | # Executables 30 | *.exe 31 | *.out 32 | *.app 33 | 34 | *.avi 35 | *.mp4 36 | build/ 37 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 2.6) 2 | 3 | project(yolofire) 4 | list(APPEND CUDA_NVCC_FLAGS "-std=c++11") 5 | set(CMAKE_CXX_FLAGS "-std=c++0x") 6 | find_package(OpenCV REQUIRED) 7 | add_definitions(-std=c++11) 8 | add_definitions(-DAPI_EXPORTS) 9 | option(CUDA_USE_STATIC_CUDA_RUNTIME OFF) 10 | set(CMAKE_CXX_STANDARD 11) 11 | set(CMAKE_BUILD_TYPE Release) 12 | 13 | find_package(CUDA REQUIRED) 14 | set(CUDA_NVCC_PLAGS ${CUDA_NVCC_PLAGS};-std=c++11;-g;-G;-gencode;arch=compute_53;code=sm_53) 15 | 16 | 17 | find_package(OpenCV REQUIRED core imgproc highgui) 18 | 19 | if(WIN32) 20 | enable_language(CUDA) 21 | endif(WIN32) 22 | 23 | # include and link dirs of cuda and tensorrt, you need adapt them if yours are different 24 | # cuda 25 | include_directories(/usr/local/cuda/include) 26 | link_directories(/usr/local/cuda/lib64) 27 | # tensorrt 28 | include_directories(/usr/include/aarch64-linux-gnu/) 29 | link_directories(/usr/lib/aarch64-linux-gnu/) 30 | 31 | include_directories( 32 | ${CUDA_INCLUDE_DIRS} 33 | ${OpenCV_INCLUDE_DIRS} 34 | 35 | ) 36 | 37 | # ===== yolo ===== 38 | include_directories(${PROJECT_SOURCE_DIR}/yolo/include) 39 | aux_source_directory(${PROJECT_SOURCE_DIR}/yolo/src YOLO_SRC_DIR) 40 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wall -Ofast -Wfatal-errors -D_MWAITXINTRIN_H_INCLUDED") 41 | 42 | cuda_add_library(yolov5_trt SHARED ${PROJECT_SOURCE_DIR}/yolo/include/yololayer.cu ${PROJECT_SOURCE_DIR}/yolo/src/yolov5_lib.cpp) 43 | target_link_libraries(yolov5_trt nvinfer cudart) 44 | 45 | 46 | # ===== main ===== 47 | aux_source_directory(${PROJECT_SOURCE_DIR}/src M_SRC_DIR) 48 | include_directories(${PROJECT_SOURCE_DIR}/include) 49 | 50 | add_executable(yolofire ${M_SRC_DIR}) 51 | 52 | target_link_libraries(yolofire nvinfer cudart yolov5_trt ${OpenCV_LIBS}) 53 | 54 | if(UNIX) 55 | add_definitions(-O2 -pthread) 56 | endif(UNIX) 57 | set(CMAKE_CXX_FLAGS "-std=c++0x") 58 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # A C++ implementation of Yolov5 to detect fire or smoke in the wild in Jetson Xavier nx and Jetson nano 2 | This repository uses yolov5 to detect fire and smoke in the wild which can run in Jetson Xavier nx and Jetson nano. 3 | In Jetson Xavier Nx, it can achieve 33 FPS. 4 | 5 | 6 | 7 | You can see video play in [BILIBILI](https://www.bilibili.com/video/BV1VT4y1975b), or [YOUTUBE](https://www.youtube.com/watch?v=5Ysqc5bWhBM). 8 | 9 | If you want to try to train your own model, you can see [yolov5-fire-smoke-detect-python](https://github.com/RichardoMrMu/yolov5-fire-smoke-detect-python). Follow the readme to get your own model. 10 | 11 | ## Requirement 12 | 1. Jetson nano or Jetson Xavier nx 13 | 2. Jetpack 4.5.1 14 | 3. python3 with default(jetson nano or jetson xavier nx has default python3 with tensorrt 7.1.3.0 ) 15 | 4. tensorrt 7.1.3.0 16 | 5. torch 1.8.0 17 | 6. torchvision 0.9.0 18 | 7. torch2trt 0.3.0 19 | 8. onnx 1.4.1 20 | 9. opencv-python 4.5.3.56 21 | 10. protobuf 3.17.3 22 | 11. scipy 1.5.4 23 | 24 | 25 | if you have problem in this project, you can see this [artical](https://blog.csdn.net/weixin_42264234/article/details/121214079). 26 | 27 | ## Achieve and Experiment 28 | - Int8. 29 | - yolov5-s 30 | - yolov5-m 31 | 32 | 33 | ## Comming soon 34 | - [ ] Faster and use less memory. 35 | 36 | ## Speed 37 | 38 | Whole process time from read image to finish process (include every img preprocess and postprocess). And all results can get in Jetson Xavier nx. For python model and code, you can find them in this [project yolov5-fire-smoke-detect-python](https://github.com/RichardoMrMu/yolov5-fire-smoke-detect-python) 39 | | Backbone | before TensorRT |TensortRT(detection)| FPS(detection) | 40 | | :--------------: | :--------------: | :--------------: |:--------------:| 41 | | Yolov5s-640-float16 | 100ms |60-70ms | 14 ~ 18 | 42 | | Yolov5m-640-float16 | 120ms |70-75ms | 13 ~ 14 | 43 | | Yolov5s-640-int8 | |30-40ms | 25 ~ 33 | 44 | | Yolov5m-640-int8 | |50-60ms | 16 ~ 20 | 45 | 46 | ------ 47 | 48 | ## Build and Run 49 | 50 | ```shell 51 | 52 | git clone https://github.com/RichardoMrMu/yolov5-fire-smoke-detect.git 53 | cd yolov5-fire-smoke-detect 54 | mkdir build 55 | cmake .. 56 | make 57 | ``` 58 | if you meet some errors in cmake and make, please see this [artical](https://blog.csdn.net/weixin_42264234/article/details/121214079) or see Attention. 59 | 60 | ## Model 61 | You need yolov5 model, for detection, generating from [tensorrtx](https://github.com/wang-xinyu/tensorrtx). 62 | 63 | ### Generate yolov5 model 64 | For yolov5 detection model, I choose yolov5s, and choose `yolov5s.pt->yolov5s.wts->yolov5s.engine` 65 | Note that, used models can get from [yolov5](https://github.com/ultralytics/yolov5) and if you need to use your own model, you can follow the `Run Your Custom Model`. 66 | You can also see [tensorrtx official readme](https://github.com/wang-xinyu/tensorrtx/tree/master/yolov5) 67 | 68 | 1. Get yolov5 repository 69 | 70 | Note that, here uses the official pertained model.And I use yolov5-5, v5.0. So if you train your own model, please be sure your yolov5 code is v5.0. 71 | 72 | ```shell 73 | git clone -b v5.0 https://github.com/ultralytics/yolov5.git 74 | cd yolov5 75 | mkdir weights 76 | cd weights 77 | // download https://github.com/ultralytics/yolov5/releases/download/v5.0/yolov5s.pt 78 | wget https://github.com/ultralytics/yolov5/releases/download/v5.0/yolov5s.pt 79 | 80 | ``` 81 | 82 | 2. Get tensorrtx. 83 | 84 | ```shell 85 | git clone https://github.com/wang-xinyu/tensorrtx 86 | ``` 87 | 88 | 3. Get xxx.wst model 89 | 90 | ```shell 91 | cp tensorrtx/gen_wts.py yolov5/ 92 | cd yolov5 93 | python3 gen_wts.py -w ./weights/yolov5s.pt -o ./weights/yolov5s.wts 94 | // a file 'yolov5s.wts' will be generated. 95 | ``` 96 | You can get yolov5s.wts model in `yolov5/weights/` 97 | 98 | 4. Build tensorrtx/yolov5 and get tensorrt engine 99 | 100 | ```shell 101 | cd tensorrtx/yolov5 102 | // update CLASS_NUM in yololayer.h if your model is trained on custom dataset 103 | mkdir build 104 | cd build 105 | cp {ultralytics}/yolov5/yolov5s.wts {tensorrtx}/yolov5/build 106 | cmake .. 107 | make 108 | // yolov5s 109 | sudo ./yolov5 -s yolov5s.wts yolov5s.engine s 110 | // test your engine file 111 | sudo ./yolov5 -d yolov5s.engine ../samples 112 | ``` 113 | Then you get the yolov5s.engine, and you can put `yolov5s.engine` in My project. For example 114 | 115 | ```shell 116 | cd {yolov5-fire-smoke-detect} 117 | mkdir resources 118 | cp {tensorrtx}/yolov5/build/yolov5s.engine {yolov5-fire-smoke-detect}/resources 119 | ``` 120 | 121 | After all 4 step, you can get the yolov5s.engine. 122 | 123 | You may face some problems in getting yolov5s.engine, you can upload your issue in github or [csdn artical](https://blog.csdn.net/weixin_42264234/article/details/121214079). 124 |
125 | Different versions of yolov5 126 | 127 | Currently, tensorrt support yolov5 v1.0(yolov5s only), v2.0, v3.0, v3.1, v4.0 and v5.0. 128 | 129 | - For yolov5 v5.0, download .pt from [yolov5 release v5.0](https://github.com/ultralytics/yolov5/releases/tag/v5.0), `git clone -b v5.0 https://github.com/ultralytics/yolov5.git` and `git clone https://github.com/wang-xinyu/tensorrtx.git`, then follow how-to-run in current page. 130 | - For yolov5 v4.0, download .pt from [yolov5 release v4.0](https://github.com/ultralytics/yolov5/releases/tag/v4.0), `git clone -b v4.0 https://github.com/ultralytics/yolov5.git` and `git clone -b yolov5-v4.0 https://github.com/wang-xinyu/tensorrtx.git`, then follow how-to-run in [tensorrtx/yolov5-v4.0](https://github.com/wang-xinyu/tensorrtx/tree/yolov5-v4.0/yolov5). 131 | - For yolov5 v3.1, download .pt from [yolov5 release v3.1](https://github.com/ultralytics/yolov5/releases/tag/v3.1), `git clone -b v3.1 https://github.com/ultralytics/yolov5.git` and `git clone -b yolov5-v3.1 https://github.com/wang-xinyu/tensorrtx.git`, then follow how-to-run in [tensorrtx/yolov5-v3.1](https://github.com/wang-xinyu/tensorrtx/tree/yolov5-v3.1/yolov5). 132 | - For yolov5 v3.0, download .pt from [yolov5 release v3.0](https://github.com/ultralytics/yolov5/releases/tag/v3.0), `git clone -b v3.0 https://github.com/ultralytics/yolov5.git` and `git clone -b yolov5-v3.0 https://github.com/wang-xinyu/tensorrtx.git`, then follow how-to-run in [tensorrtx/yolov5-v3.0](https://github.com/wang-xinyu/tensorrtx/tree/yolov5-v3.0/yolov5). 133 | - For yolov5 v2.0, download .pt from [yolov5 release v2.0](https://github.com/ultralytics/yolov5/releases/tag/v2.0), `git clone -b v2.0 https://github.com/ultralytics/yolov5.git` and `git clone -b yolov5-v2.0 https://github.com/wang-xinyu/tensorrtx.git`, then follow how-to-run in [tensorrtx/yolov5-v2.0](https://github.com/wang-xinyu/tensorrtx/tree/yolov5-v2.0/yolov5). 134 | - For yolov5 v1.0, download .pt from [yolov5 release v1.0](https://github.com/ultralytics/yolov5/releases/tag/v1.0), `git clone -b v1.0 https://github.com/ultralytics/yolov5.git` and `git clone -b yolov5-v1.0 https://github.com/wang-xinyu/tensorrtx.git`, then follow how-to-run in [tensorrtx/yolov5-v1.0](https://github.com/wang-xinyu/tensorrtx/tree/yolov5-v1.0/yolov5). 135 |
136 | 137 |
138 | 139 | Config 140 | 141 | - Choose the model s/m/l/x/s6/m6/l6/x6 from command line arguments. 142 | - Input shape defined in yololayer.h 143 | - Number of classes defined in yololayer.h, **DO NOT FORGET TO ADAPT THIS, If using your own model** 144 | - INT8/FP16/FP32 can be selected by the macro in yolov5.cpp, **INT8 need more steps, pls follow `How to Run` first and then go the `INT8 Quantization` below** 145 | - GPU id can be selected by the macro in yolov5.cpp 146 | - NMS thresh in yolov5.cpp 147 | - BBox confidence thresh in yolov5.cpp 148 | - Batch size in yolov5.cpp 149 |
150 | 151 | ## Run Your Custom Model 152 | You may need train your own model and transfer your trained-model to tensorRT. So you can follow the following steps. 153 | 1. Train Custom Model 154 | You can follow the [official wiki](https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data 155 | ) to train your own model on your dataset. For example, I choose yolov5-s to train my model. 156 | 2. Transfer Custom Model 157 | Just like [tensorRT official guideline](https://github.com/wang-xinyu/tensorrtx/edit/master/yolov5/).When your follow ` Generate yolov5 model` to get yolov5 and tensorrt rep, next step is to transfer your pytorch model to tensorrt. 158 | Before this, you need to change yololayer.h file 20,21 and 22 line(CLASS_NUM,INPUT_H,INPUT_W) to your own parameters. 159 | 160 | ```shell 161 | // before 162 | static constexpr int CLASS_NUM = 80; // 20 163 | static constexpr int INPUT_H = 640; // 21 yolov5's input height and width must be divisible by 32. 164 | static constexpr int INPUT_W = 640; // 22 165 | 166 | // after 167 | // if your model is 2 classfication and image size is 416*416 168 | static constexpr int CLASS_NUM = 2; // 20 169 | static constexpr int INPUT_H = 416; // 21 yolov5's input height and width must be divisible by 32. 170 | static constexpr int INPUT_W = 416; // 22 171 | ``` 172 | 173 | ```shell 174 | cd {tensorrtx}/yolov5/ 175 | // update CLASS_NUM in yololayer.h if your model is trained on custom dataset 176 | 177 | mkdir build 178 | cd build 179 | cp {ultralytics}/yolov5/yolov5s.wts {tensorrtx}/yolov5/build 180 | cmake .. 181 | make 182 | sudo ./yolov5 -s [.wts] [.engine] [s/m/l/x/s6/m6/l6/x6 or c/c6 gd gw] // serialize model to plan file 183 | sudo ./yolov5 -d [.engine] [image folder] // deserialize and run inference, the images in [image folder] will be processed. 184 | // For example yolov5s 185 | sudo ./yolov5 -s yolov5s.wts yolov5s.engine s 186 | sudo ./yolov5 -d yolov5s.engine ../samples 187 | // For example Custom model with depth_multiple=0.17, width_multiple=0.25 in yolov5.yaml 188 | sudo ./yolov5 -s yolov5_custom.wts yolov5.engine c 0.17 0.25 189 | sudo ./yolov5 -d yolov5.engine ../samples 190 | ``` 191 | 192 | In this way, you can get your own tensorrt yolov5 model. Enjoy it! 193 | 194 | ## INT8 Quantization 195 | It has some diffirence between float16 tensorrt engine file and int8. Just like [tensorrtx readme](https://github.com/wang-xinyu/tensorrtx/tree/master/yolov5), Int8 engine file needs calibration images. 196 | 197 | For official yolov5 model , you need to downlowd `coco_calid.zip` from this [google drive url ](https://drive.google.com/drive/folders/1s7jE9DtOngZMzJC1uL307J2MiaGwdRSI) or [BAIDUYUN](https://pan.baidu.com/s/1GOm_-JobpyLMAqZWCDUhKg) --- `a9wh` . And unzip to `{project}/build/`. 198 | 199 | Then change `yolov5.cpp`'s 10 line from `USE_FLOAT16` to `USE_INT8`.And run this : 200 | 201 | ```shell 202 | cmake .. 203 | make 204 | // yolov5s 205 | sudo ./yolov5 -s yolov5s.wts yolov5s-int8.engine s 206 | // testyour engine file 207 | sudo ./yolov5 -d yolov5s-int8.engine ../samples 208 | ``` 209 | -------------------------------------------------------------------------------- /assets/yolofire.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RichardoMrMu/yolov5-fire-smoke-detect/238cc65aa775952962e178c302b0992c4d999edf/assets/yolofire.gif -------------------------------------------------------------------------------- /include/datatype.h: -------------------------------------------------------------------------------- 1 | #ifndef DATATYPE_H 2 | #define DATATYPE_H 3 | 4 | typedef struct DetectBox { 5 | DetectBox(float x1=0, float y1=0, float x2=0, float y2=0, 6 | float confidence=0, float classID=-1, float trackID=-1) { 7 | this->x1 = x1; 8 | this->y1 = y1; 9 | this->x2 = x2; 10 | this->y2 = y2; 11 | this->confidence = confidence; 12 | this->classID = classID; 13 | this->trackID = trackID; 14 | } 15 | float x1, y1, x2, y2; 16 | float confidence; 17 | float classID; 18 | float trackID; 19 | } DetectBox; 20 | 21 | #endif // DATATYPE_H 22 | 23 | #ifndef DEEPSORTDATATYPE_H 24 | #define DEEPSORTDATATYPE_H 25 | 26 | #include 27 | #include 28 | #include 29 | #include 30 | typedef struct CLSCONF { 31 | CLSCONF() { 32 | this->cls = -1; 33 | this->conf = -1; 34 | } 35 | CLSCONF(int cls, float conf) { 36 | this->cls = cls; 37 | this->conf = conf; 38 | } 39 | int cls; 40 | float conf; 41 | } CLSCONF; 42 | 43 | typedef Eigen::Matrix DETECTBOX; 44 | typedef Eigen::Matrix DETECTBOXSS; 45 | typedef Eigen::Matrix FEATURE; 46 | typedef Eigen::Matrix FEATURESS; 47 | //typedef std::vector FEATURESS; 48 | 49 | //Kalmanfilter 50 | //typedef Eigen::Matrix KAL_FILTER; 51 | typedef Eigen::Matrix KAL_MEAN; 52 | typedef Eigen::Matrix KAL_COVA; 53 | typedef Eigen::Matrix KAL_HMEAN; 54 | typedef Eigen::Matrix KAL_HCOVA; 55 | using KAL_DATA = std::pair; 56 | using KAL_HDATA = std::pair; 57 | 58 | //main 59 | using RESULT_DATA = std::pair; 60 | 61 | //tracker: 62 | using TRACKER_DATA = std::pair; 63 | using MATCH_DATA = std::pair; 64 | typedef struct t{ 65 | std::vector matches; 66 | std::vector unmatched_tracks; 67 | std::vector unmatched_detections; 68 | }TRACHER_MATCHD; 69 | 70 | //linear_assignment: 71 | typedef Eigen::Matrix DYNAMICM; 72 | 73 | #endif //DEEPSORTDATATYPE_H -------------------------------------------------------------------------------- /include/manager.hpp: -------------------------------------------------------------------------------- 1 | #ifndef _MANAGER_H 2 | #define _MANAGER_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include "logging.h" 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include "time.h" 14 | 15 | #include 16 | #include 17 | #include "yolov5_lib.h" 18 | 19 | 20 | using std::vector; 21 | using namespace cv; 22 | //static Logger gLogger; 23 | 24 | class Trtyolosort{ 25 | public: 26 | // init 27 | Trtyolosort(char *yolo_engine_path); 28 | // detect and show 29 | int TrtDetect(cv::Mat &frame,float &conf_thresh,std::vector &det); 30 | void showDetection(cv::Mat& img, std::vector& boxes); 31 | 32 | private: 33 | char* yolo_engine_path_ = NULL; 34 | void *trt_engine = NULL; 35 | // deepsort parms 36 | std::vector t; 37 | //std::vector det; 38 | // save video 39 | cv::VideoWriter outputVideo; 40 | 41 | }; 42 | #endif // _MANAGER_H 43 | 44 | -------------------------------------------------------------------------------- /src/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "manager.hpp" 3 | #include "opencv2/core/core.hpp" 4 | #include "opencv2/opencv.hpp" 5 | #include "opencv2/videoio/videoio.hpp" 6 | #include "opencv2/highgui/highgui.hpp" 7 | #include "opencv2/video.hpp" 8 | #include "opencv2/imgproc/imgproc.hpp" 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | using namespace cv; 15 | using namespace std; 16 | 17 | 18 | 19 | int main(){ 20 | bool is_first = true; 21 | char* yolo_engine = "/home/tthd/workspace/project/yolofiresmoke-simple/resources/firesmoke-s.engine"; 22 | float conf_thre = 0.3; 23 | Trtyolosort yosort(yolo_engine); 24 | VideoCapture capture; 25 | cv::Mat frame; 26 | frame = capture.open("/home/tthd/workspace/project/yolofiresmoke-simple/resources/141798581-1-192.mp4"); 27 | if (!capture.isOpened()){ 28 | std::cout<<"can not open"< det; 33 | auto start_draw_time = std::chrono::system_clock::now(); 34 | 35 | clock_t start_draw,end_draw; 36 | start_draw = clock(); 37 | int i = 0; 38 | 39 | while(capture.read(frame)){ 40 | if (i%1==0){ 41 | //std::cout<<"origin img size:"<(end - start).count(); 47 | std::cout << "delay_infer:" << delay_infer << "ms" << std::endl; 48 | } 49 | i++; 50 | } 51 | capture.release(); 52 | return 0; 53 | 54 | } 55 | -------------------------------------------------------------------------------- /src/manager.cpp: -------------------------------------------------------------------------------- 1 | #include "manager.hpp" 2 | #include "string" 3 | using std::vector; 4 | using namespace cv; 5 | static Logger gLogger; 6 | 7 | Trtyolosort::Trtyolosort(char *yolo_engine_path){ 8 | yolo_engine_path_ = yolo_engine_path; 9 | trt_engine = yolov5_trt_create(yolo_engine_path_); 10 | printf("create yolov5-trt , instance = %p\n", trt_engine); 11 | std::string videopath = "saved.avi"; 12 | int codec = cv::VideoWriter::fourcc('M', 'J', 'P', 'G'); 13 | outputVideo.open(videopath,codec,25.0,cv::Size(1024, 576),true); 14 | } 15 | 16 | void Trtyolosort::showDetection(cv::Mat& img, std::vector& boxes) { 17 | cv::Mat temp = img.clone(); 18 | for (auto box : boxes) { 19 | cv::Point lt(box.x1, box.y1); 20 | cv::Point br(box.x2, box.y2); 21 | cv::rectangle(temp, lt, br, cv::Scalar(255, 0, 0), 1); 22 | std::string lbl; 23 | 24 | if (((int)box.classID) == 0) lbl = cv::format("%s","fire"); 25 | else lbl = cv::format("%s","smoke"); 26 | cv::putText(temp, lbl, lt, cv::FONT_HERSHEY_COMPLEX, 0.5, cv::Scalar(0,255,0)); 27 | } 28 | //cv::imshow("img", temp); 29 | cv::resize(temp, temp, cv::Size(1024, 576), 0, 0); 30 | outputVideo.write(temp); 31 | cv::waitKey(1); 32 | } 33 | 34 | int Trtyolosort::TrtDetect(cv::Mat &frame,float &conf_thresh,std::vector &det){ 35 | // yolo detect 36 | auto ret = yolov5_trt_detect(trt_engine, frame, conf_thresh,det); 37 | showDetection(frame,det); 38 | return 1 ; 39 | 40 | } 41 | -------------------------------------------------------------------------------- /yolo/include/calibrator.h: -------------------------------------------------------------------------------- 1 | #ifndef ENTROPY_CALIBRATOR_H 2 | #define ENTROPY_CALIBRATOR_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include "macros.h" 8 | 9 | //! \class Int8EntropyCalibrator2 10 | //! 11 | //! \brief Implements Entropy calibrator 2. 12 | //! CalibrationAlgoType is kENTROPY_CALIBRATION_2. 13 | //! 14 | class Int8EntropyCalibrator2 : public nvinfer1::IInt8EntropyCalibrator2 15 | { 16 | public: 17 | Int8EntropyCalibrator2(int batchsize, int input_w, int input_h, const char* img_dir, const char* calib_table_name, const char* input_blob_name, bool read_cache = true); 18 | 19 | virtual ~Int8EntropyCalibrator2(); 20 | int getBatchSize() const TRT_NOEXCEPT override; 21 | bool getBatch(void* bindings[], const char* names[], int nbBindings) TRT_NOEXCEPT override; 22 | const void* readCalibrationCache(size_t& length) TRT_NOEXCEPT override; 23 | void writeCalibrationCache(const void* cache, size_t length) TRT_NOEXCEPT override; 24 | 25 | private: 26 | int batchsize_; 27 | int input_w_; 28 | int input_h_; 29 | int img_idx_; 30 | std::string img_dir_; 31 | std::vector img_files_; 32 | size_t input_count_; 33 | std::string calib_table_name_; 34 | const char* input_blob_name_; 35 | bool read_cache_; 36 | void* device_input_; 37 | std::vector calib_cache_; 38 | }; 39 | 40 | #endif // ENTROPY_CALIBRATOR_H 41 | -------------------------------------------------------------------------------- /yolo/include/common.hpp: -------------------------------------------------------------------------------- 1 | #ifndef YOLOV5_COMMON_H_ 2 | #define YOLOV5_COMMON_H_ 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include "NvInfer.h" 10 | #include "yololayer.h" 11 | 12 | using namespace nvinfer1; 13 | 14 | cv::Rect get_rect(cv::Mat& img, float bbox[4]) { 15 | int l, r, t, b; 16 | float r_w = Yolo::INPUT_W / (img.cols * 1.0); 17 | float r_h = Yolo::INPUT_H / (img.rows * 1.0); 18 | if (r_h > r_w) { 19 | l = bbox[0] - bbox[2] / 2.f; 20 | r = bbox[0] + bbox[2] / 2.f; 21 | t = bbox[1] - bbox[3] / 2.f - (Yolo::INPUT_H - r_w * img.rows) / 2; 22 | b = bbox[1] + bbox[3] / 2.f - (Yolo::INPUT_H - r_w * img.rows) / 2; 23 | l = l / r_w; 24 | r = r / r_w; 25 | t = t / r_w; 26 | b = b / r_w; 27 | } else { 28 | l = bbox[0] - bbox[2] / 2.f - (Yolo::INPUT_W - r_h * img.cols) / 2; 29 | r = bbox[0] + bbox[2] / 2.f - (Yolo::INPUT_W - r_h * img.cols) / 2; 30 | t = bbox[1] - bbox[3] / 2.f; 31 | b = bbox[1] + bbox[3] / 2.f; 32 | l = l / r_h; 33 | r = r / r_h; 34 | t = t / r_h; 35 | b = b / r_h; 36 | } 37 | return cv::Rect(l, t, r - l, b - t); 38 | } 39 | 40 | float iou(float lbox[4], float rbox[4]) { 41 | float interBox[] = { 42 | (std::max)(lbox[0] - lbox[2] / 2.f , rbox[0] - rbox[2] / 2.f), //left 43 | (std::min)(lbox[0] + lbox[2] / 2.f , rbox[0] + rbox[2] / 2.f), //right 44 | (std::max)(lbox[1] - lbox[3] / 2.f , rbox[1] - rbox[3] / 2.f), //top 45 | (std::min)(lbox[1] + lbox[3] / 2.f , rbox[1] + rbox[3] / 2.f), //bottom 46 | }; 47 | 48 | if (interBox[2] > interBox[3] || interBox[0] > interBox[1]) 49 | return 0.0f; 50 | 51 | float interBoxS = (interBox[1] - interBox[0])*(interBox[3] - interBox[2]); 52 | return interBoxS / (lbox[2] * lbox[3] + rbox[2] * rbox[3] - interBoxS); 53 | } 54 | 55 | bool cmp(const Yolo::Detection& a, const Yolo::Detection& b) { 56 | return a.conf > b.conf; 57 | } 58 | 59 | void nms(std::vector& res, float *output, float conf_thresh, float nms_thresh = 0.5) { 60 | int det_size = sizeof(Yolo::Detection) / sizeof(float); 61 | std::map> m; 62 | for (int i = 0; i < output[0] && i < Yolo::MAX_OUTPUT_BBOX_COUNT; i++) { 63 | if (output[1 + det_size * i + 4] <= conf_thresh) continue; 64 | Yolo::Detection det; 65 | memcpy(&det, &output[1 + det_size * i], det_size * sizeof(float)); 66 | if (m.count(det.class_id) == 0) m.emplace(det.class_id, std::vector()); 67 | m[det.class_id].push_back(det); 68 | } 69 | for (auto it = m.begin(); it != m.end(); it++) { 70 | //std::cout << it->second[0].class_id << " --- " << std::endl; 71 | auto& dets = it->second; 72 | std::sort(dets.begin(), dets.end(), cmp); 73 | for (size_t m = 0; m < dets.size(); ++m) { 74 | auto& item = dets[m]; 75 | res.push_back(item); 76 | for (size_t n = m + 1; n < dets.size(); ++n) { 77 | if (iou(item.bbox, dets[n].bbox) > nms_thresh) { 78 | dets.erase(dets.begin() + n); 79 | --n; 80 | } 81 | } 82 | } 83 | } 84 | } 85 | 86 | // TensorRT weight files have a simple space delimited format: 87 | // [type] [size] 88 | std::map loadWeights(const std::string file) { 89 | std::cout << "Loading weights: " << file << std::endl; 90 | std::map weightMap; 91 | 92 | // Open weights file 93 | std::ifstream input(file); 94 | assert(input.is_open() && "Unable to load weight file. please check if the .wts file path is right!!!!!!"); 95 | 96 | // Read number of weight blobs 97 | int32_t count; 98 | input >> count; 99 | assert(count > 0 && "Invalid weight map file."); 100 | 101 | while (count--) 102 | { 103 | Weights wt{ DataType::kFLOAT, nullptr, 0 }; 104 | uint32_t size; 105 | 106 | // Read name and type of blob 107 | std::string name; 108 | input >> name >> std::dec >> size; 109 | wt.type = DataType::kFLOAT; 110 | 111 | // Load blob 112 | uint32_t* val = reinterpret_cast(malloc(sizeof(val) * size)); 113 | for (uint32_t x = 0, y = size; x < y; ++x) 114 | { 115 | input >> std::hex >> val[x]; 116 | } 117 | wt.values = val; 118 | 119 | wt.count = size; 120 | weightMap[name] = wt; 121 | } 122 | 123 | return weightMap; 124 | } 125 | 126 | IScaleLayer* addBatchNorm2d(INetworkDefinition *network, std::map& weightMap, ITensor& input, std::string lname, float eps) { 127 | float *gamma = (float*)weightMap[lname + ".weight"].values; 128 | float *beta = (float*)weightMap[lname + ".bias"].values; 129 | float *mean = (float*)weightMap[lname + ".running_mean"].values; 130 | float *var = (float*)weightMap[lname + ".running_var"].values; 131 | int len = weightMap[lname + ".running_var"].count; 132 | 133 | float *scval = reinterpret_cast(malloc(sizeof(float) * len)); 134 | for (int i = 0; i < len; i++) { 135 | scval[i] = gamma[i] / sqrt(var[i] + eps); 136 | } 137 | Weights scale{ DataType::kFLOAT, scval, len }; 138 | 139 | float *shval = reinterpret_cast(malloc(sizeof(float) * len)); 140 | for (int i = 0; i < len; i++) { 141 | shval[i] = beta[i] - mean[i] * gamma[i] / sqrt(var[i] + eps); 142 | } 143 | Weights shift{ DataType::kFLOAT, shval, len }; 144 | 145 | float *pval = reinterpret_cast(malloc(sizeof(float) * len)); 146 | for (int i = 0; i < len; i++) { 147 | pval[i] = 1.0; 148 | } 149 | Weights power{ DataType::kFLOAT, pval, len }; 150 | 151 | weightMap[lname + ".scale"] = scale; 152 | weightMap[lname + ".shift"] = shift; 153 | weightMap[lname + ".power"] = power; 154 | IScaleLayer* scale_1 = network->addScale(input, ScaleMode::kCHANNEL, shift, scale, power); 155 | assert(scale_1); 156 | return scale_1; 157 | } 158 | 159 | ILayer* convBlock(INetworkDefinition *network, std::map& weightMap, ITensor& input, int outch, int ksize, int s, int g, std::string lname) { 160 | Weights emptywts{ DataType::kFLOAT, nullptr, 0 }; 161 | int p = ksize / 2; 162 | IConvolutionLayer* conv1 = network->addConvolutionNd(input, outch, DimsHW{ ksize, ksize }, weightMap[lname + ".conv.weight"], emptywts); 163 | assert(conv1); 164 | conv1->setStrideNd(DimsHW{ s, s }); 165 | conv1->setPaddingNd(DimsHW{ p, p }); 166 | conv1->setNbGroups(g); 167 | IScaleLayer* bn1 = addBatchNorm2d(network, weightMap, *conv1->getOutput(0), lname + ".bn", 1e-3); 168 | 169 | // silu = x * sigmoid 170 | auto sig = network->addActivation(*bn1->getOutput(0), ActivationType::kSIGMOID); 171 | assert(sig); 172 | auto ew = network->addElementWise(*bn1->getOutput(0), *sig->getOutput(0), ElementWiseOperation::kPROD); 173 | assert(ew); 174 | return ew; 175 | } 176 | 177 | ILayer* focus(INetworkDefinition *network, std::map& weightMap, ITensor& input, int inch, int outch, int ksize, std::string lname) { 178 | ISliceLayer *s1 = network->addSlice(input, Dims3{ 0, 0, 0 }, Dims3{ inch, Yolo::INPUT_H / 2, Yolo::INPUT_W / 2 }, Dims3{ 1, 2, 2 }); 179 | ISliceLayer *s2 = network->addSlice(input, Dims3{ 0, 1, 0 }, Dims3{ inch, Yolo::INPUT_H / 2, Yolo::INPUT_W / 2 }, Dims3{ 1, 2, 2 }); 180 | ISliceLayer *s3 = network->addSlice(input, Dims3{ 0, 0, 1 }, Dims3{ inch, Yolo::INPUT_H / 2, Yolo::INPUT_W / 2 }, Dims3{ 1, 2, 2 }); 181 | ISliceLayer *s4 = network->addSlice(input, Dims3{ 0, 1, 1 }, Dims3{ inch, Yolo::INPUT_H / 2, Yolo::INPUT_W / 2 }, Dims3{ 1, 2, 2 }); 182 | ITensor* inputTensors[] = { s1->getOutput(0), s2->getOutput(0), s3->getOutput(0), s4->getOutput(0) }; 183 | auto cat = network->addConcatenation(inputTensors, 4); 184 | auto conv = convBlock(network, weightMap, *cat->getOutput(0), outch, ksize, 1, 1, lname + ".conv"); 185 | return conv; 186 | } 187 | 188 | ILayer* bottleneck(INetworkDefinition *network, std::map& weightMap, ITensor& input, int c1, int c2, bool shortcut, int g, float e, std::string lname) { 189 | auto cv1 = convBlock(network, weightMap, input, (int)((float)c2 * e), 1, 1, 1, lname + ".cv1"); 190 | auto cv2 = convBlock(network, weightMap, *cv1->getOutput(0), c2, 3, 1, g, lname + ".cv2"); 191 | if (shortcut && c1 == c2) { 192 | auto ew = network->addElementWise(input, *cv2->getOutput(0), ElementWiseOperation::kSUM); 193 | return ew; 194 | } 195 | return cv2; 196 | } 197 | 198 | ILayer* bottleneckCSP(INetworkDefinition *network, std::map& weightMap, ITensor& input, int c1, int c2, int n, bool shortcut, int g, float e, std::string lname) { 199 | Weights emptywts{ DataType::kFLOAT, nullptr, 0 }; 200 | int c_ = (int)((float)c2 * e); 201 | auto cv1 = convBlock(network, weightMap, input, c_, 1, 1, 1, lname + ".cv1"); 202 | auto cv2 = network->addConvolutionNd(input, c_, DimsHW{ 1, 1 }, weightMap[lname + ".cv2.weight"], emptywts); 203 | ITensor *y1 = cv1->getOutput(0); 204 | for (int i = 0; i < n; i++) { 205 | auto b = bottleneck(network, weightMap, *y1, c_, c_, shortcut, g, 1.0, lname + ".m." + std::to_string(i)); 206 | y1 = b->getOutput(0); 207 | } 208 | auto cv3 = network->addConvolutionNd(*y1, c_, DimsHW{ 1, 1 }, weightMap[lname + ".cv3.weight"], emptywts); 209 | 210 | ITensor* inputTensors[] = { cv3->getOutput(0), cv2->getOutput(0) }; 211 | auto cat = network->addConcatenation(inputTensors, 2); 212 | 213 | IScaleLayer* bn = addBatchNorm2d(network, weightMap, *cat->getOutput(0), lname + ".bn", 1e-4); 214 | auto lr = network->addActivation(*bn->getOutput(0), ActivationType::kLEAKY_RELU); 215 | lr->setAlpha(0.1); 216 | 217 | auto cv4 = convBlock(network, weightMap, *lr->getOutput(0), c2, 1, 1, 1, lname + ".cv4"); 218 | return cv4; 219 | } 220 | 221 | ILayer* C3(INetworkDefinition *network, std::map& weightMap, ITensor& input, int c1, int c2, int n, bool shortcut, int g, float e, std::string lname) { 222 | int c_ = (int)((float)c2 * e); 223 | auto cv1 = convBlock(network, weightMap, input, c_, 1, 1, 1, lname + ".cv1"); 224 | auto cv2 = convBlock(network, weightMap, input, c_, 1, 1, 1, lname + ".cv2"); 225 | ITensor *y1 = cv1->getOutput(0); 226 | for (int i = 0; i < n; i++) { 227 | auto b = bottleneck(network, weightMap, *y1, c_, c_, shortcut, g, 1.0, lname + ".m." + std::to_string(i)); 228 | y1 = b->getOutput(0); 229 | } 230 | 231 | ITensor* inputTensors[] = { y1, cv2->getOutput(0) }; 232 | auto cat = network->addConcatenation(inputTensors, 2); 233 | 234 | auto cv3 = convBlock(network, weightMap, *cat->getOutput(0), c2, 1, 1, 1, lname + ".cv3"); 235 | return cv3; 236 | } 237 | 238 | ILayer* SPP(INetworkDefinition *network, std::map& weightMap, ITensor& input, int c1, int c2, int k1, int k2, int k3, std::string lname) { 239 | int c_ = c1 / 2; 240 | auto cv1 = convBlock(network, weightMap, input, c_, 1, 1, 1, lname + ".cv1"); 241 | 242 | auto pool1 = network->addPoolingNd(*cv1->getOutput(0), PoolingType::kMAX, DimsHW{ k1, k1 }); 243 | pool1->setPaddingNd(DimsHW{ k1 / 2, k1 / 2 }); 244 | pool1->setStrideNd(DimsHW{ 1, 1 }); 245 | auto pool2 = network->addPoolingNd(*cv1->getOutput(0), PoolingType::kMAX, DimsHW{ k2, k2 }); 246 | pool2->setPaddingNd(DimsHW{ k2 / 2, k2 / 2 }); 247 | pool2->setStrideNd(DimsHW{ 1, 1 }); 248 | auto pool3 = network->addPoolingNd(*cv1->getOutput(0), PoolingType::kMAX, DimsHW{ k3, k3 }); 249 | pool3->setPaddingNd(DimsHW{ k3 / 2, k3 / 2 }); 250 | pool3->setStrideNd(DimsHW{ 1, 1 }); 251 | 252 | ITensor* inputTensors[] = { cv1->getOutput(0), pool1->getOutput(0), pool2->getOutput(0), pool3->getOutput(0) }; 253 | auto cat = network->addConcatenation(inputTensors, 4); 254 | 255 | auto cv2 = convBlock(network, weightMap, *cat->getOutput(0), c2, 1, 1, 1, lname + ".cv2"); 256 | return cv2; 257 | } 258 | 259 | std::vector> getAnchors(std::map& weightMap, std::string lname) { 260 | std::vector> anchors; 261 | Weights wts = weightMap[lname + ".anchor_grid"]; 262 | int anchor_len = Yolo::CHECK_COUNT * 2; 263 | for (int i = 0; i < wts.count / anchor_len; i++) { 264 | auto *p = (const float*)wts.values + i * anchor_len; 265 | std::vector anchor(p, p + anchor_len); 266 | anchors.push_back(anchor); 267 | } 268 | return anchors; 269 | } 270 | 271 | IPluginV2Layer* addYoLoLayer(INetworkDefinition *network, std::map& weightMap, std::string lname, std::vector dets) { 272 | auto creator = getPluginRegistry()->getPluginCreator("YoloLayer_TRT", "1"); 273 | auto anchors = getAnchors(weightMap, lname); 274 | PluginField plugin_fields[2]; 275 | int netinfo[4] = {Yolo::CLASS_NUM, Yolo::INPUT_W, Yolo::INPUT_H, Yolo::MAX_OUTPUT_BBOX_COUNT}; 276 | plugin_fields[0].data = netinfo; 277 | plugin_fields[0].length = 4; 278 | plugin_fields[0].name = "netinfo"; 279 | plugin_fields[0].type = PluginFieldType::kFLOAT32; 280 | int scale = 8; 281 | std::vector kernels; 282 | for (size_t i = 0; i < anchors.size(); i++) { 283 | Yolo::YoloKernel kernel; 284 | kernel.width = Yolo::INPUT_W / scale; 285 | kernel.height = Yolo::INPUT_H / scale; 286 | memcpy(kernel.anchors, &anchors[i][0], anchors[i].size() * sizeof(float)); 287 | kernels.push_back(kernel); 288 | scale *= 2; 289 | } 290 | plugin_fields[1].data = &kernels[0]; 291 | plugin_fields[1].length = kernels.size(); 292 | plugin_fields[1].name = "kernels"; 293 | plugin_fields[1].type = PluginFieldType::kFLOAT32; 294 | PluginFieldCollection plugin_data; 295 | plugin_data.nbFields = 2; 296 | plugin_data.fields = plugin_fields; 297 | IPluginV2 *plugin_obj = creator->createPlugin("yololayer", &plugin_data); 298 | std::vector input_tensors; 299 | for (auto det: dets) { 300 | input_tensors.push_back(det->getOutput(0)); 301 | } 302 | auto yolo = network->addPluginV2(&input_tensors[0], input_tensors.size(), *plugin_obj); 303 | return yolo; 304 | } 305 | #endif 306 | 307 | -------------------------------------------------------------------------------- /yolo/include/cuda_utils.h: -------------------------------------------------------------------------------- 1 | #ifndef TRTX_CUDA_UTILS_H_ 2 | #define TRTX_CUDA_UTILS_H_ 3 | 4 | #include 5 | 6 | #ifndef CUDA_CHECK 7 | #define CUDA_CHECK(callstr)\ 8 | {\ 9 | cudaError_t error_code = callstr;\ 10 | if (error_code != cudaSuccess) {\ 11 | std::cerr << "CUDA error " << error_code << " at " << __FILE__ << ":" << __LINE__;\ 12 | assert(0);\ 13 | }\ 14 | } 15 | #endif // CUDA_CHECK 16 | 17 | #endif // TRTX_CUDA_UTILS_H_ 18 | 19 | -------------------------------------------------------------------------------- /yolo/include/logging.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef TENSORRT_LOGGING_H 18 | #define TENSORRT_LOGGING_H 19 | 20 | #include "NvInferRuntimeCommon.h" 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include "macros.h" 29 | 30 | using Severity = nvinfer1::ILogger::Severity; 31 | 32 | class LogStreamConsumerBuffer : public std::stringbuf 33 | { 34 | public: 35 | LogStreamConsumerBuffer(std::ostream& stream, const std::string& prefix, bool shouldLog) 36 | : mOutput(stream) 37 | , mPrefix(prefix) 38 | , mShouldLog(shouldLog) 39 | { 40 | } 41 | 42 | LogStreamConsumerBuffer(LogStreamConsumerBuffer&& other) 43 | : mOutput(other.mOutput) 44 | { 45 | } 46 | 47 | ~LogStreamConsumerBuffer() 48 | { 49 | // std::streambuf::pbase() gives a pointer to the beginning of the buffered part of the output sequence 50 | // std::streambuf::pptr() gives a pointer to the current position of the output sequence 51 | // if the pointer to the beginning is not equal to the pointer to the current position, 52 | // call putOutput() to log the output to the stream 53 | if (pbase() != pptr()) 54 | { 55 | putOutput(); 56 | } 57 | } 58 | 59 | // synchronizes the stream buffer and returns 0 on success 60 | // synchronizing the stream buffer consists of inserting the buffer contents into the stream, 61 | // resetting the buffer and flushing the stream 62 | virtual int sync() 63 | { 64 | putOutput(); 65 | return 0; 66 | } 67 | 68 | void putOutput() 69 | { 70 | if (mShouldLog) 71 | { 72 | // prepend timestamp 73 | std::time_t timestamp = std::time(nullptr); 74 | tm* tm_local = std::localtime(×tamp); 75 | std::cout << "["; 76 | std::cout << std::setw(2) << std::setfill('0') << 1 + tm_local->tm_mon << "/"; 77 | std::cout << std::setw(2) << std::setfill('0') << tm_local->tm_mday << "/"; 78 | std::cout << std::setw(4) << std::setfill('0') << 1900 + tm_local->tm_year << "-"; 79 | std::cout << std::setw(2) << std::setfill('0') << tm_local->tm_hour << ":"; 80 | std::cout << std::setw(2) << std::setfill('0') << tm_local->tm_min << ":"; 81 | std::cout << std::setw(2) << std::setfill('0') << tm_local->tm_sec << "] "; 82 | // std::stringbuf::str() gets the string contents of the buffer 83 | // insert the buffer contents pre-appended by the appropriate prefix into the stream 84 | mOutput << mPrefix << str(); 85 | // set the buffer to empty 86 | str(""); 87 | // flush the stream 88 | mOutput.flush(); 89 | } 90 | } 91 | 92 | void setShouldLog(bool shouldLog) 93 | { 94 | mShouldLog = shouldLog; 95 | } 96 | 97 | private: 98 | std::ostream& mOutput; 99 | std::string mPrefix; 100 | bool mShouldLog; 101 | }; 102 | 103 | //! 104 | //! \class LogStreamConsumerBase 105 | //! \brief Convenience object used to initialize LogStreamConsumerBuffer before std::ostream in LogStreamConsumer 106 | //! 107 | class LogStreamConsumerBase 108 | { 109 | public: 110 | LogStreamConsumerBase(std::ostream& stream, const std::string& prefix, bool shouldLog) 111 | : mBuffer(stream, prefix, shouldLog) 112 | { 113 | } 114 | 115 | protected: 116 | LogStreamConsumerBuffer mBuffer; 117 | }; 118 | 119 | //! 120 | //! \class LogStreamConsumer 121 | //! \brief Convenience object used to facilitate use of C++ stream syntax when logging messages. 122 | //! Order of base classes is LogStreamConsumerBase and then std::ostream. 123 | //! This is because the LogStreamConsumerBase class is used to initialize the LogStreamConsumerBuffer member field 124 | //! in LogStreamConsumer and then the address of the buffer is passed to std::ostream. 125 | //! This is necessary to prevent the address of an uninitialized buffer from being passed to std::ostream. 126 | //! Please do not change the order of the parent classes. 127 | //! 128 | class LogStreamConsumer : protected LogStreamConsumerBase, public std::ostream 129 | { 130 | public: 131 | //! \brief Creates a LogStreamConsumer which logs messages with level severity. 132 | //! Reportable severity determines if the messages are severe enough to be logged. 133 | LogStreamConsumer(Severity reportableSeverity, Severity severity) 134 | : LogStreamConsumerBase(severityOstream(severity), severityPrefix(severity), severity <= reportableSeverity) 135 | , std::ostream(&mBuffer) // links the stream buffer with the stream 136 | , mShouldLog(severity <= reportableSeverity) 137 | , mSeverity(severity) 138 | { 139 | } 140 | 141 | LogStreamConsumer(LogStreamConsumer&& other) 142 | : LogStreamConsumerBase(severityOstream(other.mSeverity), severityPrefix(other.mSeverity), other.mShouldLog) 143 | , std::ostream(&mBuffer) // links the stream buffer with the stream 144 | , mShouldLog(other.mShouldLog) 145 | , mSeverity(other.mSeverity) 146 | { 147 | } 148 | 149 | void setReportableSeverity(Severity reportableSeverity) 150 | { 151 | mShouldLog = mSeverity <= reportableSeverity; 152 | mBuffer.setShouldLog(mShouldLog); 153 | } 154 | 155 | private: 156 | static std::ostream& severityOstream(Severity severity) 157 | { 158 | return severity >= Severity::kINFO ? std::cout : std::cerr; 159 | } 160 | 161 | static std::string severityPrefix(Severity severity) 162 | { 163 | switch (severity) 164 | { 165 | case Severity::kINTERNAL_ERROR: return "[F] "; 166 | case Severity::kERROR: return "[E] "; 167 | case Severity::kWARNING: return "[W] "; 168 | case Severity::kINFO: return "[I] "; 169 | case Severity::kVERBOSE: return "[V] "; 170 | default: assert(0); return ""; 171 | } 172 | } 173 | 174 | bool mShouldLog; 175 | Severity mSeverity; 176 | }; 177 | 178 | //! \class Logger 179 | //! 180 | //! \brief Class which manages logging of TensorRT tools and samples 181 | //! 182 | //! \details This class provides a common interface for TensorRT tools and samples to log information to the console, 183 | //! and supports logging two types of messages: 184 | //! 185 | //! - Debugging messages with an associated severity (info, warning, error, or internal error/fatal) 186 | //! - Test pass/fail messages 187 | //! 188 | //! The advantage of having all samples use this class for logging as opposed to emitting directly to stdout/stderr is 189 | //! that the logic for controlling the verbosity and formatting of sample output is centralized in one location. 190 | //! 191 | //! In the future, this class could be extended to support dumping test results to a file in some standard format 192 | //! (for example, JUnit XML), and providing additional metadata (e.g. timing the duration of a test run). 193 | //! 194 | //! TODO: For backwards compatibility with existing samples, this class inherits directly from the nvinfer1::ILogger 195 | //! interface, which is problematic since there isn't a clean separation between messages coming from the TensorRT 196 | //! library and messages coming from the sample. 197 | //! 198 | //! In the future (once all samples are updated to use Logger::getTRTLogger() to access the ILogger) we can refactor the 199 | //! class to eliminate the inheritance and instead make the nvinfer1::ILogger implementation a member of the Logger 200 | //! object. 201 | 202 | class Logger : public nvinfer1::ILogger 203 | { 204 | public: 205 | Logger(Severity severity = Severity::kWARNING) 206 | : mReportableSeverity(severity) 207 | { 208 | } 209 | 210 | //! 211 | //! \enum TestResult 212 | //! \brief Represents the state of a given test 213 | //! 214 | enum class TestResult 215 | { 216 | kRUNNING, //!< The test is running 217 | kPASSED, //!< The test passed 218 | kFAILED, //!< The test failed 219 | kWAIVED //!< The test was waived 220 | }; 221 | 222 | //! 223 | //! \brief Forward-compatible method for retrieving the nvinfer::ILogger associated with this Logger 224 | //! \return The nvinfer1::ILogger associated with this Logger 225 | //! 226 | //! TODO Once all samples are updated to use this method to register the logger with TensorRT, 227 | //! we can eliminate the inheritance of Logger from ILogger 228 | //! 229 | nvinfer1::ILogger& getTRTLogger() 230 | { 231 | return *this; 232 | } 233 | 234 | //! 235 | //! \brief Implementation of the nvinfer1::ILogger::log() virtual method 236 | //! 237 | //! Note samples should not be calling this function directly; it will eventually go away once we eliminate the 238 | //! inheritance from nvinfer1::ILogger 239 | //! 240 | void log(Severity severity, const char* msg) TRT_NOEXCEPT override 241 | { 242 | LogStreamConsumer(mReportableSeverity, severity) << "[TRT] " << std::string(msg) << std::endl; 243 | } 244 | 245 | //! 246 | //! \brief Method for controlling the verbosity of logging output 247 | //! 248 | //! \param severity The logger will only emit messages that have severity of this level or higher. 249 | //! 250 | void setReportableSeverity(Severity severity) 251 | { 252 | mReportableSeverity = severity; 253 | } 254 | 255 | //! 256 | //! \brief Opaque handle that holds logging information for a particular test 257 | //! 258 | //! This object is an opaque handle to information used by the Logger to print test results. 259 | //! The sample must call Logger::defineTest() in order to obtain a TestAtom that can be used 260 | //! with Logger::reportTest{Start,End}(). 261 | //! 262 | class TestAtom 263 | { 264 | public: 265 | TestAtom(TestAtom&&) = default; 266 | 267 | private: 268 | friend class Logger; 269 | 270 | TestAtom(bool started, const std::string& name, const std::string& cmdline) 271 | : mStarted(started) 272 | , mName(name) 273 | , mCmdline(cmdline) 274 | { 275 | } 276 | 277 | bool mStarted; 278 | std::string mName; 279 | std::string mCmdline; 280 | }; 281 | 282 | //! 283 | //! \brief Define a test for logging 284 | //! 285 | //! \param[in] name The name of the test. This should be a string starting with 286 | //! "TensorRT" and containing dot-separated strings containing 287 | //! the characters [A-Za-z0-9_]. 288 | //! For example, "TensorRT.sample_googlenet" 289 | //! \param[in] cmdline The command line used to reproduce the test 290 | // 291 | //! \return a TestAtom that can be used in Logger::reportTest{Start,End}(). 292 | //! 293 | static TestAtom defineTest(const std::string& name, const std::string& cmdline) 294 | { 295 | return TestAtom(false, name, cmdline); 296 | } 297 | 298 | //! 299 | //! \brief A convenience overloaded version of defineTest() that accepts an array of command-line arguments 300 | //! as input 301 | //! 302 | //! \param[in] name The name of the test 303 | //! \param[in] argc The number of command-line arguments 304 | //! \param[in] argv The array of command-line arguments (given as C strings) 305 | //! 306 | //! \return a TestAtom that can be used in Logger::reportTest{Start,End}(). 307 | static TestAtom defineTest(const std::string& name, int argc, char const* const* argv) 308 | { 309 | auto cmdline = genCmdlineString(argc, argv); 310 | return defineTest(name, cmdline); 311 | } 312 | 313 | //! 314 | //! \brief Report that a test has started. 315 | //! 316 | //! \pre reportTestStart() has not been called yet for the given testAtom 317 | //! 318 | //! \param[in] testAtom The handle to the test that has started 319 | //! 320 | static void reportTestStart(TestAtom& testAtom) 321 | { 322 | reportTestResult(testAtom, TestResult::kRUNNING); 323 | assert(!testAtom.mStarted); 324 | testAtom.mStarted = true; 325 | } 326 | 327 | //! 328 | //! \brief Report that a test has ended. 329 | //! 330 | //! \pre reportTestStart() has been called for the given testAtom 331 | //! 332 | //! \param[in] testAtom The handle to the test that has ended 333 | //! \param[in] result The result of the test. Should be one of TestResult::kPASSED, 334 | //! TestResult::kFAILED, TestResult::kWAIVED 335 | //! 336 | static void reportTestEnd(const TestAtom& testAtom, TestResult result) 337 | { 338 | assert(result != TestResult::kRUNNING); 339 | assert(testAtom.mStarted); 340 | reportTestResult(testAtom, result); 341 | } 342 | 343 | static int reportPass(const TestAtom& testAtom) 344 | { 345 | reportTestEnd(testAtom, TestResult::kPASSED); 346 | return EXIT_SUCCESS; 347 | } 348 | 349 | static int reportFail(const TestAtom& testAtom) 350 | { 351 | reportTestEnd(testAtom, TestResult::kFAILED); 352 | return EXIT_FAILURE; 353 | } 354 | 355 | static int reportWaive(const TestAtom& testAtom) 356 | { 357 | reportTestEnd(testAtom, TestResult::kWAIVED); 358 | return EXIT_SUCCESS; 359 | } 360 | 361 | static int reportTest(const TestAtom& testAtom, bool pass) 362 | { 363 | return pass ? reportPass(testAtom) : reportFail(testAtom); 364 | } 365 | 366 | Severity getReportableSeverity() const 367 | { 368 | return mReportableSeverity; 369 | } 370 | 371 | private: 372 | //! 373 | //! \brief returns an appropriate string for prefixing a log message with the given severity 374 | //! 375 | static const char* severityPrefix(Severity severity) 376 | { 377 | switch (severity) 378 | { 379 | case Severity::kINTERNAL_ERROR: return "[F] "; 380 | case Severity::kERROR: return "[E] "; 381 | case Severity::kWARNING: return "[W] "; 382 | case Severity::kINFO: return "[I] "; 383 | case Severity::kVERBOSE: return "[V] "; 384 | default: assert(0); return ""; 385 | } 386 | } 387 | 388 | //! 389 | //! \brief returns an appropriate string for prefixing a test result message with the given result 390 | //! 391 | static const char* testResultString(TestResult result) 392 | { 393 | switch (result) 394 | { 395 | case TestResult::kRUNNING: return "RUNNING"; 396 | case TestResult::kPASSED: return "PASSED"; 397 | case TestResult::kFAILED: return "FAILED"; 398 | case TestResult::kWAIVED: return "WAIVED"; 399 | default: assert(0); return ""; 400 | } 401 | } 402 | 403 | //! 404 | //! \brief returns an appropriate output stream (cout or cerr) to use with the given severity 405 | //! 406 | static std::ostream& severityOstream(Severity severity) 407 | { 408 | return severity >= Severity::kINFO ? std::cout : std::cerr; 409 | } 410 | 411 | //! 412 | //! \brief method that implements logging test results 413 | //! 414 | static void reportTestResult(const TestAtom& testAtom, TestResult result) 415 | { 416 | severityOstream(Severity::kINFO) << "&&&& " << testResultString(result) << " " << testAtom.mName << " # " 417 | << testAtom.mCmdline << std::endl; 418 | } 419 | 420 | //! 421 | //! \brief generate a command line string from the given (argc, argv) values 422 | //! 423 | static std::string genCmdlineString(int argc, char const* const* argv) 424 | { 425 | std::stringstream ss; 426 | for (int i = 0; i < argc; i++) 427 | { 428 | if (i > 0) 429 | ss << " "; 430 | ss << argv[i]; 431 | } 432 | return ss.str(); 433 | } 434 | 435 | Severity mReportableSeverity; 436 | }; 437 | 438 | namespace 439 | { 440 | 441 | //! 442 | //! \brief produces a LogStreamConsumer object that can be used to log messages of severity kVERBOSE 443 | //! 444 | //! Example usage: 445 | //! 446 | //! LOG_VERBOSE(logger) << "hello world" << std::endl; 447 | //! 448 | inline LogStreamConsumer LOG_VERBOSE(const Logger& logger) 449 | { 450 | return LogStreamConsumer(logger.getReportableSeverity(), Severity::kVERBOSE); 451 | } 452 | 453 | //! 454 | //! \brief produces a LogStreamConsumer object that can be used to log messages of severity kINFO 455 | //! 456 | //! Example usage: 457 | //! 458 | //! LOG_INFO(logger) << "hello world" << std::endl; 459 | //! 460 | inline LogStreamConsumer LOG_INFO(const Logger& logger) 461 | { 462 | return LogStreamConsumer(logger.getReportableSeverity(), Severity::kINFO); 463 | } 464 | 465 | //! 466 | //! \brief produces a LogStreamConsumer object that can be used to log messages of severity kWARNING 467 | //! 468 | //! Example usage: 469 | //! 470 | //! LOG_WARN(logger) << "hello world" << std::endl; 471 | //! 472 | inline LogStreamConsumer LOG_WARN(const Logger& logger) 473 | { 474 | return LogStreamConsumer(logger.getReportableSeverity(), Severity::kWARNING); 475 | } 476 | 477 | //! 478 | //! \brief produces a LogStreamConsumer object that can be used to log messages of severity kERROR 479 | //! 480 | //! Example usage: 481 | //! 482 | //! LOG_ERROR(logger) << "hello world" << std::endl; 483 | //! 484 | inline LogStreamConsumer LOG_ERROR(const Logger& logger) 485 | { 486 | return LogStreamConsumer(logger.getReportableSeverity(), Severity::kERROR); 487 | } 488 | 489 | //! 490 | //! \brief produces a LogStreamConsumer object that can be used to log messages of severity kINTERNAL_ERROR 491 | // ("fatal" severity) 492 | //! 493 | //! Example usage: 494 | //! 495 | //! LOG_FATAL(logger) << "hello world" << std::endl; 496 | //! 497 | inline LogStreamConsumer LOG_FATAL(const Logger& logger) 498 | { 499 | return LogStreamConsumer(logger.getReportableSeverity(), Severity::kINTERNAL_ERROR); 500 | } 501 | 502 | } // anonymous namespace 503 | 504 | #endif // TENSORRT_LOGGING_H 505 | -------------------------------------------------------------------------------- /yolo/include/macros.h: -------------------------------------------------------------------------------- 1 | #ifndef __MACROS_H 2 | #define __MACROS_H 3 | 4 | #ifdef API_EXPORTS 5 | #if defined(_MSC_VER) 6 | #define API __declspec(dllexport) 7 | #else 8 | #define API __attribute__((visibility("default"))) 9 | #endif 10 | #else 11 | 12 | #if defined(_MSC_VER) 13 | #define API __declspec(dllimport) 14 | #else 15 | #define API 16 | #endif 17 | #endif // API_EXPORTS 18 | 19 | #if NV_TENSORRT_MAJOR >= 8 20 | #define TRT_NOEXCEPT noexcept 21 | #define TRT_CONST_ENQUEUE const 22 | #else 23 | #define TRT_NOEXCEPT 24 | #define TRT_CONST_ENQUEUE 25 | #endif 26 | 27 | #endif // __MACROS_H 28 | -------------------------------------------------------------------------------- /yolo/include/utils.h: -------------------------------------------------------------------------------- 1 | #ifndef TRTX_YOLOV5_UTILS_H_ 2 | #define TRTX_YOLOV5_UTILS_H_ 3 | 4 | #include 5 | #include 6 | 7 | static inline cv::Mat preprocess_img(cv::Mat& img, int input_w, int input_h) { 8 | int w, h, x, y; 9 | float r_w = input_w / (img.cols*1.0); 10 | float r_h = input_h / (img.rows*1.0); 11 | if (r_h > r_w) { 12 | w = input_w; 13 | h = r_w * img.rows; 14 | x = 0; 15 | y = (input_h - h) / 2; 16 | } else { 17 | w = r_h * img.cols; 18 | h = input_h; 19 | x = (input_w - w) / 2; 20 | y = 0; 21 | } 22 | cv::Mat re(h, w, CV_8UC3); 23 | cv::resize(img, re, re.size(), 0, 0, cv::INTER_LINEAR); 24 | cv::Mat out(input_h, input_w, CV_8UC3, cv::Scalar(128, 128, 128)); 25 | re.copyTo(out(cv::Rect(x, y, re.cols, re.rows))); 26 | return out; 27 | } 28 | 29 | static inline int read_files_in_dir(const char *p_dir_name, std::vector &file_names) { 30 | DIR *p_dir = opendir(p_dir_name); 31 | if (p_dir == nullptr) { 32 | return -1; 33 | } 34 | 35 | struct dirent* p_file = nullptr; 36 | while ((p_file = readdir(p_dir)) != nullptr) { 37 | if (strcmp(p_file->d_name, ".") != 0 && 38 | strcmp(p_file->d_name, "..") != 0) { 39 | //std::string cur_file_name(p_dir_name); 40 | //cur_file_name += "/"; 41 | //cur_file_name += p_file->d_name; 42 | std::string cur_file_name(p_file->d_name); 43 | file_names.push_back(cur_file_name); 44 | } 45 | } 46 | 47 | closedir(p_dir); 48 | return 0; 49 | } 50 | 51 | #endif // TRTX_YOLOV5_UTILS_H_ 52 | 53 | -------------------------------------------------------------------------------- /yolo/include/yololayer.cu: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "yololayer.h" 5 | #include "cuda_utils.h" 6 | 7 | namespace Tn 8 | { 9 | template 10 | void write(char*& buffer, const T& val) 11 | { 12 | *reinterpret_cast(buffer) = val; 13 | buffer += sizeof(T); 14 | } 15 | 16 | template 17 | void read(const char*& buffer, T& val) 18 | { 19 | val = *reinterpret_cast(buffer); 20 | buffer += sizeof(T); 21 | } 22 | } 23 | 24 | using namespace Yolo; 25 | 26 | namespace nvinfer1 27 | { 28 | YoloLayerPlugin::YoloLayerPlugin(int classCount, int netWidth, int netHeight, int maxOut, const std::vector& vYoloKernel) 29 | { 30 | mClassCount = classCount; 31 | mYoloV5NetWidth = netWidth; 32 | mYoloV5NetHeight = netHeight; 33 | mMaxOutObject = maxOut; 34 | mYoloKernel = vYoloKernel; 35 | mKernelCount = vYoloKernel.size(); 36 | 37 | CUDA_CHECK(cudaMallocHost(&mAnchor, mKernelCount * sizeof(void*))); 38 | size_t AnchorLen = sizeof(float)* CHECK_COUNT * 2; 39 | for (int ii = 0; ii < mKernelCount; ii++) 40 | { 41 | CUDA_CHECK(cudaMalloc(&mAnchor[ii], AnchorLen)); 42 | const auto& yolo = mYoloKernel[ii]; 43 | CUDA_CHECK(cudaMemcpy(mAnchor[ii], yolo.anchors, AnchorLen, cudaMemcpyHostToDevice)); 44 | } 45 | } 46 | YoloLayerPlugin::~YoloLayerPlugin() 47 | { 48 | for (int ii = 0; ii < mKernelCount; ii++) 49 | { 50 | CUDA_CHECK(cudaFree(mAnchor[ii])); 51 | } 52 | CUDA_CHECK(cudaFreeHost(mAnchor)); 53 | } 54 | 55 | // create the plugin at runtime from a byte stream 56 | YoloLayerPlugin::YoloLayerPlugin(const void* data, size_t length) 57 | { 58 | using namespace Tn; 59 | const char *d = reinterpret_cast(data), *a = d; 60 | read(d, mClassCount); 61 | read(d, mThreadCount); 62 | read(d, mKernelCount); 63 | read(d, mYoloV5NetWidth); 64 | read(d, mYoloV5NetHeight); 65 | read(d, mMaxOutObject); 66 | mYoloKernel.resize(mKernelCount); 67 | auto kernelSize = mKernelCount * sizeof(YoloKernel); 68 | memcpy(mYoloKernel.data(), d, kernelSize); 69 | d += kernelSize; 70 | CUDA_CHECK(cudaMallocHost(&mAnchor, mKernelCount * sizeof(void*))); 71 | size_t AnchorLen = sizeof(float)* CHECK_COUNT * 2; 72 | for (int ii = 0; ii < mKernelCount; ii++) 73 | { 74 | CUDA_CHECK(cudaMalloc(&mAnchor[ii], AnchorLen)); 75 | const auto& yolo = mYoloKernel[ii]; 76 | CUDA_CHECK(cudaMemcpy(mAnchor[ii], yolo.anchors, AnchorLen, cudaMemcpyHostToDevice)); 77 | } 78 | assert(d == a + length); 79 | } 80 | 81 | void YoloLayerPlugin::serialize(void* buffer) const TRT_NOEXCEPT 82 | { 83 | using namespace Tn; 84 | char* d = static_cast(buffer), *a = d; 85 | write(d, mClassCount); 86 | write(d, mThreadCount); 87 | write(d, mKernelCount); 88 | write(d, mYoloV5NetWidth); 89 | write(d, mYoloV5NetHeight); 90 | write(d, mMaxOutObject); 91 | auto kernelSize = mKernelCount * sizeof(YoloKernel); 92 | memcpy(d, mYoloKernel.data(), kernelSize); 93 | d += kernelSize; 94 | 95 | assert(d == a + getSerializationSize()); 96 | } 97 | 98 | size_t YoloLayerPlugin::getSerializationSize() const TRT_NOEXCEPT 99 | { 100 | return sizeof(mClassCount) + sizeof(mThreadCount) + sizeof(mKernelCount) + sizeof(Yolo::YoloKernel) * mYoloKernel.size() + sizeof(mYoloV5NetWidth) + sizeof(mYoloV5NetHeight) + sizeof(mMaxOutObject); 101 | } 102 | 103 | int YoloLayerPlugin::initialize() TRT_NOEXCEPT 104 | { 105 | return 0; 106 | } 107 | 108 | Dims YoloLayerPlugin::getOutputDimensions(int index, const Dims* inputs, int nbInputDims) TRT_NOEXCEPT 109 | { 110 | //output the result to channel 111 | int totalsize = mMaxOutObject * sizeof(Detection) / sizeof(float); 112 | 113 | return Dims3(totalsize + 1, 1, 1); 114 | } 115 | 116 | // Set plugin namespace 117 | void YoloLayerPlugin::setPluginNamespace(const char* pluginNamespace) TRT_NOEXCEPT 118 | { 119 | mPluginNamespace = pluginNamespace; 120 | } 121 | 122 | const char* YoloLayerPlugin::getPluginNamespace() const TRT_NOEXCEPT 123 | { 124 | return mPluginNamespace; 125 | } 126 | 127 | // Return the DataType of the plugin output at the requested index 128 | DataType YoloLayerPlugin::getOutputDataType(int index, const nvinfer1::DataType* inputTypes, int nbInputs) const TRT_NOEXCEPT 129 | { 130 | return DataType::kFLOAT; 131 | } 132 | 133 | // Return true if output tensor is broadcast across a batch. 134 | bool YoloLayerPlugin::isOutputBroadcastAcrossBatch(int outputIndex, const bool* inputIsBroadcasted, int nbInputs) const TRT_NOEXCEPT 135 | { 136 | return false; 137 | } 138 | 139 | // Return true if plugin can use input that is broadcast across batch without replication. 140 | bool YoloLayerPlugin::canBroadcastInputAcrossBatch(int inputIndex) const TRT_NOEXCEPT 141 | { 142 | return false; 143 | } 144 | 145 | void YoloLayerPlugin::configurePlugin(const PluginTensorDesc* in, int nbInput, const PluginTensorDesc* out, int nbOutput) TRT_NOEXCEPT 146 | { 147 | } 148 | 149 | // Attach the plugin object to an execution context and grant the plugin the access to some context resource. 150 | void YoloLayerPlugin::attachToContext(cudnnContext* cudnnContext, cublasContext* cublasContext, IGpuAllocator* gpuAllocator) TRT_NOEXCEPT 151 | { 152 | } 153 | 154 | // Detach the plugin object from its execution context. 155 | void YoloLayerPlugin::detachFromContext() TRT_NOEXCEPT {} 156 | 157 | const char* YoloLayerPlugin::getPluginType() const TRT_NOEXCEPT 158 | { 159 | return "YoloLayer_TRT"; 160 | } 161 | 162 | const char* YoloLayerPlugin::getPluginVersion() const TRT_NOEXCEPT 163 | { 164 | return "1"; 165 | } 166 | 167 | void YoloLayerPlugin::destroy() TRT_NOEXCEPT 168 | { 169 | delete this; 170 | } 171 | 172 | // Clone the plugin 173 | IPluginV2IOExt* YoloLayerPlugin::clone() const TRT_NOEXCEPT 174 | { 175 | YoloLayerPlugin* p = new YoloLayerPlugin(mClassCount, mYoloV5NetWidth, mYoloV5NetHeight, mMaxOutObject, mYoloKernel); 176 | p->setPluginNamespace(mPluginNamespace); 177 | return p; 178 | } 179 | 180 | __device__ float Logist(float data) { return 1.0f / (1.0f + expf(-data)); }; 181 | 182 | __global__ void CalDetection(const float *input, float *output, int noElements, 183 | const int netwidth, const int netheight, int maxoutobject, int yoloWidth, int yoloHeight, const float anchors[CHECK_COUNT * 2], int classes, int outputElem) 184 | { 185 | 186 | int idx = threadIdx.x + blockDim.x * blockIdx.x; 187 | if (idx >= noElements) return; 188 | 189 | int total_grid = yoloWidth * yoloHeight; 190 | int bnIdx = idx / total_grid; 191 | idx = idx - total_grid * bnIdx; 192 | int info_len_i = 5 + classes; 193 | const float* curInput = input + bnIdx * (info_len_i * total_grid * CHECK_COUNT); 194 | 195 | for (int k = 0; k < CHECK_COUNT; ++k) { 196 | float box_prob = Logist(curInput[idx + k * info_len_i * total_grid + 4 * total_grid]); 197 | if (box_prob < IGNORE_THRESH) continue; 198 | int class_id = 0; 199 | float max_cls_prob = 0.0; 200 | for (int i = 5; i < info_len_i; ++i) { 201 | float p = Logist(curInput[idx + k * info_len_i * total_grid + i * total_grid]); 202 | if (p > max_cls_prob) { 203 | max_cls_prob = p; 204 | class_id = i - 5; 205 | } 206 | } 207 | float *res_count = output + bnIdx * outputElem; 208 | int count = (int)atomicAdd(res_count, 1); 209 | if (count >= maxoutobject) return; 210 | char *data = (char*)res_count + sizeof(float) + count * sizeof(Detection); 211 | Detection *det = (Detection*)(data); 212 | 213 | int row = idx / yoloWidth; 214 | int col = idx % yoloWidth; 215 | 216 | //Location 217 | // pytorch: 218 | // y = x[i].sigmoid() 219 | // y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i].to(x[i].device)) * self.stride[i] # xy 220 | // y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh 221 | // X: (sigmoid(tx) + cx)/FeaturemapW * netwidth 222 | det->bbox[0] = (col - 0.5f + 2.0f * Logist(curInput[idx + k * info_len_i * total_grid + 0 * total_grid])) * netwidth / yoloWidth; 223 | det->bbox[1] = (row - 0.5f + 2.0f * Logist(curInput[idx + k * info_len_i * total_grid + 1 * total_grid])) * netheight / yoloHeight; 224 | 225 | // W: (Pw * e^tw) / FeaturemapW * netwidth 226 | // v5: https://github.com/ultralytics/yolov5/issues/471 227 | det->bbox[2] = 2.0f * Logist(curInput[idx + k * info_len_i * total_grid + 2 * total_grid]); 228 | det->bbox[2] = det->bbox[2] * det->bbox[2] * anchors[2 * k]; 229 | det->bbox[3] = 2.0f * Logist(curInput[idx + k * info_len_i * total_grid + 3 * total_grid]); 230 | det->bbox[3] = det->bbox[3] * det->bbox[3] * anchors[2 * k + 1]; 231 | det->conf = box_prob * max_cls_prob; 232 | det->class_id = class_id; 233 | } 234 | } 235 | 236 | void YoloLayerPlugin::forwardGpu(const float* const* inputs, float *output, cudaStream_t stream, int batchSize) 237 | { 238 | int outputElem = 1 + mMaxOutObject * sizeof(Detection) / sizeof(float); 239 | for (int idx = 0; idx < batchSize; ++idx) { 240 | CUDA_CHECK(cudaMemset(output + idx * outputElem, 0, sizeof(float))); 241 | } 242 | int numElem = 0; 243 | for (unsigned int i = 0; i < mYoloKernel.size(); ++i) { 244 | const auto& yolo = mYoloKernel[i]; 245 | numElem = yolo.width * yolo.height * batchSize; 246 | if (numElem < mThreadCount) mThreadCount = numElem; 247 | 248 | //printf("Net: %d %d \n", mYoloV5NetWidth, mYoloV5NetHeight); 249 | CalDetection << < (numElem + mThreadCount - 1) / mThreadCount, mThreadCount, 0, stream >> > 250 | (inputs[i], output, numElem, mYoloV5NetWidth, mYoloV5NetHeight, mMaxOutObject, yolo.width, yolo.height, (float*)mAnchor[i], mClassCount, outputElem); 251 | } 252 | } 253 | 254 | 255 | int YoloLayerPlugin::enqueue(int batchSize, const void* const* inputs, void* TRT_CONST_ENQUEUE* outputs, void* workspace, cudaStream_t stream) TRT_NOEXCEPT 256 | { 257 | forwardGpu((const float* const*)inputs, (float*)outputs[0], stream, batchSize); 258 | return 0; 259 | } 260 | 261 | PluginFieldCollection YoloPluginCreator::mFC{}; 262 | std::vector YoloPluginCreator::mPluginAttributes; 263 | 264 | YoloPluginCreator::YoloPluginCreator() 265 | { 266 | mPluginAttributes.clear(); 267 | 268 | mFC.nbFields = mPluginAttributes.size(); 269 | mFC.fields = mPluginAttributes.data(); 270 | } 271 | 272 | const char* YoloPluginCreator::getPluginName() const TRT_NOEXCEPT 273 | { 274 | return "YoloLayer_TRT"; 275 | } 276 | 277 | const char* YoloPluginCreator::getPluginVersion() const TRT_NOEXCEPT 278 | { 279 | return "1"; 280 | } 281 | 282 | const PluginFieldCollection* YoloPluginCreator::getFieldNames() TRT_NOEXCEPT 283 | { 284 | return &mFC; 285 | } 286 | 287 | IPluginV2IOExt* YoloPluginCreator::createPlugin(const char* name, const PluginFieldCollection* fc) TRT_NOEXCEPT 288 | { 289 | assert(fc->nbFields == 2); 290 | assert(strcmp(fc->fields[0].name, "netinfo") == 0); 291 | assert(strcmp(fc->fields[1].name, "kernels") == 0); 292 | int *p_netinfo = (int*)(fc->fields[0].data); 293 | int class_count = p_netinfo[0]; 294 | int input_w = p_netinfo[1]; 295 | int input_h = p_netinfo[2]; 296 | int max_output_object_count = p_netinfo[3]; 297 | std::vector kernels(fc->fields[1].length); 298 | memcpy(&kernels[0], fc->fields[1].data, kernels.size() * sizeof(Yolo::YoloKernel)); 299 | YoloLayerPlugin* obj = new YoloLayerPlugin(class_count, input_w, input_h, max_output_object_count, kernels); 300 | obj->setPluginNamespace(mNamespace.c_str()); 301 | return obj; 302 | } 303 | 304 | IPluginV2IOExt* YoloPluginCreator::deserializePlugin(const char* name, const void* serialData, size_t serialLength) TRT_NOEXCEPT 305 | { 306 | // This object will be deleted when the network is destroyed, which will 307 | // call YoloLayerPlugin::destroy() 308 | YoloLayerPlugin* obj = new YoloLayerPlugin(serialData, serialLength); 309 | obj->setPluginNamespace(mNamespace.c_str()); 310 | return obj; 311 | } 312 | } 313 | 314 | -------------------------------------------------------------------------------- /yolo/include/yololayer.h: -------------------------------------------------------------------------------- 1 | #ifndef _YOLO_LAYER_H 2 | #define _YOLO_LAYER_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include "macros.h" 8 | 9 | namespace Yolo 10 | { 11 | static constexpr int CHECK_COUNT = 3; 12 | static constexpr float IGNORE_THRESH = 0.1f; 13 | struct YoloKernel 14 | { 15 | int width; 16 | int height; 17 | float anchors[CHECK_COUNT * 2]; 18 | }; 19 | static constexpr int MAX_OUTPUT_BBOX_COUNT = 1000; 20 | static constexpr int CLASS_NUM = 2; 21 | static constexpr int INPUT_H = 640; // yolov5's input height and width must be divisible by 32. 22 | static constexpr int INPUT_W = 640; 23 | 24 | static constexpr int LOCATIONS = 4; 25 | struct alignas(float) Detection { 26 | //center_x center_y w h 27 | float bbox[LOCATIONS]; 28 | float conf; // bbox_conf * cls_conf 29 | float class_id; 30 | }; 31 | } 32 | 33 | namespace nvinfer1 34 | { 35 | class API YoloLayerPlugin : public IPluginV2IOExt 36 | { 37 | public: 38 | YoloLayerPlugin(int classCount, int netWidth, int netHeight, int maxOut, const std::vector& vYoloKernel); 39 | YoloLayerPlugin(const void* data, size_t length); 40 | ~YoloLayerPlugin(); 41 | 42 | int getNbOutputs() const TRT_NOEXCEPT override 43 | { 44 | return 1; 45 | } 46 | 47 | Dims getOutputDimensions(int index, const Dims* inputs, int nbInputDims) TRT_NOEXCEPT override; 48 | 49 | int initialize() TRT_NOEXCEPT override; 50 | 51 | virtual void terminate() TRT_NOEXCEPT override {}; 52 | 53 | virtual size_t getWorkspaceSize(int maxBatchSize) const TRT_NOEXCEPT override { return 0; } 54 | 55 | virtual int enqueue(int batchSize, const void* const* inputs, void*TRT_CONST_ENQUEUE* outputs, void* workspace, cudaStream_t stream) TRT_NOEXCEPT override; 56 | 57 | virtual size_t getSerializationSize() const TRT_NOEXCEPT override; 58 | 59 | virtual void serialize(void* buffer) const TRT_NOEXCEPT override; 60 | 61 | bool supportsFormatCombination(int pos, const PluginTensorDesc* inOut, int nbInputs, int nbOutputs) const TRT_NOEXCEPT override { 62 | return inOut[pos].format == TensorFormat::kLINEAR && inOut[pos].type == DataType::kFLOAT; 63 | } 64 | 65 | const char* getPluginType() const TRT_NOEXCEPT override; 66 | 67 | const char* getPluginVersion() const TRT_NOEXCEPT override; 68 | 69 | void destroy() TRT_NOEXCEPT override; 70 | 71 | IPluginV2IOExt* clone() const TRT_NOEXCEPT override; 72 | 73 | void setPluginNamespace(const char* pluginNamespace) TRT_NOEXCEPT override; 74 | 75 | const char* getPluginNamespace() const TRT_NOEXCEPT override; 76 | 77 | DataType getOutputDataType(int index, const nvinfer1::DataType* inputTypes, int nbInputs) const TRT_NOEXCEPT override; 78 | 79 | bool isOutputBroadcastAcrossBatch(int outputIndex, const bool* inputIsBroadcasted, int nbInputs) const TRT_NOEXCEPT override; 80 | 81 | bool canBroadcastInputAcrossBatch(int inputIndex) const TRT_NOEXCEPT override; 82 | 83 | void attachToContext( 84 | cudnnContext* cudnnContext, cublasContext* cublasContext, IGpuAllocator* gpuAllocator) TRT_NOEXCEPT override; 85 | 86 | void configurePlugin(const PluginTensorDesc* in, int nbInput, const PluginTensorDesc* out, int nbOutput) TRT_NOEXCEPT override; 87 | 88 | void detachFromContext() TRT_NOEXCEPT override; 89 | 90 | private: 91 | void forwardGpu(const float* const* inputs, float *output, cudaStream_t stream, int batchSize = 1); 92 | int mThreadCount = 256; 93 | const char* mPluginNamespace; 94 | int mKernelCount; 95 | int mClassCount; 96 | int mYoloV5NetWidth; 97 | int mYoloV5NetHeight; 98 | int mMaxOutObject; 99 | std::vector mYoloKernel; 100 | void** mAnchor; 101 | }; 102 | 103 | class API YoloPluginCreator : public IPluginCreator 104 | { 105 | public: 106 | YoloPluginCreator(); 107 | 108 | ~YoloPluginCreator() override = default; 109 | 110 | const char* getPluginName() const TRT_NOEXCEPT override; 111 | 112 | const char* getPluginVersion() const TRT_NOEXCEPT override; 113 | 114 | const PluginFieldCollection* getFieldNames() TRT_NOEXCEPT override; 115 | 116 | IPluginV2IOExt* createPlugin(const char* name, const PluginFieldCollection* fc) TRT_NOEXCEPT override; 117 | 118 | IPluginV2IOExt* deserializePlugin(const char* name, const void* serialData, size_t serialLength) TRT_NOEXCEPT override; 119 | 120 | void setPluginNamespace(const char* libNamespace) TRT_NOEXCEPT override 121 | { 122 | mNamespace = libNamespace; 123 | } 124 | 125 | const char* getPluginNamespace() const TRT_NOEXCEPT override 126 | { 127 | return mNamespace.c_str(); 128 | } 129 | 130 | private: 131 | std::string mNamespace; 132 | static PluginFieldCollection mFC; 133 | static std::vector mPluginAttributes; 134 | }; 135 | REGISTER_TENSORRT_PLUGIN(YoloPluginCreator); 136 | }; 137 | 138 | #endif // _YOLO_LAYER_H 139 | -------------------------------------------------------------------------------- /yolo/include/yolov5_lib.h: -------------------------------------------------------------------------------- 1 | 2 | #pragma once 3 | #ifdef __cplusplus 4 | #include "datatype.h" 5 | extern "C" 6 | { 7 | #endif 8 | 9 | void * yolov5_trt_create(const char * engine_name); 10 | 11 | int yolov5_trt_detect(void *h, cv::Mat &img, float threshold,std::vector& det); 12 | 13 | void yolov5_trt_destroy(void *h); 14 | 15 | #ifdef __cplusplus 16 | } 17 | #endif 18 | 19 | 20 | -------------------------------------------------------------------------------- /yolo/src/calibrator.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include "calibrator.h" 6 | #include "cuda_utils.h" 7 | #include "utils.h" 8 | 9 | Int8EntropyCalibrator2::Int8EntropyCalibrator2(int batchsize, int input_w, int input_h, const char* img_dir, const char* calib_table_name, const char* input_blob_name, bool read_cache) 10 | : batchsize_(batchsize) 11 | , input_w_(input_w) 12 | , input_h_(input_h) 13 | , img_idx_(0) 14 | , img_dir_(img_dir) 15 | , calib_table_name_(calib_table_name) 16 | , input_blob_name_(input_blob_name) 17 | , read_cache_(read_cache) 18 | { 19 | input_count_ = 3 * input_w * input_h * batchsize; 20 | CUDA_CHECK(cudaMalloc(&device_input_, input_count_ * sizeof(float))); 21 | read_files_in_dir(img_dir, img_files_); 22 | } 23 | 24 | Int8EntropyCalibrator2::~Int8EntropyCalibrator2() 25 | { 26 | CUDA_CHECK(cudaFree(device_input_)); 27 | } 28 | 29 | int Int8EntropyCalibrator2::getBatchSize() const TRT_NOEXCEPT 30 | { 31 | return batchsize_; 32 | } 33 | 34 | bool Int8EntropyCalibrator2::getBatch(void* bindings[], const char* names[], int nbBindings) TRT_NOEXCEPT 35 | { 36 | if (img_idx_ + batchsize_ > (int)img_files_.size()) { 37 | return false; 38 | } 39 | 40 | std::vector input_imgs_; 41 | for (int i = img_idx_; i < img_idx_ + batchsize_; i++) { 42 | std::cout << img_files_[i] << " " << i << std::endl; 43 | cv::Mat temp = cv::imread(img_dir_ + img_files_[i]); 44 | if (temp.empty()){ 45 | std::cerr << "Fatal error: image cannot open!" << std::endl; 46 | return false; 47 | } 48 | cv::Mat pr_img = preprocess_img(temp, input_w_, input_h_); 49 | input_imgs_.push_back(pr_img); 50 | } 51 | img_idx_ += batchsize_; 52 | cv::Mat blob = cv::dnn::blobFromImages(input_imgs_, 1.0 / 255.0, cv::Size(input_w_, input_h_), cv::Scalar(0, 0, 0), true, false); 53 | 54 | CUDA_CHECK(cudaMemcpy(device_input_, blob.ptr(0), input_count_ * sizeof(float), cudaMemcpyHostToDevice)); 55 | assert(!strcmp(names[0], input_blob_name_)); 56 | bindings[0] = device_input_; 57 | return true; 58 | } 59 | 60 | const void* Int8EntropyCalibrator2::readCalibrationCache(size_t& length) TRT_NOEXCEPT 61 | { 62 | std::cout << "reading calib cache: " << calib_table_name_ << std::endl; 63 | calib_cache_.clear(); 64 | std::ifstream input(calib_table_name_, std::ios::binary); 65 | input >> std::noskipws; 66 | if (read_cache_ && input.good()) 67 | { 68 | std::copy(std::istream_iterator(input), std::istream_iterator(), std::back_inserter(calib_cache_)); 69 | } 70 | length = calib_cache_.size(); 71 | return length ? calib_cache_.data() : nullptr; 72 | } 73 | 74 | void Int8EntropyCalibrator2::writeCalibrationCache(const void* cache, size_t length) TRT_NOEXCEPT 75 | { 76 | std::cout << "writing calib cache: " << calib_table_name_ << " size: " << length << std::endl; 77 | std::ofstream output(calib_table_name_, std::ios::binary); 78 | output.write(reinterpret_cast(cache), length); 79 | } 80 | 81 | -------------------------------------------------------------------------------- /yolo/src/yolov5_lib.cpp: -------------------------------------------------------------------------------- 1 | //yolov5_lib.cpp 2 | 3 | #include 4 | #include 5 | #include "cuda_runtime_api.h" 6 | #include "logging.h" 7 | #include "common.hpp" 8 | #include "yolov5_lib.h" 9 | #include "cuda_utils.h" 10 | #include "utils.h" 11 | #include "datatype.h" 12 | #define USE_FP16 // comment out this if want to use FP32 13 | #define DEVICE 0 // GPU id 14 | #define NMS_THRESH 0.4 15 | #define CONF_THRESH 0.3 16 | #define BATCH_SIZE 1 17 | 18 | // stuff we know about the network and the input/output blobs 19 | static const int INPUT_H = Yolo::INPUT_H; 20 | static const int INPUT_W = Yolo::INPUT_W; 21 | static const int CLASS_NUM = Yolo::CLASS_NUM; 22 | static const int OUTPUT_SIZE = Yolo::MAX_OUTPUT_BBOX_COUNT * sizeof(Yolo::Detection) / sizeof(float) + 1; // we assume the yololayer outputs no more than MAX_OUTPUT_BBOX_COUNT boxes that conf >= 0.1 23 | const char* INPUT_BLOB_NAME = "data"; 24 | const char* OUTPUT_BLOB_NAME = "prob"; 25 | static Logger gLogger; 26 | 27 | 28 | static void doInference(IExecutionContext& context, cudaStream_t& stream, void **buffers, float* input, float* output, int batchSize) { 29 | // DMA input batch data to device, infer on the batch asynchronously, and DMA output back to host 30 | CUDA_CHECK(cudaMemcpyAsync(buffers[0], input, batchSize * 3 * INPUT_H * INPUT_W * sizeof(float), cudaMemcpyHostToDevice, stream)); 31 | //cudaMemcpyAsync(buffers[0], input, batchSize * 3 * INPUT_H * INPUT_W * sizeof(float), cudaMemcpyHostToDevice, stream); 32 | context.enqueue(batchSize, buffers, stream, nullptr); 33 | CUDA_CHECK(cudaMemcpyAsync(output, buffers[1], batchSize * OUTPUT_SIZE * sizeof(float), cudaMemcpyDeviceToHost, stream)); 34 | //cudaMemcpyAsync(output, buffers[1], batchSize * OUTPUT_SIZE * sizeof(float), cudaMemcpyDeviceToHost, stream); 35 | cudaStreamSynchronize(stream); 36 | } 37 | 38 | 39 | typedef struct 40 | { 41 | 42 | float *data; 43 | float *prob; 44 | IRuntime *runtime; 45 | ICudaEngine *engine; 46 | IExecutionContext *exe_context; 47 | void* buffers[2]; 48 | cudaStream_t cuda_stream; 49 | int inputIndex; 50 | int outputIndex; 51 | char result_json_str[16384]; 52 | 53 | }Yolov5TRTContext; 54 | 55 | typedef struct{ 56 | int class_id; 57 | int x1; 58 | int y1; 59 | int x2; 60 | int y2; 61 | float conf; 62 | 63 | }DeepsortContext; 64 | 65 | void * yolov5_trt_create(const char * engine_name) 66 | { 67 | size_t size = 0; 68 | char *trtModelStream = NULL; 69 | Yolov5TRTContext * trt_ctx = NULL; 70 | 71 | trt_ctx = new Yolov5TRTContext(); 72 | 73 | std::ifstream file(engine_name, std::ios::binary); 74 | printf("yolov5_trt_create ... \n"); 75 | if (file.good()) { 76 | file.seekg(0, file.end); 77 | size = file.tellg(); 78 | file.seekg(0, file.beg); 79 | trtModelStream = new char[size]; 80 | assert(trtModelStream); 81 | file.read(trtModelStream, size); 82 | file.close(); 83 | }else 84 | return NULL; 85 | 86 | trt_ctx->data = new float[BATCH_SIZE * 3 * INPUT_H * INPUT_W]; 87 | trt_ctx->prob = new float[BATCH_SIZE * OUTPUT_SIZE]; 88 | trt_ctx->runtime = createInferRuntime(gLogger); 89 | assert(trt_ctx->runtime != nullptr); 90 | 91 | printf("yolov5_trt_create cuda engine... \n"); 92 | trt_ctx->engine = trt_ctx->runtime->deserializeCudaEngine(trtModelStream, size); 93 | assert(trt_ctx->engine != nullptr); 94 | trt_ctx->exe_context = trt_ctx->engine->createExecutionContext(); 95 | 96 | 97 | delete[] trtModelStream; 98 | assert(trt_ctx->engine->getNbBindings() == 2); 99 | 100 | // In order to bind the buffers, we need to know the names of the input and output tensors. 101 | // Note that indices are guaranteed to be less than IEngine::getNbBindings() 102 | trt_ctx->inputIndex = trt_ctx->engine->getBindingIndex(INPUT_BLOB_NAME); 103 | trt_ctx->outputIndex = trt_ctx->engine->getBindingIndex(OUTPUT_BLOB_NAME); 104 | 105 | assert(trt_ctx->inputIndex == 0); 106 | assert(trt_ctx->outputIndex == 1); 107 | // Create GPU buffers on device 108 | 109 | printf("yolov5_trt_create buffer ... \n"); 110 | CUDA_CHECK(cudaMalloc(&trt_ctx->buffers[trt_ctx->inputIndex], BATCH_SIZE * 3 * INPUT_H * INPUT_W * sizeof(float))); 111 | //cudaMalloc(&trt_ctx->buffers[trt_ctx->inputIndex], BATCH_SIZE * 3 * INPUT_H * INPUT_W * sizeof(float)); 112 | CUDA_CHECK(cudaMalloc(&trt_ctx->buffers[trt_ctx->outputIndex], BATCH_SIZE * OUTPUT_SIZE * sizeof(float))); 113 | //cudaMalloc(&trt_ctx->buffers[trt_ctx->outputIndex], BATCH_SIZE * OUTPUT_SIZE * sizeof(float)); 114 | // Create stream 115 | 116 | printf("yolov5_trt_create stream ... \n"); 117 | CUDA_CHECK(cudaStreamCreate(&trt_ctx->cuda_stream)); 118 | //cudaStreamCreate(&trt_ctx->cuda_stream); 119 | printf("yolov5_trt_create done ... \n"); 120 | return (void *)trt_ctx; 121 | 122 | 123 | } 124 | 125 | 126 | int yolov5_trt_detect(void *h, cv::Mat &img, float threshold,std::vector& det) 127 | { 128 | Yolov5TRTContext *trt_ctx; 129 | int i; 130 | int delay_preprocess; 131 | int delay_infer; 132 | 133 | trt_ctx = (Yolov5TRTContext *)h; 134 | 135 | 136 | trt_ctx->result_json_str[0] = 0; 137 | // whether det is empty , if not, empty det 138 | if (!det.empty()) det.clear(); 139 | if (img.empty()) return 0; 140 | 141 | auto start0 = std::chrono::system_clock::now(); 142 | 143 | //printf("yolov5_trt_detect start preprocess img \n"); 144 | cv::Mat pr_img = preprocess_img(img, INPUT_W, INPUT_H); 145 | //std::cout<<"after preprocess_img pr_img size:"<data[i] = (float)uc_pixel[2] / 255.0; 156 | trt_ctx->data[i + INPUT_H * INPUT_W] = (float)uc_pixel[1] / 255.0; 157 | trt_ctx->data[i + 2 * INPUT_H * INPUT_W] = (float)uc_pixel[0] / 255.0; 158 | uc_pixel += 3; 159 | ++i; 160 | } 161 | } 162 | auto end0 = std::chrono::system_clock::now(); 163 | 164 | delay_preprocess = std::chrono::duration_cast(end0 - start0).count(); 165 | 166 | // Run inference 167 | //printf("yolov5_trt_detect start do inference\n"); 168 | auto start = std::chrono::system_clock::now(); 169 | doInference(*trt_ctx->exe_context, trt_ctx->cuda_stream, trt_ctx->buffers, trt_ctx->data, trt_ctx->prob, BATCH_SIZE); 170 | 171 | auto end = std::chrono::system_clock::now(); 172 | delay_infer = std::chrono::duration_cast(end - start).count(); 173 | 174 | std::cout <<"delay_proress:" << delay_preprocess << "ms, " << "delay_infer:" << delay_infer << "ms" << std::endl; 175 | 176 | //printf("yolov5_trt_detect start do process infer result \n"); 177 | 178 | int fcount = 1; 179 | int str_len; 180 | std::vector> batch_res(1); 181 | auto& res = batch_res[0]; 182 | nms(res, &trt_ctx->prob[0], threshold, NMS_THRESH); 183 | 184 | 185 | i = 0; 186 | for(i = 0 ; i < res.size(); i++){ 187 | int x1, y1, x2, y2; 188 | int class_id; 189 | float conf; 190 | cv::Rect r = get_rect(img, res[i].bbox); 191 | DetectBox dd(r.x,r.y,r.x + r.width,r.y + r.height,(float)res[i].conf,(int)res[i].class_id); 192 | det.push_back(dd); 193 | } 194 | return 1; 195 | } 196 | 197 | 198 | void yolov5_trt_destroy(void *h) 199 | { 200 | Yolov5TRTContext *trt_ctx; 201 | 202 | trt_ctx = (Yolov5TRTContext *)h; 203 | 204 | // Release stream and buffers 205 | cudaStreamDestroy(trt_ctx->cuda_stream); 206 | CUDA_CHECK(cudaFree(trt_ctx->buffers[trt_ctx->inputIndex])); 207 | //cudaFree(trt_ctx->buffers[trt_ctx->inputIndex]); 208 | CUDA_CHECK(cudaFree(trt_ctx->buffers[trt_ctx->outputIndex])); 209 | //cudaFree(trt_ctx->buffers[trt_ctx->outputIndex]) 210 | // Destroy the engine 211 | trt_ctx->exe_context->destroy(); 212 | trt_ctx->engine->destroy(); 213 | trt_ctx->runtime->destroy(); 214 | 215 | delete trt_ctx->data; 216 | delete trt_ctx->prob; 217 | 218 | delete trt_ctx; 219 | 220 | } 221 | 222 | --------------------------------------------------------------------------------