commit 29d61f54abe2f344bed56b74277a0e10ffcc57dd Author: guanyuankai Date: Mon Nov 10 16:40:23 2025 +0800 yolo-sdk source code diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ed4a29f --- /dev/null +++ b/.gitignore @@ -0,0 +1,1045 @@ +##### Windows +# Windows thumbnail cache files +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +##### Linux +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +##### MacOS +# General +.DS_Store +.AppleDouble +.LSOverride + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +##### Android +# Built application files +*.apk +*.ap_ +*.aab + +# Files for the ART/Dalvik VM +*.dex + +# Java class files +*.class + +# Generated files +bin/ +gen/ +out/ +# Uncomment the following line in case you need and you don't have the release build type files in your app +# release/ + +# Gradle files +.gradle/ +build/ + +# Local configuration file (sdk path, etc) +local.properties + +# Proguard folder generated by Eclipse +proguard/ + +# Log Files +*.log + +# Android Studio Navigation editor temp files +.navigation/ + +# Android Studio captures folder +captures/ + +# IntelliJ +*.iml +.idea/workspace.xml +.idea/tasks.xml +.idea/gradle.xml +.idea/assetWizardSettings.xml +.idea/dictionaries +.idea/libraries +# Android Studio 3 in .gitignore file. +.idea/caches +.idea/modules.xml +# Comment next line if keeping position of elements in Navigation Editor is relevant for you +.idea/navEditor.xml + +# Keystore files +# Uncomment the following lines if you do not want to check your keystore files in. +#*.jks +#*.keystore + +# External native build folder generated in Android Studio 2.2 and later +.externalNativeBuild + +# Google Services (e.g. APIs or Firebase) +# google-services.json + +# Freeline +freeline.py +freeline/ +freeline_project_description.json + +# fastlane +fastlane/report.xml +fastlane/Preview.html +fastlane/screenshots +fastlane/test_output +fastlane/readme.md + +# Version control +vcs.xml + +# lint +lint/intermediates/ +lint/generated/ +lint/outputs/ +lint/tmp/ +# lint/reports/ + +##### Backup +*.bak +*.gho +*.ori +*.orig +*.tmp + +##### GPG +secring.* + +##### Dropbox +# Dropbox settings and caches +.dropbox +.dropbox.attr +.dropbox.cache + +##### SynopsysVCS +# Waveform formats +*.vcd +*.vpd +*.evcd +*.fsdb + +# Default name of the simulation executable. A different name can be +# specified with this switch (the associated daidir database name is +# also taken from here): -o / +simv + +# Generated for Verilog and VHDL top configs +simv.daidir/ +simv.db.dir/ + +# Infrastructure necessary to co-simulate SystemC models with +# Verilog/VHDL models. An alternate directory may be specified with this +# switch: -Mdir= +csrc/ + +# Log file - the following switch allows to specify the file that will be +# used to write all messages from simulation: -l +*.log + +# Coverage results (generated with urg) and database location. The +# following switch can also be used: urg -dir .vdb +simv.vdb/ +urgReport/ + +# DVE and UCLI related files. +DVEfiles/ +ucli.key + +# When the design is elaborated for DirectC, the following file is created +# with declarations for C/C++ functions. +vc_hdrs.h + +##### SVN +.svn/ + +##### Mercurial +.hg/ +.hgignore +.hgsigs +.hgsub +.hgsubstate +.hgtags + +##### Bazaar +.bzr/ +.bzrignore + +##### CVS +/CVS/* +**/CVS/* +.cvsignore +*/.cvsignore + +##### TortoiseGit +# Project-level settings +/.tgitconfig + +##### PuTTY +# Private key +*.ppk + +##### Vim +# Swap +[._]*.s[a-v][a-z] +!*.svg # comment out if you don't need vector files +[._]*.sw[a-p] +[._]s[a-rt-v][a-z] +[._]ss[a-gi-z] +[._]sw[a-p] + +# Session +Session.vim +Sessionx.vim + +# Temporary +.netrwhist +*~ +# Auto-generated tag files +tags +# Persistent undo +[._]*.un~ + +##### Emacs +# -*- mode: gitignore; -*- +*~ +\#*\# +/.emacs.desktop +/.emacs.desktop.lock +*.elc +auto-save-list +tramp +.\#* + +# Org-mode +.org-id-locations +*_archive + +# flymake-mode +*_flymake.* + +# eshell files +/eshell/history +/eshell/lastdir + +# elpa packages +/elpa/ + +# reftex files +*.rel + +# AUCTeX auto folder +/auto/ + +# cask packages +.cask/ +dist/ + +# Flycheck +flycheck_*.el + +# server auth directory +/server/ + +# projectiles files +.projectile + +# directory configuration +.dir-locals.el + +# network security +/network-security.data + +##### SublimeText +# Cache files for Sublime Text +*.tmlanguage.cache +*.tmPreferences.cache +*.stTheme.cache + +# Workspace files are user-specific +*.sublime-workspace + +# Project files should be checked into the repository, unless a significant +# proportion of contributors will probably not be using Sublime Text +# *.sublime-project + +# SFTP configuration file +sftp-config.json +sftp-config-alt*.json + +# Package control specific files +Package Control.last-run +Package Control.ca-list +Package Control.ca-bundle +Package Control.system-ca-bundle +Package Control.cache/ +Package Control.ca-certs/ +Package Control.merged-ca-bundle +Package Control.user-ca-bundle +oscrypto-ca-bundle.crt +bh_unicode_properties.cache + +# Sublime-github package stores a github token in this file +# https://packagecontrol.io/packages/sublime-github +GitHub.sublime-settings + +##### Notepad++ +# Notepad++ backups # +*.bak + +##### TextMate +*.tmproj +*.tmproject +tmtags + +##### VisualStudioCode +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +##### NetBeans +**/nbproject/private/ +**/nbproject/Makefile-*.mk +**/nbproject/Package-*.bash +build/ +nbbuild/ +dist/ +nbdist/ +.nb-gradle/ + +##### JetBrains +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +##### Eclipse +.metadata +bin/ +tmp/ +*.tmp +*.bak +*.swp +*~.nib +local.properties +.settings/ +.loadpath +.recommenders + +# External tool builders +.externalToolBuilders/ + +# Locally stored "Eclipse launch configurations" +*.launch + +# PyDev specific (Python IDE for Eclipse) +*.pydevproject + +# CDT-specific (C/C++ Development Tooling) +.cproject + +# CDT- autotools +.autotools + +# Java annotation processor (APT) +.factorypath + +# PDT-specific (PHP Development Tools) +.buildpath + +# sbteclipse plugin +.target + +# Tern plugin +.tern-project + +# TeXlipse plugin +.texlipse + +# STS (Spring Tool Suite) +.springBeans + +# Code Recommenders +.recommenders/ + +# Annotation Processing +.apt_generated/ +.apt_generated_test/ + +# Scala IDE specific (Scala & Java development for Eclipse) +.cache-main +.scala_dependencies +.worksheet + +# Uncomment this line if you wish to ignore the project description file. +# Typically, this file would be tracked if it contains build/dependency configurations: +#.project + +##### Qt +# C++ objects and libs +*.slo +*.lo +*.o +*.a +*.la +*.lai +*.so +*.so.* +*.dll +*.dylib + +# Qt-es +object_script.*.Release +object_script.*.Debug +*_plugin_import.cpp +/.qmake.cache +/.qmake.stash +*.pro.user +*.pro.user.* +*.qbs.user +*.qbs.user.* +*.moc +moc_*.cpp +moc_*.h +qrc_*.cpp +ui_*.h +*.qmlc +*.jsc +Makefile* +*build-* +*.qm +*.prl + +# Qt unit tests +target_wrapper.* + +# QtCreator +*.autosave + +# QtCreator Qml +*.qmlproject.user +*.qmlproject.user.* + +# QtCreator CMake +CMakeLists.txt.user* + +# QtCreator 4.8< compilation database +compile_commands.json + +# QtCreator local machine specific files for imported projects +*creator.user* + +##### VisualStudio +##### VisualStudio +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*[.json, .xml, .info] + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +##### Gradle +.gradle +**/build/ +!src/**/build/ + +# Ignore Gradle GUI config +gradle-app.setting + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar + +# Cache of project +.gradletasknamecache + +# # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 +# gradle/wrapper/gradle-wrapper.properties + +##### CMake +CMakeLists.txt.user +CMakeCache.txt +CMakeFiles +CMakeScripts +Testing +Makefile +cmake_install.cmake +install_manifest.txt +compile_commands.json +CTestTestfile.cmake +_deps + +##### C++ +# Prerequisites +*.d + +# Compiled Object files +*.slo +*.lo +*.o +*.obj + +# Precompiled Headers +*.gch +*.pch + +# Compiled Dynamic libraries +*.so +*.dylib +*.dll + +# Fortran module files +*.mod +*.smod + +# Compiled Static libraries +*.lai +*.la +*.a +*.lib + +# Executables +*.exe +*.out +*.app + +# C/C++ binary extension file +*.bin + +##### C +# Prerequisites +*.d + +# Object files +*.o +*.ko +*.obj +*.elf + +# Linker output +*.ilk +*.map +*.exp + +# Precompiled Headers +*.gch +*.pch + +# Libraries +*.lib +*.a +*.la +*.lo + +# Shared objects (inc. Windows DLLs) +*.dll +*.so +*.so.* +*.dylib + +# Executables +*.exe +*.out +*.app +*.i*86 +*.x86_64 +*.hex + +# Debug files +*.dSYM/ +*.su +*.idb +*.pdb + +# Kernel Module Compile Results +*.mod* +*.cmd +.tmp_versions/ +modules.order +Module.symvers +Mkfile.old +dkms.conf + +# Raspberry Pi Pico Object file +*.uf2 +# Raspberry Pi Pico disassembler file +*.dis \ No newline at end of file diff --git a/TestApp/TestApp.cpp b/TestApp/TestApp.cpp new file mode 100644 index 0000000..58cd1e4 --- /dev/null +++ b/TestApp/TestApp.cpp @@ -0,0 +1,106 @@ +#include +#include +#include "../Yolo11_ONNX/Yolo_ONNX.h" // 包含DLL的头文件 + +int main() +{ + // --- 1. 准备输入和参数 --- + const wchar_t* model_path = L"D:/dev/models/best.onnx"; + cv::Mat image = cv::imread("D:/dev/dataset/003.jpg"); + + if (image.empty()) { + std::cerr << "Error: Could not read the image." << std::endl; + return -1; + } + + // 【新增】将所有可配置参数定义在这里,方便修改 + const float conf_threshold = 0.9f; + const float iou_threshold = 0.45f; + const int input_width = 2016; + const int input_height = 1536; + + const char* class_names[] = { /* ... 您的类别列表 ... */ "tiaojuan", "zhujiesi", "yulingwen" }; // 示例 + int class_count = sizeof(class_names) / sizeof(class_names[0]); + + // --- 2. 调用更新后的DLL函数 --- + Detection* detections = nullptr; + int detections_count = 0; + + std::cout << "Performing detection with conf=" << conf_threshold << ", iou=" << iou_threshold << ", size=" << input_width << "x" << input_height << std::endl; + + int result = perform_detection( + model_path, + image.data, + image.cols, + image.rows, + &detections, + &detections_count, + class_names, + class_count, + conf_threshold, + iou_threshold, + input_width, + input_height + ); + + if (result != 0) { + std::cerr << "Detection failed with code: " << result << std::endl; + free_memory(detections); + return -1; + } + + std::cout << "Detection successful. Found " << detections_count << " objects." << std::endl; + + // --- 3. 打印检测结果 --- + for (int i = 0; i < detections_count; ++i) { + const auto& d = detections[i]; + std::cout << " - Class: " << class_names[d.class_id] + << ", Score: " << d.score + << ", Box: [" << d.x << ", " << d.y << ", " << d.width << ", " << d.height << "]" << std::endl; + } + + // --- 4. 调用DLL函数绘制结果并显示 --- + unsigned char* output_image_bytes = nullptr; + int output_image_size = 0; + + draw_and_encode_image( + image.data, + image.cols, + image.rows, + detections, + detections_count, + class_names, + class_count, + &output_image_bytes, + &output_image_size + ); + + if (output_image_bytes && output_image_size > 0) { + std::vector buffer(output_image_bytes, output_image_bytes + output_image_size); + cv::Mat result_image = cv::imdecode(buffer, cv::IMREAD_COLOR); + + // 定义要保存的文件名 + std::string output_filename = "detection_result.jpg"; + + // 使用 OpenCV 的 imwrite 函数将图片保存到硬盘 + bool success = cv::imwrite(output_filename, result_image); + + // 检查是否保存成功并打印提示信息 + if (success) { + std::cout << "Annotated image successfully saved to: " << output_filename << std::endl; + } + else { + std::cerr << "Error: Failed to save the annotated image." << std::endl; + } + } + + + // --- 5. 释放内存 --- + std::cout << "Freeing memory..." << std::endl; + free_memory(detections); + free_image_memory(output_image_bytes); + + std::cout << "Done." << std::endl; + + return 0; +} \ No newline at end of file diff --git a/TestApp/TestApp.vcxproj b/TestApp/TestApp.vcxproj new file mode 100644 index 0000000..02309e0 --- /dev/null +++ b/TestApp/TestApp.vcxproj @@ -0,0 +1,142 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 17.0 + Win32Proj + {4c95ea00-3099-4ab8-bf38-8927e561d281} + TestApp + 10.0 + + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + + + + + + + + + + + + + + + + + + + D:\dev\vcpkg\installed\x64-windows\include\opencv4;$(IncludePath) + D:\dev\vcpkg\installed\x64-windows\lib;$(LibraryPath) + false + + + + Level3 + true + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + true + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + $(SolutionDir)Yolo11_ONNX;%(AdditionalIncludeDirectories) + + + Console + true + + + + + + + + {7efe33a8-28e8-407b-bf53-6d1e34e537da} + + + + + + \ No newline at end of file diff --git a/TestApp/TestApp.vcxproj.filters b/TestApp/TestApp.vcxproj.filters new file mode 100644 index 0000000..047243a --- /dev/null +++ b/TestApp/TestApp.vcxproj.filters @@ -0,0 +1,22 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + 源文件 + + + \ No newline at end of file diff --git a/TestApp/detection_result.jpg b/TestApp/detection_result.jpg new file mode 100644 index 0000000..582c0eb Binary files /dev/null and b/TestApp/detection_result.jpg differ diff --git a/Yolo11_ONNX.sln b/Yolo11_ONNX.sln new file mode 100644 index 0000000..44600a5 --- /dev/null +++ b/Yolo11_ONNX.sln @@ -0,0 +1,41 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.14.36327.8 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Yolo11_ONNX", "Yolo11_ONNX\Yolo11_ONNX.vcxproj", "{7EFE33A8-28E8-407B-BF53-6D1E34E537DA}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestApp", "TestApp\TestApp.vcxproj", "{4C95EA00-3099-4AB8-BF38-8927E561D281}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {7EFE33A8-28E8-407B-BF53-6D1E34E537DA}.Debug|x64.ActiveCfg = Debug|x64 + {7EFE33A8-28E8-407B-BF53-6D1E34E537DA}.Debug|x64.Build.0 = Debug|x64 + {7EFE33A8-28E8-407B-BF53-6D1E34E537DA}.Debug|x86.ActiveCfg = Debug|Win32 + {7EFE33A8-28E8-407B-BF53-6D1E34E537DA}.Debug|x86.Build.0 = Debug|Win32 + {7EFE33A8-28E8-407B-BF53-6D1E34E537DA}.Release|x64.ActiveCfg = Release|x64 + {7EFE33A8-28E8-407B-BF53-6D1E34E537DA}.Release|x64.Build.0 = Release|x64 + {7EFE33A8-28E8-407B-BF53-6D1E34E537DA}.Release|x86.ActiveCfg = Release|Win32 + {7EFE33A8-28E8-407B-BF53-6D1E34E537DA}.Release|x86.Build.0 = Release|Win32 + {4C95EA00-3099-4AB8-BF38-8927E561D281}.Debug|x64.ActiveCfg = Debug|x64 + {4C95EA00-3099-4AB8-BF38-8927E561D281}.Debug|x64.Build.0 = Debug|x64 + {4C95EA00-3099-4AB8-BF38-8927E561D281}.Debug|x86.ActiveCfg = Debug|Win32 + {4C95EA00-3099-4AB8-BF38-8927E561D281}.Debug|x86.Build.0 = Debug|Win32 + {4C95EA00-3099-4AB8-BF38-8927E561D281}.Release|x64.ActiveCfg = Release|x64 + {4C95EA00-3099-4AB8-BF38-8927E561D281}.Release|x64.Build.0 = Release|x64 + {4C95EA00-3099-4AB8-BF38-8927E561D281}.Release|x86.ActiveCfg = Release|Win32 + {4C95EA00-3099-4AB8-BF38-8927E561D281}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {23D8EE17-32AF-4992-8F1D-A9743659AD0A} + EndGlobalSection +EndGlobal diff --git a/Yolo11_ONNX/Yolo11_ONNX.vcxproj b/Yolo11_ONNX/Yolo11_ONNX.vcxproj new file mode 100644 index 0000000..6ff9cc5 --- /dev/null +++ b/Yolo11_ONNX/Yolo11_ONNX.vcxproj @@ -0,0 +1,169 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 17.0 + Win32Proj + {7efe33a8-28e8-407b-bf53-6d1e34e537da} + Yolo11ONNX + 10.0 + Yolo_ONNX + + + + DynamicLibrary + true + v143 + Unicode + + + DynamicLibrary + false + v143 + true + Unicode + + + DynamicLibrary + true + v143 + Unicode + + + DynamicLibrary + false + v143 + true + Unicode + + + + + + + + + + + + + + + + + + + + + D:\dev\onnxruntime-win-x64-gpu-1.22.1\include;$(VC_IncludePath);$(WindowsSDK_IncludePath);D:\dev\vcpkg\installed\x64-windows\include;D:\dev\vcpkg\installed\x64-windows\include\opencv4 + D:\dev\onnxruntime-win-x64-gpu-1.22.1\lib;D:\dev\vcpkg\installed\x64-windows\lib;$(LibraryPath) + + + D:\dev\onnxruntime-win-x64-gpu-1.22.1\include;D:\dev\vcpkg\installed\x64-windows\include\opencv4;$(IncludePath) + D:\dev\onnxruntime-win-x64-gpu-1.22.1\lib;D:\dev\vcpkg\installed\x64-windows\lib;$(LibraryPath) + + + + Level3 + true + WIN32;_DEBUG;YOLO11ONNX_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) + true + Use + pch.h + + + Windows + true + false + + + + + Level3 + true + true + true + WIN32;NDEBUG;YOLO11ONNX_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) + true + Use + pch.h + + + Windows + true + false + + + + + Level3 + true + _DEBUG;YOLO11ONNX_EXPORTS;_WINDOWS;_USRDLL;USE_CUDA;YOLO_EXPORTS;%(PreprocessorDefinitions) + true + Use + pch.h + + + Windows + true + false + onnxruntime.lib;%(AdditionalDependencies) + + + + + Level3 + true + true + true + NDEBUG;YOLO11ONNX_EXPORTS;_WINDOWS;_USRDLL;YOLO_EXPORTS;%(PreprocessorDefinitions) + true + Use + pch.h + + + Windows + true + false + onnxruntime.lib;%(AdditionalDependencies) + + + + + + + + + + + Create + Create + Create + Create + + + + + + + + + + \ No newline at end of file diff --git a/Yolo11_ONNX/Yolo11_ONNX.vcxproj.filters b/Yolo11_ONNX/Yolo11_ONNX.vcxproj.filters new file mode 100644 index 0000000..c2755f3 --- /dev/null +++ b/Yolo11_ONNX/Yolo11_ONNX.vcxproj.filters @@ -0,0 +1,42 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + 头文件 + + + 头文件 + + + 头文件 + + + + + 源文件 + + + 源文件 + + + 源文件 + + + + + + \ No newline at end of file diff --git a/Yolo11_ONNX/Yolo_ONNX.cpp b/Yolo11_ONNX/Yolo_ONNX.cpp new file mode 100644 index 0000000..5c09afe --- /dev/null +++ b/Yolo11_ONNX/Yolo_ONNX.cpp @@ -0,0 +1,217 @@ +// YoloV8_ONNX.cpp (Ż) + +#include "pch.h" +#include "Yolo_ONNX.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace { + + // ŻԤ + cv::Mat preprocess(const cv::Mat& img, int target_width, int target_height, int& pad_w, int& pad_h, float& scale) { + cv::Mat resized_img; + int w = img.cols; + int h = img.rows; + scale = std::min(static_cast(target_width) / w, static_cast(target_height) / h); + int new_w = static_cast(w * scale); + int new_h = static_cast(h * scale); + + // Żʹ INTER_AREA ֵ㷨ʺͼСPythonΪӽ + cv::resize(img, resized_img, cv::Size(new_w, new_h), 0, 0, cv::INTER_AREA); + + pad_w = target_width - new_w; + pad_h = target_height - new_h; + cv::Mat padded_img; + cv::copyMakeBorder(resized_img, padded_img, 0, pad_h, 0, pad_w, cv::BORDER_CONSTANT, cv::Scalar(114, 114, 114)); + return padded_img; + } + + // + std::vector postprocess(Ort::Value& output_tensor, float scale, int pad_w, int pad_h, int img_w, int img_h, float conf_threshold, float iou_threshold) { + const auto output_shape = output_tensor.GetTensorTypeAndShapeInfo().GetShape(); + const float* raw_output = output_tensor.GetTensorData(); + int num_classes = static_cast(output_shape[1]) - 4; + int num_proposals = static_cast(output_shape[2]); + + std::vector boxes; + std::vector scores; + std::vector class_ids; + + cv::Mat raw_data_mat(num_classes + 4, num_proposals, CV_32F, (void*)raw_output); + raw_data_mat = raw_data_mat.t(); + + for (int i = 0; i < num_proposals; ++i) { + const float* proposal = raw_data_mat.ptr(i); + const float* class_scores = proposal + 4; + float max_score = 0.0f; + int class_id = -1; + for (int j = 0; j < num_classes; ++j) { + if (class_scores[j] > max_score) { + max_score = class_scores[j]; + class_id = j; + } + } + if (max_score > conf_threshold) { + float cx = proposal[0]; + float cy = proposal[1]; + float w = proposal[2]; + float h = proposal[3]; + int left = static_cast((cx - w / 2 - (pad_w / 2.0f)) / scale); + int top = static_cast((cy - h / 2 - (pad_h / 2.0f)) / scale); + int width = static_cast(w / scale); + int height = static_cast(h / scale); + left = std::max(0, std::min(left, img_w - 1)); + top = std::max(0, std::min(top, img_h - 1)); + width = std::min(width, img_w - left); + height = std::min(height, img_h - top); + boxes.push_back(cv::Rect(left, top, width, height)); + scores.push_back(max_score); + class_ids.push_back(class_id); + } + } + + std::vector nms_result; + cv::dnn::NMSBoxes(boxes, scores, conf_threshold, iou_threshold, nms_result); + std::vector detections; + for (int idx : nms_result) { + detections.push_back({ class_ids[idx], scores[idx], boxes[idx].x, boxes[idx].y, boxes[idx].width, boxes[idx].height }); + } + return detections; + } +} + + +extern "C" { + // ޸ġǩ£ĸ² + YOLO_API int perform_detection( + const wchar_t* model_path, + unsigned char* image_bytes, + int image_width, + int image_height, + Detection** out_detections, + int* out_detections_count, + const char** class_names, + int class_names_count, + float conf_threshold, // ʹôŶֵ + float iou_threshold, // ʹôIOUֵ + int input_width, // ʹôģ + int input_height // ʹôģ߶ + ) { + static Ort::Env env(ORT_LOGGING_LEVEL_WARNING, "YOLOv8-ONNX-GPU"); + static std::unique_ptr session = nullptr; + // жģǷҪ¼صı + static std::wstring current_model_path = L""; + + try { + // ģ·仯´Session + if (!session || current_model_path != model_path) { + Ort::SessionOptions session_options; + OrtCUDAProviderOptions cuda_options; + session_options.AppendExecutionProvider_CUDA(cuda_options); + session = std::make_unique(env, model_path, session_options); + current_model_path = model_path; + } + + // ޸ġƳӲijߴ磬ʹýӿڴIJ + std::vector input_shape = { 1, 3, input_height, input_width }; + + Ort::AllocatorWithDefaultOptions allocator; + std::string input_name_str = session->GetInputNameAllocated(0, allocator).get(); + std::vector input_node_names = { input_name_str.c_str() }; + + std::string output_name_str = session->GetOutputNameAllocated(0, allocator).get(); + std::vector output_node_names = { output_name_str.c_str() }; + + cv::Mat image(image_height, image_width, CV_8UC3, image_bytes); + if (image.empty()) return -1; + + int pad_w, pad_h; + float scale; + // ޸ġʹýӿڴIJԤ + cv::Mat preprocessed_img = preprocess(image, input_width, input_height, pad_w, pad_h, scale); + + cv::Mat blob; + cv::dnn::blobFromImage(preprocessed_img, blob, 1 / 255.0, cv::Size(), cv::Scalar(), false, false); + + auto memory_info = Ort::MemoryInfo::CreateCpu(OrtArenaAllocator, OrtMemTypeDefault); + Ort::Value input_tensor = Ort::Value::CreateTensor(memory_info, blob.ptr(), blob.total(), input_shape.data(), input_shape.size()); + auto output_tensors = session->Run(Ort::RunOptions{ nullptr }, input_node_names.data(), &input_tensor, 1, output_node_names.data(), 1); + + // ޸ġʹýӿڴIJк + std::vector detections = postprocess(output_tensors[0], scale, pad_w, pad_h, image_width, image_height, conf_threshold, iou_threshold); + + *out_detections_count = static_cast(detections.size()); + if (*out_detections_count > 0) { + *out_detections = new Detection[*out_detections_count]; + std::copy(detections.begin(), detections.end(), *out_detections); + } + else { + *out_detections = nullptr; + } + } + catch (const Ort::Exception& e) { + std::cerr << "ONNX Runtime 쳣: " << e.what() << std::endl; + return -2; + } + catch (const cv::Exception& e) { + std::cerr << "OpenCV 쳣: " << e.what() << std::endl; + return -3; + } + catch (const std::exception& e) { + std::cerr << "׼쳣: " << e.what() << std::endl; + return -4; + } + return 0; + } + + // ºֲ + YOLO_API void free_memory(Detection* detections) { + delete[] detections; + } + + YOLO_API void draw_and_encode_image( + unsigned char* image_bytes, + int image_width, + int image_height, + const Detection* detections, + int detections_count, + const char** class_names, + int class_names_count, + unsigned char** out_image_bytes, + int* out_image_size) { + + cv::Mat image(image_height, image_width, CV_8UC3, image_bytes); + if (image.empty()) { + *out_image_bytes = nullptr; + *out_image_size = 0; + return; + } + + for (int i = 0; i < detections_count; ++i) { + const auto& d = detections[i]; + cv::rectangle(image, cv::Rect(d.x, d.y, d.width, d.height), cv::Scalar(0, 255, 0), 2); + std::string label = "Unknown"; + if (d.class_id >= 0 && d.class_id < class_names_count) { + label = class_names[d.class_id]; + } + label += " " + std::to_string(d.score).substr(0, 4); + cv::putText(image, label, cv::Point(d.x, d.y - 10), cv::FONT_HERSHEY_SIMPLEX, 0.8, cv::Scalar(0, 255, 0), 2); + } + + std::vector buf; + cv::imencode(".jpg", image, buf); + *out_image_size = static_cast(buf.size()); + *out_image_bytes = new unsigned char[*out_image_size]; + std::copy(buf.begin(), buf.end(), *out_image_bytes); + } + + YOLO_API void free_image_memory(unsigned char* image_bytes) { + delete[] image_bytes; + } +} \ No newline at end of file diff --git a/Yolo11_ONNX/Yolo_ONNX.h b/Yolo11_ONNX/Yolo_ONNX.h new file mode 100644 index 0000000..4de853f --- /dev/null +++ b/Yolo11_ONNX/Yolo_ONNX.h @@ -0,0 +1,52 @@ +#pragma once + +#ifdef YOLO_EXPORTS +#define YOLO_API __declspec(dllexport) +#else +#define YOLO_API __declspec(dllimport) +#endif + +#include + +struct Detection +{ + int class_id; + float score; + int x; + int y; + int width; + int height; +}; + +extern "C" { + YOLO_API int perform_detection( + const wchar_t* model_path, + unsigned char* image_bytes, + int image_width, + int image_height, + Detection** out_detections, + int* out_detections_count, + const char** class_names, + int class_names_count, + float conf_threshold, // Ŷֵ ( 0.5f) + float iou_threshold, // NMSIOUֵ ( 0.5f) + int input_width, // ģ ( 640) + int input_height // ģ߶ ( 640) + ); + + YOLO_API void free_memory(Detection* detections); + + YOLO_API void draw_and_encode_image( + unsigned char* image_bytes, + int image_width, + int image_height, + const Detection* detections, + int detections_count, + const char** class_names, + int class_names_count, + unsigned char** out_image_bytes, + int* out_image_size + ); + + YOLO_API void free_image_memory(unsigned char* image_bytes); +} \ No newline at end of file diff --git a/Yolo11_ONNX/cpp.hint b/Yolo11_ONNX/cpp.hint new file mode 100644 index 0000000..e3f594b --- /dev/null +++ b/Yolo11_ONNX/cpp.hint @@ -0,0 +1,5 @@ +// 提示文件帮助 Visual Studio IDE 解释 Visual C++ 标识符, +// 如函数和宏的名称。 +// 有关详细信息,请参见 https://go.microsoft.com/fwlink/?linkid=865984 +#define YOLO_API __declspec(dllexport) +#define YOLO_API __declspec(dllimport) diff --git a/Yolo11_ONNX/dllmain.cpp b/Yolo11_ONNX/dllmain.cpp new file mode 100644 index 0000000..fbe711b --- /dev/null +++ b/Yolo11_ONNX/dllmain.cpp @@ -0,0 +1,19 @@ +// dllmain.cpp : 定义 DLL 应用程序的入口点。 +#include "pch.h" + +BOOL APIENTRY DllMain( HMODULE hModule, + DWORD ul_reason_for_call, + LPVOID lpReserved + ) +{ + switch (ul_reason_for_call) + { + case DLL_PROCESS_ATTACH: + case DLL_THREAD_ATTACH: + case DLL_THREAD_DETACH: + case DLL_PROCESS_DETACH: + break; + } + return TRUE; +} + diff --git a/Yolo11_ONNX/framework.h b/Yolo11_ONNX/framework.h new file mode 100644 index 0000000..80cbbc9 --- /dev/null +++ b/Yolo11_ONNX/framework.h @@ -0,0 +1,5 @@ +#pragma once + +#define WIN32_LEAN_AND_MEAN // 从 Windows 头文件中排除极少使用的内容 +// Windows 头文件 +#include diff --git a/Yolo11_ONNX/pch.cpp b/Yolo11_ONNX/pch.cpp new file mode 100644 index 0000000..b6fb8f4 --- /dev/null +++ b/Yolo11_ONNX/pch.cpp @@ -0,0 +1,5 @@ +// pch.cpp: 与预编译标头对应的源文件 + +#include "pch.h" + +// 当使用预编译的头时,需要使用此源文件,编译才能成功。 diff --git a/Yolo11_ONNX/pch.h b/Yolo11_ONNX/pch.h new file mode 100644 index 0000000..9660927 --- /dev/null +++ b/Yolo11_ONNX/pch.h @@ -0,0 +1,13 @@ +// pch.h: 这是预编译标头文件。 +// 下方列出的文件仅编译一次,提高了将来生成的生成性能。 +// 这还将影响 IntelliSense 性能,包括代码完成和许多代码浏览功能。 +// 但是,如果此处列出的文件中的任何一个在生成之间有更新,它们全部都将被重新编译。 +// 请勿在此处添加要频繁更新的文件,这将使得性能优势无效。 + +#ifndef PCH_H +#define PCH_H + +// 添加要在此处预编译的标头 +#include "framework.h" + +#endif //PCH_H diff --git a/tree.txt b/tree.txt new file mode 100644 index 0000000..54bf3aa Binary files /dev/null and b/tree.txt differ