yolo-sdk source code

This commit is contained in:
guanyuankai 2025-11-10 16:40:23 +08:00
commit 29d61f54ab
16 changed files with 1883 additions and 0 deletions

1045
.gitignore vendored Normal file

File diff suppressed because it is too large Load Diff

106
TestApp/TestApp.cpp Normal file
View File

@ -0,0 +1,106 @@
#include <iostream>
#include <opencv2/opencv.hpp>
#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<unsigned char> 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;
}

142
TestApp/TestApp.vcxproj Normal file
View File

@ -0,0 +1,142 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>17.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{4c95ea00-3099-4ab8-bf38-8927e561d281}</ProjectGuid>
<RootNamespace>TestApp</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<IncludePath>D:\dev\vcpkg\installed\x64-windows\include\opencv4;$(IncludePath)</IncludePath>
<LibraryPath>D:\dev\vcpkg\installed\x64-windows\lib;$(LibraryPath)</LibraryPath>
<PostBuildEventUseInBuild>false</PostBuildEventUseInBuild>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>$(SolutionDir)Yolo11_ONNX;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="TestApp.cpp" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Yolo11_ONNX\Yolo11_ONNX.vcxproj">
<Project>{7efe33a8-28e8-407b-bf53-6d1e34e537da}</Project>
</ProjectReference>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="源文件">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="头文件">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="资源文件">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="TestApp.cpp">
<Filter>源文件</Filter>
</ClCompile>
</ItemGroup>
</Project>

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 MiB

41
Yolo11_ONNX.sln Normal file
View File

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

View File

@ -0,0 +1,169 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>17.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{7efe33a8-28e8-407b-bf53-6d1e34e537da}</ProjectGuid>
<RootNamespace>Yolo11ONNX</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
<ProjectName>Yolo_ONNX</ProjectName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<IncludePath>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</IncludePath>
<LibraryPath>D:\dev\onnxruntime-win-x64-gpu-1.22.1\lib;D:\dev\vcpkg\installed\x64-windows\lib;$(LibraryPath)</LibraryPath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<IncludePath>D:\dev\onnxruntime-win-x64-gpu-1.22.1\include;D:\dev\vcpkg\installed\x64-windows\include\opencv4;$(IncludePath)</IncludePath>
<LibraryPath>D:\dev\onnxruntime-win-x64-gpu-1.22.1\lib;D:\dev\vcpkg\installed\x64-windows\lib;$(LibraryPath)</LibraryPath>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;YOLO11ONNX_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<PrecompiledHeader>Use</PrecompiledHeader>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableUAC>false</EnableUAC>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;YOLO11ONNX_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<PrecompiledHeader>Use</PrecompiledHeader>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableUAC>false</EnableUAC>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;YOLO11ONNX_EXPORTS;_WINDOWS;_USRDLL;USE_CUDA;YOLO_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<PrecompiledHeader>Use</PrecompiledHeader>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableUAC>false</EnableUAC>
<AdditionalDependencies>onnxruntime.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;YOLO11ONNX_EXPORTS;_WINDOWS;_USRDLL;YOLO_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<PrecompiledHeader>Use</PrecompiledHeader>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableUAC>false</EnableUAC>
<AdditionalDependencies>onnxruntime.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="framework.h" />
<ClInclude Include="pch.h" />
<ClInclude Include="Yolo_ONNX.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="dllmain.cpp" />
<ClCompile Include="pch.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Create</PrecompiledHeader>
</ClCompile>
<ClCompile Include="Yolo_ONNX.cpp" />
</ItemGroup>
<ItemGroup>
<None Include="cpp.hint" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,42 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="源文件">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="头文件">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="资源文件">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClInclude Include="framework.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="pch.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="Yolo_ONNX.h">
<Filter>头文件</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="dllmain.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="pch.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="Yolo_ONNX.cpp">
<Filter>源文件</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<None Include="cpp.hint" />
</ItemGroup>
</Project>

217
Yolo11_ONNX/Yolo_ONNX.cpp Normal file
View File

@ -0,0 +1,217 @@
// YoloV8_ONNX.cpp (最终优化版)
#include "pch.h"
#include "Yolo_ONNX.h"
#include <onnxruntime_c_api.h>
#include <onnxruntime_cxx_api.h>
#include <opencv2/opencv.hpp>
#include <vector>
#include <string>
#include <iostream>
#include <memory>
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<float>(target_width) / w, static_cast<float>(target_height) / h);
int new_w = static_cast<int>(w * scale);
int new_h = static_cast<int>(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<Detection> 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<float>();
int num_classes = static_cast<int>(output_shape[1]) - 4;
int num_proposals = static_cast<int>(output_shape[2]);
std::vector<cv::Rect> boxes;
std::vector<float> scores;
std::vector<int> 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<float>(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<int>((cx - w / 2 - (pad_w / 2.0f)) / scale);
int top = static_cast<int>((cy - h / 2 - (pad_h / 2.0f)) / scale);
int width = static_cast<int>(w / scale);
int height = static_cast<int>(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<int> nms_result;
cv::dnn::NMSBoxes(boxes, scores, conf_threshold, iou_threshold, nms_result);
std::vector<Detection> 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<Ort::Session> 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<Ort::Session>(env, model_path, session_options);
current_model_path = model_path;
}
// 【修改】移除硬编码的尺寸,使用接口传入的参数
std::vector<int64_t> input_shape = { 1, 3, input_height, input_width };
Ort::AllocatorWithDefaultOptions allocator;
std::string input_name_str = session->GetInputNameAllocated(0, allocator).get();
std::vector<const char*> input_node_names = { input_name_str.c_str() };
std::string output_name_str = session->GetOutputNameAllocated(0, allocator).get();
std::vector<const char*> 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;
// 【修改】使用接口传入的参数进行预处理
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<float>(memory_info, blob.ptr<float>(), 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);
// 【修改】使用接口传入的参数进行后处理
std::vector<Detection> detections = postprocess(output_tensors[0], scale, pad_w, pad_h, image_width, image_height, conf_threshold, iou_threshold);
*out_detections_count = static_cast<int>(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<unsigned char> buf;
cv::imencode(".jpg", image, buf);
*out_image_size = static_cast<int>(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;
}
}

52
Yolo11_ONNX/Yolo_ONNX.h Normal file
View File

@ -0,0 +1,52 @@
#pragma once
#ifdef YOLO_EXPORTS
#define YOLO_API __declspec(dllexport)
#else
#define YOLO_API __declspec(dllimport)
#endif
#include <vector>
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, // NMS的IOU阈值 (例如 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);
}

5
Yolo11_ONNX/cpp.hint Normal file
View File

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

19
Yolo11_ONNX/dllmain.cpp Normal file
View File

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

5
Yolo11_ONNX/framework.h Normal file
View File

@ -0,0 +1,5 @@
#pragma once
#define WIN32_LEAN_AND_MEAN // 从 Windows 头文件中排除极少使用的内容
// Windows 头文件
#include <windows.h>

5
Yolo11_ONNX/pch.cpp Normal file
View File

@ -0,0 +1,5 @@
// pch.cpp: 与预编译标头对应的源文件
#include "pch.h"
// 当使用预编译的头时,需要使用此源文件,编译才能成功。

13
Yolo11_ONNX/pch.h Normal file
View File

@ -0,0 +1,13 @@
// pch.h: 这是预编译标头文件。
// 下方列出的文件仅编译一次,提高了将来生成的生成性能。
// 这还将影响 IntelliSense 性能,包括代码完成和许多代码浏览功能。
// 但是,如果此处列出的文件中的任何一个在生成之间有更新,它们全部都将被重新编译。
// 请勿在此处添加要频繁更新的文件,这将使得性能优势无效。
#ifndef PCH_H
#define PCH_H
// 添加要在此处预编译的标头
#include "framework.h"
#endif //PCH_H

BIN
tree.txt Normal file

Binary file not shown.