diff --git a/.gitignore b/.gitignore index b268868c025..39783b88395 100644 --- a/.gitignore +++ b/.gitignore @@ -9,4 +9,6 @@ build-debug.sh *dist fastdeploy.egg-info .setuptools-cmake-build -fastdeploy/version.py \ No newline at end of file +fastdeploy/version.py +fastdeploy/LICENSE* +fastdeploy/ThirdPartyNotices* \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt index 3b3a508f55e..a8d451e02f0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -38,6 +38,9 @@ option(ENABLE_VISION_VISUALIZE "if to enable visualize vision model result toolb option(ENABLE_OPENCV_CUDA "if to enable opencv with cuda, this will allow process image with GPU." OFF) option(ENABLE_DEBUG "if to enable print debug information, this may reduce performance." OFF) +# Whether to build fastdeply with vision/text/... examples, only for testings. +option(WITH_VISION_EXAMPLES "Whether to build fastdeply with vision examples" ON) + if(ENABLE_DEBUG) add_definitions(-DFASTDEPLOY_DEBUG) endif() @@ -50,6 +53,13 @@ option(BUILD_FASTDEPLOY_PYTHON "if build python lib for fastdeploy." OFF) include_directories(${PROJECT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) +if (WTIH_VISION_EXAMPLES AND EXISTS ${PROJECT_SOURCE_DIR}/examples) + # ENABLE_VISION and ENABLE_VISION_VISUALIZE must be ON if enable vision examples. + message(STATUS "Found WTIH_VISION_EXAMPLES ON, so, force ENABLE_VISION and ENABLE_VISION_VISUALIZE ON") + set(ENABLE_VISION ON CACHE BOOL "force to enable vision models usage" FORCE) + set(ENABLE_VISION_VISUALIZE ON CACHE BOOL "force to enable visualize vision model result toolbox" FORCE) +endif() + add_definitions(-DFASTDEPLOY_LIB) file(GLOB_RECURSE ALL_DEPLOY_SRCS ${PROJECT_SOURCE_DIR}/fastdeploy/*.cc) file(GLOB_RECURSE DEPLOY_ORT_SRCS ${PROJECT_SOURCE_DIR}/fastdeploy/backends/ort/*.cc) @@ -131,6 +141,11 @@ if(ENABLE_VISION) if(ENABLE_VISION_VISUALIZE) add_definitions(-DENABLE_VISION_VISUALIZE) endif() +else() + if(ENABLE_VISION_VISUALIZE) + message("While ENABLE_VISION=OFF, will force ENABLE_VISION_VISUALIZE=OFF.") + set(ENABLE_VISION_VISUALIZE OFF) + endif() endif() configure_file(${PROJECT_SOURCE_DIR}/fastdeploy/core/config.h.in ${PROJECT_SOURCE_DIR}/fastdeploy/core/config.h) @@ -165,6 +180,13 @@ endif() set_target_properties(fastdeploy PROPERTIES VERSION ${FASTDEPLOY_VERSION}) target_link_libraries(fastdeploy ${DEPEND_LIBS}) +# add examples after prepare include paths for third-parties +if (WITH_VISION_EXAMPLES AND EXISTS ${PROJECT_SOURCE_DIR}/examples) + add_definitions(-DWITH_VISION_EXAMPLES) + set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/examples/bin) + add_subdirectory(examples) +endif() + include(external/summary.cmake) fastdeploy_summary() @@ -211,6 +233,10 @@ if(BUILD_FASTDEPLOY_PYTHON) set(CMAKE_NO_SYSTEM_FROM_IMPORTED 1) endif() + if(NOT ENABLE_VISION) + file(GLOB_RECURSE VISION_PYBIND_SRCS ${PROJECT_SOURCE_DIR}/fastdeploy/vision/*_pybind.cc) + list(REMOVE_ITEM DEPLOY_PYBIND_SRCS ${VISION_PYBIND_SRCS}) + endif() add_library(fastdeploy_main MODULE ${DEPLOY_PYBIND_SRCS}) redefine_file_macro(fastdeploy_main) set_target_properties(fastdeploy_main PROPERTIES PREFIX "") diff --git a/docs/api/runtime_option.md b/docs/api/runtime_option.md index 1a7eeab2825..30bc5a29a63 100644 --- a/docs/api/runtime_option.md +++ b/docs/api/runtime_option.md @@ -77,9 +77,9 @@ option = fd.RuntimeOption() option.backend = fd.Backend.TRT # 当使用TRT后端,且为动态输入shape时 # 需配置输入shape信息 -option.trt_min_shape = {"images": [1, 3, 224, 224]} -option.trt_opt_shape = {"images": [4, 3, 224, 224]} -option.trt_max_shape = {"images": [8, 3, 224, 224]} +option.trt_min_shape = {"x": [1, 3, 224, 224]} +option.trt_opt_shape = {"x": [4, 3, 224, 224]} +option.trt_max_shape = {"x": [8, 3, 224, 224]} model = fd.vision.ppcls.Model("resnet50/inference.pdmodel", "resnet50/inference.pdiparams", @@ -117,9 +117,9 @@ model = fd.vision.ppcls.Model("resnet50/inference.pdmodel", int main() { auto option = fastdeploy::RuntimeOption(); - option.trt_min_shape["images"] = {1, 3, 224, 224}; - option.trt_opt_shape["images"] = {4, 3, 224, 224}; - option.trt_max_shape["images"] = {8, 3, 224, 224}; + option.trt_min_shape["x"] = {1, 3, 224, 224}; + option.trt_opt_shape["x"] = {4, 3, 224, 224}; + option.trt_max_shape["x"] = {8, 3, 224, 224}; auto model = fastdeploy::vision::ppcls.Model( "resnet50/inference.pdmodel", diff --git a/docs/compile/README.md b/docs/compile/README.md index 909ac893ca3..9cf5daab4d3 100644 --- a/docs/compile/README.md +++ b/docs/compile/README.md @@ -10,7 +10,7 @@ | 选项 | 作用 | 备注 | |:---- | :--- | :--- | | ENABLE_ORT_BACKEND | 启用ONNXRuntime推理后端,默认ON | - | -| WIGH_GPU | 是否开启GPU使用,默认OFF | 当设为TRUE时,须通过CUDA_DIRECTORY指定cuda目录,如/usr/local/cuda; Mac上不支持设为ON | +| WITH_GPU | 是否开启GPU使用,默认OFF | 当设为TRUE时,须通过CUDA_DIRECTORY指定cuda目录,如/usr/local/cuda; Mac上不支持设为ON | | ENABLE_TRT_BACKEND | 启用TensorRT推理后端,默认OFF | 当设为TRUE时,需通过TRT_DIRECTORY指定tensorrt目录,如/usr/downloads/TensorRT-8.4.0.1; Mac上不支持设为ON| | ENABLE_VISION | 编译集成视觉模型模块,包括OpenCV的编译集成,默认OFF | - | | ENABLE_PADDLE_FRONTEND | 编译集成Paddle2ONNX,默认ON | - | diff --git a/examples/.gitignore b/examples/.gitignore new file mode 100644 index 00000000000..0c684c6aedc --- /dev/null +++ b/examples/.gitignore @@ -0,0 +1,8 @@ +*.jpg +*.png +*.jpeg +*.onnx +*.engine +*.pd* +*.nb +bin \ No newline at end of file diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt new file mode 100644 index 00000000000..7dd3e0e25e3 --- /dev/null +++ b/examples/CMakeLists.txt @@ -0,0 +1,23 @@ +function(add_fastdeploy_executable field url model) + # temp target name/file var in function scope + set(TEMP_TARGET_FILE ${PROJECT_SOURCE_DIR}/examples/${field}/${url}_${model}.cc) + set(TEMP_TARGET_NAME ${field}_${url}_${model}) + if (EXISTS ${TEMP_TARGET_FILE} AND TARGET fastdeploy) + add_executable(${TEMP_TARGET_NAME} ${TEMP_TARGET_FILE}) + target_link_libraries(${TEMP_TARGET_NAME} PUBLIC fastdeploy) + message(STATUS "Found source file: [${field}/${url}_${model}.cc], ADD!!! fastdeploy executable: [${TEMP_TARGET_NAME}] !") + else () + message(WARNING "Can not found source file: [${field}/${url}_${model}.cc], SKIP!!! fastdeploy executable: [${TEMP_TARGET_NAME}] !") + endif() + unset(TEMP_TARGET_FILE) + unset(TEMP_TARGET_NAME) +endfunction() + +# vision examples +if (WITH_VISION_EXAMPLES) + add_fastdeploy_executable(vision ultralytics yolov5) + add_fastdeploy_executable(vision meituan yolov6) + add_fastdeploy_executable(vision megvii yolox) +endif() + +# other examples ... \ No newline at end of file diff --git a/examples/resources/.gitignore b/examples/resources/.gitignore new file mode 100644 index 00000000000..f8c24f7a602 --- /dev/null +++ b/examples/resources/.gitignore @@ -0,0 +1,11 @@ +images/*.jpg +images/*.jpeg +images/*.png +models/*.onnx +models/*.pd* +models/*.engine +models/*.trt +models/*.nb +outputs/*.jpg +outputs/*.jpeg +outputs/*.png \ No newline at end of file diff --git a/examples/resources/images/.gitignore b/examples/resources/images/.gitignore new file mode 100644 index 00000000000..a025c1b2f5f --- /dev/null +++ b/examples/resources/images/.gitignore @@ -0,0 +1,3 @@ +*.jpg +*.jpeg +*.png \ No newline at end of file diff --git a/examples/resources/models/.gitignore b/examples/resources/models/.gitignore new file mode 100644 index 00000000000..8a3992492a1 --- /dev/null +++ b/examples/resources/models/.gitignore @@ -0,0 +1,5 @@ +*.onnx +*.engine +*.pd* +*.nb +*.trt \ No newline at end of file diff --git a/examples/resources/outputs/.gitignore b/examples/resources/outputs/.gitignore new file mode 100644 index 00000000000..b90600fbed9 --- /dev/null +++ b/examples/resources/outputs/.gitignore @@ -0,0 +1,3 @@ +*.jpg +*.png +*.jpeg \ No newline at end of file diff --git a/examples/vision/megvii_yolox.cc b/examples/vision/megvii_yolox.cc new file mode 100644 index 00000000000..340694b54f6 --- /dev/null +++ b/examples/vision/megvii_yolox.cc @@ -0,0 +1,52 @@ +// Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "fastdeploy/vision.h" + +int main() { + namespace vis = fastdeploy::vision; + + std::string model_file = "../resources/models/yolox_s.onnx"; + std::string img_path = "../resources/images/bus.jpg"; + std::string vis_path = "../resources/outputs/megvii_yolox_vis_result.jpg"; + + auto model = vis::megvii::YOLOX(model_file); + if (!model.Initialized()) { + std::cerr << "Init Failed! Model: " << model_file << std::endl; + return -1; + } else { + std::cout << "Init Done! Model:" << model_file << std::endl; + } + model.EnableDebug(); + + cv::Mat im = cv::imread(img_path); + cv::Mat vis_im = im.clone(); + + vis::DetectionResult res; + if (!model.Predict(&im, &res)) { + std::cerr << "Prediction Failed." << std::endl; + return -1; + } else { + std::cout << "Prediction Done!" << std::endl; + } + + // 输出预测框结果 + std::cout << res.Str() << std::endl; + + // 可视化预测结果 + vis::Visualize::VisDetection(&vis_im, res); + cv::imwrite(vis_path, vis_im); + std::cout << "Detect Done! Saved: " << vis_path << std::endl; + return 0; +} diff --git a/examples/vision/meituan_yolov6.cc b/examples/vision/meituan_yolov6.cc new file mode 100644 index 00000000000..7bdd78e5dca --- /dev/null +++ b/examples/vision/meituan_yolov6.cc @@ -0,0 +1,52 @@ +// Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "fastdeploy/vision.h" + +int main() { + namespace vis = fastdeploy::vision; + + std::string model_file = "../resources/models/yolov6s.onnx"; + std::string img_path = "../resources/images/bus.jpg"; + std::string vis_path = "../resources/outputs/meituan_yolov6_vis_result.jpg"; + + auto model = vis::meituan::YOLOv6(model_file); + if (!model.Initialized()) { + std::cerr << "Init Failed! Model: " << model_file << std::endl; + return -1; + } else { + std::cout << "Init Done! Model:" << model_file << std::endl; + } + model.EnableDebug(); + + cv::Mat im = cv::imread(img_path); + cv::Mat vis_im = im.clone(); + + vis::DetectionResult res; + if (!model.Predict(&im, &res)) { + std::cerr << "Prediction Failed." << std::endl; + return -1; + } else { + std::cout << "Prediction Done!" << std::endl; + } + + // 输出预测框结果 + std::cout << res.Str() << std::endl; + + // 可视化预测结果 + vis::Visualize::VisDetection(&vis_im, res); + cv::imwrite(vis_path, vis_im); + std::cout << "Detect Done! Saved: " << vis_path << std::endl; + return 0; +} diff --git a/examples/vision/ultralytics_yolov5.cc b/examples/vision/ultralytics_yolov5.cc new file mode 100644 index 00000000000..42a23368616 --- /dev/null +++ b/examples/vision/ultralytics_yolov5.cc @@ -0,0 +1,52 @@ +// Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "fastdeploy/vision.h" + +int main() { + namespace vis = fastdeploy::vision; + + std::string model_file = "../resources/models/yolov5s.onnx"; + std::string img_path = "../resources/images/bus.jpg"; + std::string vis_path = "../resources/outputs/ultralytics_yolov5_vis_result.jpg"; + + auto model = vis::ultralytics::YOLOv5(model_file); + if (!model.Initialized()) { + std::cerr << "Init Failed! Model: " << model_file << std::endl; + return -1; + } else { + std::cout << "Init Done! Model:" << model_file << std::endl; + } + model.EnableDebug(); + + cv::Mat im = cv::imread(img_path); + cv::Mat vis_im = im.clone(); + + vis::DetectionResult res; + if (!model.Predict(&im, &res)) { + std::cerr << "Prediction Failed." << std::endl; + return -1; + } else { + std::cout << "Prediction Done!" << std::endl; + } + + // 输出预测框结果 + std::cout << res.Str() << std::endl; + + // 可视化预测结果 + vis::Visualize::VisDetection(&vis_im, res); + cv::imwrite(vis_path, vis_im); + std::cout << "Detect Done! Saved: " << vis_path << std::endl; + return 0; +} diff --git a/external/paddle2onnx.cmake b/external/paddle2onnx.cmake index 0274c319aa8..fe1fcc8a8f2 100644 --- a/external/paddle2onnx.cmake +++ b/external/paddle2onnx.cmake @@ -43,7 +43,7 @@ else() endif(WIN32) set(PADDLE2ONNX_URL_BASE "https://bj.bcebos.com/paddle2onnx/libs/") -set(PADDLE2ONNX_VERSION "0.9.9") +set(PADDLE2ONNX_VERSION "1.0.0rc1") if(WIN32) set(PADDLE2ONNX_FILE "paddle2onnx-win-x64-${PADDLE2ONNX_VERSION}.zip") elseif(APPLE) diff --git a/fastdeploy/backends/tensorrt/trt_backend.cc b/fastdeploy/backends/tensorrt/trt_backend.cc index 5dbb61ffe83..a29af6e9a37 100644 --- a/fastdeploy/backends/tensorrt/trt_backend.cc +++ b/fastdeploy/backends/tensorrt/trt_backend.cc @@ -52,7 +52,7 @@ std::vector toVec(const nvinfer1::Dims& dim) { return out; } -bool TrtBackend::InitFromTrt(const std::string& trt_engine_file, +bool TrtBackend::InitFromTrt(const std::string& trt_engine_file, const TrtBackendOption& option) { if (initialized_) { FDERROR << "TrtBackend is already initlized, cannot initialize again." @@ -139,17 +139,6 @@ bool TrtBackend::InitFromOnnx(const std::string& model_file, } cudaSetDevice(option.gpu_id); - if (option.serialize_file != "") { - std::ifstream fin(option.serialize_file, std::ios::binary | std::ios::in); - if (fin) { - FDLogger() << "Detect serialized TensorRT Engine file in " - << option.serialize_file << ", will load it directly." - << std::endl; - fin.close(); - return InitFromTrt(option.serialize_file); - } - } - std::string onnx_content = ""; if (!from_memory_buffer) { std::ifstream fin(model_file.c_str(), std::ios::binary | std::ios::in); @@ -167,6 +156,29 @@ bool TrtBackend::InitFromOnnx(const std::string& model_file, onnx_content = model_file; } + // This part of code will record the original outputs order + // because the converted tensorrt network may exist wrong order of outputs + outputs_order_.clear(); + auto onnx_reader = + paddle2onnx::OnnxReader(onnx_content.c_str(), onnx_content.size()); + for (int i = 0; i < onnx_reader.NumOutputs(); ++i) { + std::string name( + onnx_reader.output_names[i], + onnx_reader.output_names[i] + strlen(onnx_reader.output_names[i])); + outputs_order_[name] = i; + } + + if (option.serialize_file != "") { + std::ifstream fin(option.serialize_file, std::ios::binary | std::ios::in); + if (fin) { + FDLogger() << "Detect serialized TensorRT Engine file in " + << option.serialize_file << ", will load it directly." + << std::endl; + fin.close(); + return InitFromTrt(option.serialize_file); + } + } + if (!CreateTrtEngine(onnx_content, option)) { return false; } @@ -251,13 +263,20 @@ void TrtBackend::AllocateBufferInDynamicShape( for (size_t i = 0; i < outputs_desc_.size(); ++i) { auto idx = engine_->getBindingIndex(outputs_desc_[i].name.c_str()); auto output_dims = context_->getBindingDimensions(idx); - (*outputs)[i].dtype = GetFDDataType(outputs_desc_[i].dtype); - (*outputs)[i].shape.assign(output_dims.d, - output_dims.d + output_dims.nbDims); - (*outputs)[i].name = outputs_desc_[i].name; - (*outputs)[i].data.resize(volume(output_dims) * - TrtDataTypeSize(outputs_desc_[i].dtype)); - if ((*outputs)[i].Nbytes() > + + // find the original index of output + auto iter = outputs_order_.find(outputs_desc_[i].name); + FDASSERT(iter != outputs_order_.end(), + "Cannot find output:" + outputs_desc_[i].name + + " of tensorrt network from the original model."); + auto ori_idx = iter->second; + (*outputs)[ori_idx].dtype = GetFDDataType(outputs_desc_[i].dtype); + (*outputs)[ori_idx].shape.assign(output_dims.d, + output_dims.d + output_dims.nbDims); + (*outputs)[ori_idx].name = outputs_desc_[i].name; + (*outputs)[ori_idx].data.resize(volume(output_dims) * + TrtDataTypeSize(outputs_desc_[i].dtype)); + if ((*outputs)[ori_idx].Nbytes() > outputs_buffer_[outputs_desc_[i].name].nbBytes()) { outputs_buffer_[outputs_desc_[i].name].resize(output_dims); bindings_[idx] = outputs_buffer_[outputs_desc_[i].name].data(); diff --git a/fastdeploy/backends/tensorrt/trt_backend.h b/fastdeploy/backends/tensorrt/trt_backend.h index e3f848a012a..1da7f147144 100644 --- a/fastdeploy/backends/tensorrt/trt_backend.h +++ b/fastdeploy/backends/tensorrt/trt_backend.h @@ -28,8 +28,8 @@ #include "fastdeploy/backends/tensorrt/common/parserOnnxConfig.h" #include "fastdeploy/backends/tensorrt/common/sampleUtils.h" -#include "NvInfer.h" #include +#include "NvInfer.h" namespace fastdeploy { using namespace samplesCommon; @@ -69,7 +69,7 @@ class TrtBackend : public BaseBackend { bool InitFromOnnx(const std::string& model_file, const TrtBackendOption& option = TrtBackendOption(), bool from_memory_buffer = false); - bool InitFromTrt(const std::string& trt_engine_file, + bool InitFromTrt(const std::string& trt_engine_file, const TrtBackendOption& option = TrtBackendOption()); bool Infer(std::vector& inputs, std::vector* outputs); @@ -89,6 +89,13 @@ class TrtBackend : public BaseBackend { std::map inputs_buffer_; std::map outputs_buffer_; + // Sometimes while the number of outputs > 1 + // the output order of tensorrt may not be same + // with the original onnx model + // So this parameter will record to origin outputs + // order, to help recover the rigt order + std::map outputs_order_; + void GetInputOutputInfo(); void AllocateBufferInDynamicShape(const std::vector& inputs, std::vector* outputs); @@ -96,4 +103,4 @@ class TrtBackend : public BaseBackend { const TrtBackendOption& option); }; -} // namespace fastdeploy +} // namespace fastdeploy diff --git a/fastdeploy/download.py b/fastdeploy/download.py index 805f63636ee..e00af098dfd 100644 --- a/fastdeploy/download.py +++ b/fastdeploy/download.py @@ -18,6 +18,7 @@ import requests import time import zipfile +import tarfile import hashlib import tqdm import logging diff --git a/fastdeploy/fastdeploy_runtime.cc b/fastdeploy/fastdeploy_runtime.cc index b053db586fa..3141e71721e 100644 --- a/fastdeploy/fastdeploy_runtime.cc +++ b/fastdeploy/fastdeploy_runtime.cc @@ -138,7 +138,7 @@ void Runtime::CreateTrtBackend() { trt_option.max_workspace_size = option.trt_max_workspace_size; trt_option.fixed_shape = option.trt_fixed_shape; trt_option.max_shape = option.trt_max_shape; - trt_option.min_shape = option.trt_max_shape; + trt_option.min_shape = option.trt_min_shape; trt_option.opt_shape = option.trt_opt_shape; trt_option.serialize_file = option.trt_serialize_file; FDASSERT(option.model_format == Frontend::PADDLE || diff --git a/fastdeploy/fastdeploy_runtime.py b/fastdeploy/fastdeploy_runtime.py index 3eef861f2f7..4b7acb25edd 100644 --- a/fastdeploy/fastdeploy_runtime.py +++ b/fastdeploy/fastdeploy_runtime.py @@ -51,5 +51,5 @@ def runtime_option(self): @property def initialized(self): if self._model is None: - return false + return False return self._model.initialized() diff --git a/fastdeploy/pybind/fastdeploy_model.cc b/fastdeploy/pybind/fastdeploy_model.cc index 3693bfa4d75..b59c0fd0ffa 100644 --- a/fastdeploy/pybind/fastdeploy_model.cc +++ b/fastdeploy/pybind/fastdeploy_model.cc @@ -13,6 +13,7 @@ // limitations under the License. #include "fastdeploy/pybind/main.h" +#include "fastdeploy/fastdeploy_model.h" namespace fastdeploy { diff --git a/fastdeploy/vision.h b/fastdeploy/vision.h index ca2b9a618af..d0e83ed030c 100644 --- a/fastdeploy/vision.h +++ b/fastdeploy/vision.h @@ -17,6 +17,8 @@ #ifdef ENABLE_VISION #include "fastdeploy/vision/ppcls/model.h" #include "fastdeploy/vision/ultralytics/yolov5.h" +#include "fastdeploy/vision/meituan/yolov6.h" +#include "fastdeploy/vision/megvii/yolox.h" #endif #include "fastdeploy/vision/visualize/visualize.h" diff --git a/fastdeploy/vision/__init__.py b/fastdeploy/vision/__init__.py index 810b23cd3db..f2de6190b08 100644 --- a/fastdeploy/vision/__init__.py +++ b/fastdeploy/vision/__init__.py @@ -16,4 +16,6 @@ from . import evaluation from . import ppcls from . import ultralytics +from . import meituan +from . import megvii from . import visualize diff --git a/fastdeploy/vision/megvii/__init__.py b/fastdeploy/vision/megvii/__init__.py new file mode 100644 index 00000000000..67096e4fc8f --- /dev/null +++ b/fastdeploy/vision/megvii/__init__.py @@ -0,0 +1,96 @@ +# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import absolute_import +import logging +from ... import FastDeployModel, Frontend +from ... import fastdeploy_main as C + + +class YOLOX(FastDeployModel): + def __init__(self, + model_file, + params_file="", + runtime_option=None, + model_format=Frontend.ONNX): + # 调用基函数进行backend_option的初始化 + # 初始化后的option保存在self._runtime_option + super(YOLOX, self).__init__(runtime_option) + + self._model = C.vision.megvii.YOLOX( + model_file, params_file, self._runtime_option, model_format) + # 通过self.initialized判断整个模型的初始化是否成功 + assert self.initialized, "YOLOX initialize failed." + + def predict(self, input_image, conf_threshold=0.25, nms_iou_threshold=0.5): + return self._model.predict(input_image, conf_threshold, + nms_iou_threshold) + + # 一些跟YOLOX模型有关的属性封装 + # 多数是预处理相关,可通过修改如model.size = [1280, 1280]改变预处理时resize的大小(前提是模型支持) + @property + def size(self): + return self._model.size + + @property + def padding_value(self): + return self._model.padding_value + + @property + def is_decode_exported(self): + return self._model.is_decode_exported + + @property + def downsample_strides(self): + return self._model.downsample_strides + + @property + def max_wh(self): + return self._model.max_wh + + @size.setter + def size(self, wh): + assert isinstance(wh, [list, tuple]),\ + "The value to set `size` must be type of tuple or list." + assert len(wh) == 2,\ + "The value to set `size` must contatins 2 elements means [width, height], but now it contains {} elements.".format( + len(wh)) + self._model.size = wh + + @padding_value.setter + def padding_value(self, value): + assert isinstance( + value, + list), "The value to set `padding_value` must be type of list." + self._model.padding_value = value + + @is_decode_exported.setter + def is_decode_exported(self, value): + assert isinstance( + value, + bool), "The value to set `is_decode_exported` must be type of bool." + self._model.max_wh = value + + @downsample_strides.setter + def downsample_strides(self, value): + assert isinstance( + value, + list), "The value to set `downsample_strides` must be type of list." + self._model.downsample_strides = value + + @max_wh.setter + def max_wh(self, value): + assert isinstance( + value, float), "The value to set `max_wh` must be type of float." + self._model.max_wh = value diff --git a/fastdeploy/vision/megvii/megvii_pybind.cc b/fastdeploy/vision/megvii/megvii_pybind.cc new file mode 100644 index 00000000000..7e7fbc79aa5 --- /dev/null +++ b/fastdeploy/vision/megvii/megvii_pybind.cc @@ -0,0 +1,41 @@ +// Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "fastdeploy/pybind/main.h" + +namespace fastdeploy { +void BindMegvii(pybind11::module& m) { + auto megvii_module = + m.def_submodule("megvii", "https://github.com/megvii/YOLOX"); + pybind11::class_( + megvii_module, "YOLOX") + .def(pybind11::init()) + .def("predict", + [](vision::megvii::YOLOX& self, pybind11::array& data, + float conf_threshold, float nms_iou_threshold) { + auto mat = PyArrayToCvMat(data); + vision::DetectionResult res; + self.Predict(&mat, &res, conf_threshold, nms_iou_threshold); + return res; + }) + .def_readwrite("size", &vision::megvii::YOLOX::size) + .def_readwrite("padding_value", + &vision::megvii::YOLOX::padding_value) + .def_readwrite("is_decode_exported", + &vision::megvii::YOLOX::is_decode_exported) + .def_readwrite("downsample_strides", + &vision::megvii::YOLOX::downsample_strides) + .def_readwrite("max_wh", &vision::megvii::YOLOX::max_wh); +} +} // namespace fastdeploy diff --git a/fastdeploy/vision/megvii/yolox.cc b/fastdeploy/vision/megvii/yolox.cc new file mode 100644 index 00000000000..e308297050d --- /dev/null +++ b/fastdeploy/vision/megvii/yolox.cc @@ -0,0 +1,341 @@ +// Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "fastdeploy/vision/megvii/yolox.h" +#include "fastdeploy/utils/perf.h" +#include "fastdeploy/vision/utils/utils.h" + +namespace fastdeploy { + +namespace vision { + +namespace megvii { + +struct YOLOXAnchor { + int grid0; + int grid1; + int stride; +}; + +void GenerateYOLOXAnchors(const std::vector &size, + const std::vector &downsample_strides, + std::vector &anchors) { + // size: tuple of input (width, height) + // downsample_strides: downsample strides in YOLOX, e.g (8,16,32) + const int width = size[0]; + const int height = size[1]; + for (const auto &ds: downsample_strides) { + int num_grid_w = width / ds; + int num_grid_h = height / ds; + for (int g1 = 0; g1 < num_grid_h; ++g1) { + for (int g0 = 0; g0 < num_grid_w; ++g0) { + anchors.emplace_back(YOLOXAnchor{g0, g1, ds}); + } + } + } +} + +void PreProc(Mat* mat, std::vector size, std::vector color) { + // specific pre process for YOLOX, not the same as YOLOv5 + // reference: YOLOX/yolox/data/data_augment.py#L142 + float r = std::min(size[1] * 1.0f / static_cast(mat->Height()), + size[0] * 1.0f / static_cast(mat->Width())); + + int resize_h = int(round(static_cast(mat->Height()) * r)); + int resize_w = int(round(static_cast(mat->Width()) * r)); + + if (resize_h != mat->Height() || resize_w != mat->Width()) { + Resize::Run(mat, resize_w, resize_h); + } + + int pad_w = size[0] - resize_w; + int pad_h = size[1] - resize_h; + // right-bottom padding for YOLOX + if (pad_h > 0 || pad_w > 0) { + int top = 0; + int left = 0; + int right = pad_w; + int bottom = pad_h; + Pad::Run(mat, top, bottom, left, right, color); + } +} + +YOLOX::YOLOX(const std::string& model_file, const std::string& params_file, + const RuntimeOption& custom_option, + const Frontend& model_format) { + if (model_format == Frontend::ONNX) { + valid_cpu_backends = {Backend::ORT}; // 指定可用的CPU后端 + valid_gpu_backends = {Backend::ORT, Backend::TRT}; // 指定可用的GPU后端 + } else { + valid_cpu_backends = {Backend::PDINFER, Backend::ORT}; + valid_gpu_backends = {Backend::PDINFER, Backend::ORT, Backend::TRT}; + } + runtime_option = custom_option; + runtime_option.model_format = model_format; + runtime_option.model_file = model_file; + runtime_option.params_file = params_file; + initialized = Initialize(); +} + +bool YOLOX::Initialize() { + // parameters for preprocess + size = {640, 640}; + padding_value = {114.0, 114.0, 114.0}; + downsample_strides = {8, 16, 32}; + max_wh = 4096.0f; + is_decode_exported = false; + + if (!InitRuntime()) { + FDERROR << "Failed to initialize fastdeploy backend." << std::endl; + return false; + } + // Check if the input shape is dynamic after Runtime already initialized. + is_dynamic_input_ = false; + auto shape = InputInfoOfRuntime(0).shape; + for (int i = 0; i < shape.size(); ++i) { + // if height or width is dynamic + if (i >= 2 && shape[i] <= 0) { + is_dynamic_input_ = true; + break; + } + } + return true; +} + +bool YOLOX::Preprocess(Mat* mat, FDTensor* output, + std::map>* im_info) { + // YOLOX ( >= v0.1.1) preprocess steps + // 1. preproc + // 2. HWC->CHW + // 3. NO!!! BRG2GRB and Normalize needed in YOLOX + PreProc(mat, size, padding_value); + // Record output shape of preprocessed image + (*im_info)["output_shape"] = {static_cast(mat->Height()), + static_cast(mat->Width())}; + + HWC2CHW::Run(mat); + Cast::Run(mat, "float"); + mat->ShareWithTensor(output); + output->shape.insert(output->shape.begin(), 1); // reshape to n, h, w, c + return true; +} + +bool YOLOX::Postprocess( + FDTensor& infer_result, DetectionResult* result, + const std::map>& im_info, + float conf_threshold, float nms_iou_threshold) { + FDASSERT(infer_result.shape[0] == 1, "Only support batch =1 now."); + result->Clear(); + result->Reserve(infer_result.shape[1]); + if (infer_result.dtype != FDDataType::FP32) { + FDERROR << "Only support post process with float32 data." << std::endl; + return false; + } + float* data = static_cast(infer_result.Data()); + for (size_t i = 0; i < infer_result.shape[1]; ++i) { + int s = i * infer_result.shape[2]; + float confidence = data[s + 4]; + float* max_class_score = + std::max_element(data + s + 5, data + s + infer_result.shape[2]); + confidence *= (*max_class_score); + // filter boxes by conf_threshold + if (confidence <= conf_threshold) { + continue; + } + int32_t label_id = std::distance(data + s + 5, max_class_score); + // convert from [x, y, w, h] to [x1, y1, x2, y2] + result->boxes.emplace_back(std::array{ + data[s] - data[s + 2] / 2.0f + label_id * max_wh, + data[s + 1] - data[s + 3] / 2.0f + label_id * max_wh, + data[s + 0] + data[s + 2] / 2.0f + label_id * max_wh, + data[s + 1] + data[s + 3] / 2.0f + label_id * max_wh}); + result->label_ids.push_back(label_id); + result->scores.push_back(confidence); + } + utils::NMS(result, nms_iou_threshold); + + // scale the boxes to the origin image shape + auto iter_out = im_info.find("output_shape"); + auto iter_ipt = im_info.find("input_shape"); + FDASSERT(iter_out != im_info.end() && iter_ipt != im_info.end(), + "Cannot find input_shape or output_shape from im_info."); + float out_h = iter_out->second[0]; + float out_w = iter_out->second[1]; + float ipt_h = iter_ipt->second[0]; + float ipt_w = iter_ipt->second[1]; + float r = std::min(out_h / ipt_h, out_w / ipt_w); + for (size_t i = 0; i < result->boxes.size(); ++i) { + int32_t label_id = (result->label_ids)[i]; + // clip box + result->boxes[i][0] = result->boxes[i][0] - max_wh * label_id; + result->boxes[i][1] = result->boxes[i][1] - max_wh * label_id; + result->boxes[i][2] = result->boxes[i][2] - max_wh * label_id; + result->boxes[i][3] = result->boxes[i][3] - max_wh * label_id; + result->boxes[i][0] = std::max(result->boxes[i][0] / r, 0.0f); + result->boxes[i][1] = std::max(result->boxes[i][1] / r, 0.0f); + result->boxes[i][2] = std::max(result->boxes[i][2] / r, 0.0f); + result->boxes[i][3] = std::max(result->boxes[i][3] / r, 0.0f); + result->boxes[i][0] = std::min(result->boxes[i][0], ipt_w - 1.0f); + result->boxes[i][1] = std::min(result->boxes[i][1], ipt_h - 1.0f); + result->boxes[i][2] = std::min(result->boxes[i][2], ipt_w - 1.0f); + result->boxes[i][3] = std::min(result->boxes[i][3], ipt_h - 1.0f); + } + return true; +} + +bool YOLOX::PostprocessWithDecode( + FDTensor& infer_result, DetectionResult* result, + const std::map>& im_info, + float conf_threshold, float nms_iou_threshold) { + FDASSERT(infer_result.shape[0] == 1, "Only support batch =1 now."); + result->Clear(); + result->Reserve(infer_result.shape[1]); + if (infer_result.dtype != FDDataType::FP32) { + FDERROR << "Only support post process with float32 data." << std::endl; + return false; + } + // generate anchors with dowmsample strides + std::vector anchors; + GenerateYOLOXAnchors(size, downsample_strides, anchors); + + // infer_result shape might look like (1,n,85=5+80) + float* data = static_cast(infer_result.Data()); + for (size_t i = 0; i < infer_result.shape[1]; ++i) { + int s = i * infer_result.shape[2]; + float confidence = data[s + 4]; + float* max_class_score = + std::max_element(data + s + 5, data + s + infer_result.shape[2]); + confidence *= (*max_class_score); + // filter boxes by conf_threshold + if (confidence <= conf_threshold) { + continue; + } + int32_t label_id = std::distance(data + s + 5, max_class_score); + // fetch i-th anchor + float grid0 = static_cast(anchors.at(i).grid0); + float grid1 = static_cast(anchors.at(i).grid1); + float downsample_stride = static_cast(anchors.at(i).stride); + // convert from offsets to [x, y, w, h] + float dx = data[s]; + float dy = data[s + 1]; + float dw = data[s + 2]; + float dh = data[s + 3]; + + float x = (dx + grid0) * downsample_stride; + float y = (dy + grid1) * downsample_stride; + float w = std::exp(dw) * downsample_stride; + float h = std::exp(dh) * downsample_stride; + + // convert from [x, y, w, h] to [x1, y1, x2, y2] + result->boxes.emplace_back(std::array{ + x - w / 2.0f + label_id * max_wh, + y - h / 2.0f + label_id * max_wh, + x + w / 2.0f + label_id * max_wh, + y + h / 2.0f + label_id * max_wh}); + // label_id * max_wh for multi classes NMS + result->label_ids.push_back(label_id); + result->scores.push_back(confidence); + } + utils::NMS(result, nms_iou_threshold); + + // scale the boxes to the origin image shape + auto iter_out = im_info.find("output_shape"); + auto iter_ipt = im_info.find("input_shape"); + FDASSERT(iter_out != im_info.end() && iter_ipt != im_info.end(), + "Cannot find input_shape or output_shape from im_info."); + float out_h = iter_out->second[0]; + float out_w = iter_out->second[1]; + float ipt_h = iter_ipt->second[0]; + float ipt_w = iter_ipt->second[1]; + float r = std::min(out_h / ipt_h, out_w / ipt_w); + for (size_t i = 0; i < result->boxes.size(); ++i) { + int32_t label_id = (result->label_ids)[i]; + // clip box + result->boxes[i][0] = result->boxes[i][0] - max_wh * label_id; + result->boxes[i][1] = result->boxes[i][1] - max_wh * label_id; + result->boxes[i][2] = result->boxes[i][2] - max_wh * label_id; + result->boxes[i][3] = result->boxes[i][3] - max_wh * label_id; + result->boxes[i][0] = std::max(result->boxes[i][0] / r, 0.0f); + result->boxes[i][1] = std::max(result->boxes[i][1] / r, 0.0f); + result->boxes[i][2] = std::max(result->boxes[i][2] / r, 0.0f); + result->boxes[i][3] = std::max(result->boxes[i][3] / r, 0.0f); + result->boxes[i][0] = std::min(result->boxes[i][0], ipt_w - 1.0f); + result->boxes[i][1] = std::min(result->boxes[i][1], ipt_h - 1.0f); + result->boxes[i][2] = std::min(result->boxes[i][2], ipt_w - 1.0f); + result->boxes[i][3] = std::min(result->boxes[i][3], ipt_h - 1.0f); + } + return true; +} + +bool YOLOX::Predict(cv::Mat* im, DetectionResult* result, float conf_threshold, + float nms_iou_threshold) { +#ifdef FASTDEPLOY_DEBUG + TIMERECORD_START(0) +#endif + + Mat mat(*im); + std::vector input_tensors(1); + + std::map> im_info; + + // Record the shape of image and the shape of preprocessed image + im_info["input_shape"] = {static_cast(mat.Height()), + static_cast(mat.Width())}; + im_info["output_shape"] = {static_cast(mat.Height()), + static_cast(mat.Width())}; + + if (!Preprocess(&mat, &input_tensors[0], &im_info)) { + FDERROR << "Failed to preprocess input image." << std::endl; + return false; + } + +#ifdef FASTDEPLOY_DEBUG + TIMERECORD_END(0, "Preprocess") + TIMERECORD_START(1) +#endif + + input_tensors[0].name = InputInfoOfRuntime(0).name; + std::vector output_tensors; + if (!Infer(input_tensors, &output_tensors)) { + FDERROR << "Failed to inference." << std::endl; + return false; + } +#ifdef FASTDEPLOY_DEBUG + TIMERECORD_END(1, "Inference") + TIMERECORD_START(2) +#endif + + if (is_decode_exported) { + if (!Postprocess(output_tensors[0], result, im_info, conf_threshold, + nms_iou_threshold)) { + FDERROR << "Failed to post process." << std::endl; + return false; + } + } else { + if (!PostprocessWithDecode(output_tensors[0], result, im_info, conf_threshold, + nms_iou_threshold)) { + FDERROR << "Failed to post process." << std::endl; + return false; + } + } + +#ifdef FASTDEPLOY_DEBUG + TIMERECORD_END(2, "Postprocess") +#endif + return true; +} + +} // namespace megvii +} // namespace vision +} // namespace fastdeploy \ No newline at end of file diff --git a/fastdeploy/vision/megvii/yolox.h b/fastdeploy/vision/megvii/yolox.h new file mode 100644 index 00000000000..7ff8edcf007 --- /dev/null +++ b/fastdeploy/vision/megvii/yolox.h @@ -0,0 +1,105 @@ +// Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#pragma once + +#include "fastdeploy/fastdeploy_model.h" +#include "fastdeploy/vision/common/processors/transform.h" +#include "fastdeploy/vision/common/result.h" + +namespace fastdeploy { + +namespace vision { + +namespace megvii { + +class FASTDEPLOY_DECL YOLOX : public FastDeployModel { + public: + // 当model_format为ONNX时,无需指定params_file + // 当model_format为Paddle时,则需同时指定model_file & params_file + YOLOX(const std::string& model_file, const std::string& params_file = "", + const RuntimeOption& custom_option = RuntimeOption(), + const Frontend& model_format = Frontend::ONNX); + + // 定义模型的名称 + std::string ModelName() const { return "megvii/YOLOX"; } + + // 模型预测接口,即用户调用的接口 + // im 为用户的输入数据,目前对于CV均定义为cv::Mat + // result 为模型预测的输出结构体 + // conf_threshold 为后处理的参数 + // nms_iou_threshold 为后处理的参数 + virtual bool Predict(cv::Mat* im, DetectionResult* result, + float conf_threshold = 0.25, + float nms_iou_threshold = 0.5); + + // 以下为模型在预测时的一些参数,基本是前后处理所需 + // 用户在创建模型后,可根据模型的要求,以及自己的需求 + // 对参数进行修改 + // tuple of (width, height) + std::vector size; + // padding value, size should be same with Channels + std::vector padding_value; + // whether the model_file was exported with decode module. The official + // YOLOX/tools/export_onnx.py script will export ONNX file without + // decode module. Please set it 'true' manually if the model file + // was exported with decode module. + bool is_decode_exported; + // downsample strides for YOLOX to generate anchors, will take + // (8,16,32) as default values, might have stride=64. + std::vector downsample_strides; + // for offseting the boxes by classes when using NMS, default 4096. + float max_wh; + + private: + // 初始化函数,包括初始化后端,以及其它模型推理需要涉及的操作 + bool Initialize(); + + // 输入图像预处理操作 + // Mat为FastDeploy定义的数据结构 + // FDTensor为预处理后的Tensor数据,传给后端进行推理 + // im_info为预处理过程保存的数据,在后处理中需要用到 + bool Preprocess(Mat* mat, FDTensor* outputs, + std::map>* im_info); + + // 后端推理结果后处理,输出给用户 + // infer_result 为后端推理后的输出Tensor + // result 为模型预测的结果 + // im_info 为预处理记录的信息,后处理用于还原box + // conf_threshold 后处理时过滤box的置信度阈值 + // nms_iou_threshold 后处理时NMS设定的iou阈值 + bool Postprocess( + FDTensor& infer_result, DetectionResult* result, + const std::map>& im_info, + float conf_threshold, float nms_iou_threshold); + + // YOLOX的官方脚本默认导出不带decode模块的模型文件 需要在后处理进行decode + bool PostprocessWithDecode( + FDTensor& infer_result, DetectionResult* result, + const std::map>& im_info, + float conf_threshold, float nms_iou_threshold); + + // 查看输入是否为动态维度的 不建议直接使用 不同模型的逻辑可能不一致 + bool IsDynamicInput() const { return is_dynamic_input_; } + + // whether to inference with dynamic shape (e.g ONNX export with dynamic shape or not.) + // megvii/YOLOX official 'export_onnx.py' script will export static ONNX by default. + // while is_dynamic_shape if 'false', is_mini_pad will force 'false'. This value will + // auto check by fastdeploy after the internal Runtime already initialized. + bool is_dynamic_input_; +}; + +} // namespace megvii +} // namespace vision +} // namespace fastdeploy diff --git a/fastdeploy/vision/meituan/__init__.py b/fastdeploy/vision/meituan/__init__.py new file mode 100644 index 00000000000..7b6635dd368 --- /dev/null +++ b/fastdeploy/vision/meituan/__init__.py @@ -0,0 +1,116 @@ +# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import absolute_import +import logging +from ... import FastDeployModel, Frontend +from ... import fastdeploy_main as C + + +class YOLOv6(FastDeployModel): + def __init__(self, + model_file, + params_file="", + runtime_option=None, + model_format=Frontend.ONNX): + # 调用基函数进行backend_option的初始化 + # 初始化后的option保存在self._runtime_option + super(YOLOv6, self).__init__(runtime_option) + + self._model = C.vision.meituan.YOLOv6( + model_file, params_file, self._runtime_option, model_format) + # 通过self.initialized判断整个模型的初始化是否成功 + assert self.initialized, "YOLOv6 initialize failed." + + def predict(self, input_image, conf_threshold=0.25, nms_iou_threshold=0.5): + return self._model.predict(input_image, conf_threshold, + nms_iou_threshold) + + # 一些跟YOLOv6模型有关的属性封装 + # 多数是预处理相关,可通过修改如model.size = [1280, 1280]改变预处理时resize的大小(前提是模型支持) + @property + def size(self): + return self._model.size + + @property + def padding_value(self): + return self._model.padding_value + + @property + def is_no_pad(self): + return self._model.is_no_pad + + @property + def is_mini_pad(self): + return self._model.is_mini_pad + + @property + def is_scale_up(self): + return self._model.is_scale_up + + @property + def stride(self): + return self._model.stride + + @property + def max_wh(self): + return self._model.max_wh + + @size.setter + def size(self, wh): + assert isinstance(wh, [list, tuple]),\ + "The value to set `size` must be type of tuple or list." + assert len(wh) == 2,\ + "The value to set `size` must contatins 2 elements means [width, height], but now it contains {} elements.".format( + len(wh)) + self._model.size = wh + + @padding_value.setter + def padding_value(self, value): + assert isinstance( + value, + list), "The value to set `padding_value` must be type of list." + self._model.padding_value = value + + @is_no_pad.setter + def is_no_pad(self, value): + assert isinstance( + value, bool), "The value to set `is_no_pad` must be type of bool." + self._model.is_no_pad = value + + @is_mini_pad.setter + def is_mini_pad(self, value): + assert isinstance( + value, + bool), "The value to set `is_mini_pad` must be type of bool." + self._model.is_mini_pad = value + + @is_scale_up.setter + def is_scale_up(self, value): + assert isinstance( + value, + bool), "The value to set `is_scale_up` must be type of bool." + self._model.is_scale_up = value + + @stride.setter + def stride(self, value): + assert isinstance( + value, int), "The value to set `stride` must be type of int." + self._model.stride = value + + @max_wh.setter + def max_wh(self, value): + assert isinstance( + value, float), "The value to set `max_wh` must be type of float." + self._model.max_wh = value diff --git a/fastdeploy/vision/meituan/meituan_pybind.cc b/fastdeploy/vision/meituan/meituan_pybind.cc new file mode 100644 index 00000000000..d1e81fa582c --- /dev/null +++ b/fastdeploy/vision/meituan/meituan_pybind.cc @@ -0,0 +1,41 @@ +// Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "fastdeploy/pybind/main.h" + +namespace fastdeploy { +void BindMeituan(pybind11::module& m) { + auto meituan_module = + m.def_submodule("meituan", "https://github.com/meituan/YOLOv6"); + pybind11::class_( + meituan_module, "YOLOv6") + .def(pybind11::init()) + .def("predict", + [](vision::meituan::YOLOv6& self, pybind11::array& data, + float conf_threshold, float nms_iou_threshold) { + auto mat = PyArrayToCvMat(data); + vision::DetectionResult res; + self.Predict(&mat, &res, conf_threshold, nms_iou_threshold); + return res; + }) + .def_readwrite("size", &vision::meituan::YOLOv6::size) + .def_readwrite("padding_value", + &vision::meituan::YOLOv6::padding_value) + .def_readwrite("is_mini_pad", &vision::meituan::YOLOv6::is_mini_pad) + .def_readwrite("is_no_pad", &vision::meituan::YOLOv6::is_no_pad) + .def_readwrite("is_scale_up", &vision::meituan::YOLOv6::is_scale_up) + .def_readwrite("stride", &vision::meituan::YOLOv6::stride) + .def_readwrite("max_wh", &vision::meituan::YOLOv6::max_wh); +} +} // namespace fastdeploy diff --git a/fastdeploy/vision/meituan/yolov6.cc b/fastdeploy/vision/meituan/yolov6.cc new file mode 100644 index 00000000000..8f37bf89c6f --- /dev/null +++ b/fastdeploy/vision/meituan/yolov6.cc @@ -0,0 +1,263 @@ +// Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "fastdeploy/vision/meituan/yolov6.h" +#include "fastdeploy/utils/perf.h" +#include "fastdeploy/vision/utils/utils.h" + +namespace fastdeploy { + +namespace vision { + +namespace meituan { + +void LetterBox(Mat* mat, std::vector size, std::vector color, + bool _auto, bool scale_fill = false, bool scale_up = true, + int stride = 32) { + float scale = std::min(size[1] * 1.0f / static_cast(mat->Height()), + size[0] * 1.0f / static_cast(mat->Width())); + if (!scale_up) { + scale = std::min(scale, 1.0f); + } + + int resize_h = int(round(static_cast(mat->Height()) * scale)); + int resize_w = int(round(static_cast(mat->Width()) * scale)); + + int pad_w = size[0] - resize_w; + int pad_h = size[1] - resize_h; + if (_auto) { + pad_h = pad_h % stride; + pad_w = pad_w % stride; + } else if (scale_fill) { + pad_h = 0; + pad_w = 0; + resize_h = size[1]; + resize_w = size[0]; + } + if (resize_h != mat->Height() || resize_w != mat->Width()) { + Resize::Run(mat, resize_w, resize_h); + } + if (pad_h > 0 || pad_w > 0) { + float half_h = pad_h * 1.0 / 2; + int top = int(round(half_h - 0.1)); + int bottom = int(round(half_h + 0.1)); + float half_w = pad_w * 1.0 / 2; + int left = int(round(half_w - 0.1)); + int right = int(round(half_w + 0.1)); + Pad::Run(mat, top, bottom, left, right, color); + } +} + +YOLOv6::YOLOv6(const std::string& model_file, const std::string& params_file, + const RuntimeOption& custom_option, + const Frontend& model_format) { + if (model_format == Frontend::ONNX) { + valid_cpu_backends = {Backend::ORT}; // 指定可用的CPU后端 + valid_gpu_backends = {Backend::ORT, Backend::TRT}; // 指定可用的GPU后端 + } else { + valid_cpu_backends = {Backend::PDINFER, Backend::ORT}; + valid_gpu_backends = {Backend::PDINFER, Backend::ORT, Backend::TRT}; + } + runtime_option = custom_option; + runtime_option.model_format = model_format; + runtime_option.model_file = model_file; + runtime_option.params_file = params_file; + initialized = Initialize(); +} + +bool YOLOv6::Initialize() { + // parameters for preprocess + size = {640, 640}; + padding_value = {114.0, 114.0, 114.0}; + is_mini_pad = false; + is_no_pad = false; + is_scale_up = false; + stride = 32; + max_wh = 4096.0f; + + if (!InitRuntime()) { + FDERROR << "Failed to initialize fastdeploy backend." << std::endl; + return false; + } + // Check if the input shape is dynamic after Runtime already initialized, + // Note that, We need to force is_mini_pad 'false' to keep static + // shape after padding (LetterBox) when the is_dynamic_shape is 'false'. + is_dynamic_input_ = false; + auto shape = InputInfoOfRuntime(0).shape; + for (int i = 0; i < shape.size(); ++i) { + // if height or width is dynamic + if (i >= 2 && shape[i] <= 0) { + is_dynamic_input_ = true; + break; + } + } + if (!is_dynamic_input_) { + is_mini_pad = false; + } + return true; +} + +bool YOLOv6::Preprocess(Mat* mat, FDTensor* output, + std::map>* im_info) { + // process after image load + float ratio = std::min(size[1] * 1.0f / static_cast(mat->Height()), + size[0] * 1.0f / static_cast(mat->Width())); + if (ratio != 1.0) { + int interp = cv::INTER_AREA; + if (ratio > 1.0) { + interp = cv::INTER_LINEAR; + } + int resize_h = int(round(static_cast(mat->Height()) * ratio)); + int resize_w = int(round(static_cast(mat->Width()) * ratio)); + Resize::Run(mat, resize_w, resize_h, -1, -1, interp); + } + // yolov6's preprocess steps + // 1. letterbox + // 2. BGR->RGB + // 3. HWC->CHW + LetterBox(mat, size, padding_value, is_mini_pad, is_no_pad, is_scale_up, + stride); + BGR2RGB::Run(mat); + Normalize::Run(mat, std::vector(mat->Channels(), 0.0), + std::vector(mat->Channels(), 1.0)); + + // Record output shape of preprocessed image + (*im_info)["output_shape"] = {static_cast(mat->Height()), + static_cast(mat->Width())}; + + HWC2CHW::Run(mat); + Cast::Run(mat, "float"); + mat->ShareWithTensor(output); + output->shape.insert(output->shape.begin(), 1); // reshape to n, h, w, c + return true; +} + +bool YOLOv6::Postprocess( + FDTensor& infer_result, DetectionResult* result, + const std::map>& im_info, + float conf_threshold, float nms_iou_threshold) { + FDASSERT(infer_result.shape[0] == 1, "Only support batch =1 now."); + result->Clear(); + result->Reserve(infer_result.shape[1]); + if (infer_result.dtype != FDDataType::FP32) { + FDERROR << "Only support post process with float32 data." << std::endl; + return false; + } + float* data = static_cast(infer_result.Data()); + for (size_t i = 0; i < infer_result.shape[1]; ++i) { + int s = i * infer_result.shape[2]; + float confidence = data[s + 4]; + float* max_class_score = + std::max_element(data + s + 5, data + s + infer_result.shape[2]); + confidence *= (*max_class_score); + // filter boxes by conf_threshold + if (confidence <= conf_threshold) { + continue; + } + int32_t label_id = std::distance(data + s + 5, max_class_score); + // convert from [x, y, w, h] to [x1, y1, x2, y2] + result->boxes.emplace_back(std::array{ + data[s] - data[s + 2] / 2.0f + label_id * max_wh, + data[s + 1] - data[s + 3] / 2.0f + label_id * max_wh, + data[s + 0] + data[s + 2] / 2.0f + label_id * max_wh, + data[s + 1] + data[s + 3] / 2.0f + label_id * max_wh}); + result->label_ids.push_back(label_id); + result->scores.push_back(confidence); + } + utils::NMS(result, nms_iou_threshold); + + // scale the boxes to the origin image shape + auto iter_out = im_info.find("output_shape"); + auto iter_ipt = im_info.find("input_shape"); + FDASSERT(iter_out != im_info.end() && iter_ipt != im_info.end(), + "Cannot find input_shape or output_shape from im_info."); + float out_h = iter_out->second[0]; + float out_w = iter_out->second[1]; + float ipt_h = iter_ipt->second[0]; + float ipt_w = iter_ipt->second[1]; + float scale = std::min(out_h / ipt_h, out_w / ipt_w); + for (size_t i = 0; i < result->boxes.size(); ++i) { + float pad_h = (out_h - ipt_h * scale) / 2; + float pad_w = (out_w - ipt_w * scale) / 2; + int32_t label_id = (result->label_ids)[i]; + // clip box + result->boxes[i][0] = result->boxes[i][0] - max_wh * label_id; + result->boxes[i][1] = result->boxes[i][1] - max_wh * label_id; + result->boxes[i][2] = result->boxes[i][2] - max_wh * label_id; + result->boxes[i][3] = result->boxes[i][3] - max_wh * label_id; + result->boxes[i][0] = std::max((result->boxes[i][0] - pad_w) / scale, 0.0f); + result->boxes[i][1] = std::max((result->boxes[i][1] - pad_h) / scale, 0.0f); + result->boxes[i][2] = std::max((result->boxes[i][2] - pad_w) / scale, 0.0f); + result->boxes[i][3] = std::max((result->boxes[i][3] - pad_h) / scale, 0.0f); + result->boxes[i][0] = std::min(result->boxes[i][0], ipt_w - 1.0f); + result->boxes[i][1] = std::min(result->boxes[i][1], ipt_h - 1.0f); + result->boxes[i][2] = std::min(result->boxes[i][2], ipt_w - 1.0f); + result->boxes[i][3] = std::min(result->boxes[i][3], ipt_h - 1.0f); + } + return true; +} + +bool YOLOv6::Predict(cv::Mat* im, DetectionResult* result, float conf_threshold, + float nms_iou_threshold) { +#ifdef FASTDEPLOY_DEBUG + TIMERECORD_START(0) +#endif + + Mat mat(*im); + std::vector input_tensors(1); + + std::map> im_info; + + // Record the shape of image and the shape of preprocessed image + im_info["input_shape"] = {static_cast(mat.Height()), + static_cast(mat.Width())}; + im_info["output_shape"] = {static_cast(mat.Height()), + static_cast(mat.Width())}; + + if (!Preprocess(&mat, &input_tensors[0], &im_info)) { + FDERROR << "Failed to preprocess input image." << std::endl; + return false; + } + +#ifdef FASTDEPLOY_DEBUG + TIMERECORD_END(0, "Preprocess") + TIMERECORD_START(1) +#endif + + input_tensors[0].name = InputInfoOfRuntime(0).name; + std::vector output_tensors; + if (!Infer(input_tensors, &output_tensors)) { + FDERROR << "Failed to inference." << std::endl; + return false; + } +#ifdef FASTDEPLOY_DEBUG + TIMERECORD_END(1, "Inference") + TIMERECORD_START(2) +#endif + + if (!Postprocess(output_tensors[0], result, im_info, conf_threshold, + nms_iou_threshold)) { + FDERROR << "Failed to post process." << std::endl; + return false; + } + +#ifdef FASTDEPLOY_DEBUG + TIMERECORD_END(2, "Postprocess") +#endif + return true; +} + +} // namespace meituan +} // namespace vision +} // namespace fastdeploy \ No newline at end of file diff --git a/fastdeploy/vision/meituan/yolov6.h b/fastdeploy/vision/meituan/yolov6.h new file mode 100644 index 00000000000..b2d6a062df0 --- /dev/null +++ b/fastdeploy/vision/meituan/yolov6.h @@ -0,0 +1,101 @@ +// Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#pragma once + +#include "fastdeploy/fastdeploy_model.h" +#include "fastdeploy/vision/common/processors/transform.h" +#include "fastdeploy/vision/common/result.h" + +namespace fastdeploy { + +namespace vision { + +namespace meituan { + +class FASTDEPLOY_DECL YOLOv6 : public FastDeployModel { + public: + // 当model_format为ONNX时,无需指定params_file + // 当model_format为Paddle时,则需同时指定model_file & params_file + YOLOv6(const std::string& model_file, const std::string& params_file = "", + const RuntimeOption& custom_option = RuntimeOption(), + const Frontend& model_format = Frontend::ONNX); + + // 定义模型的名称 + std::string ModelName() const { return "meituan/YOLOv6"; } + + // 模型预测接口,即用户调用的接口 + // im 为用户的输入数据,目前对于CV均定义为cv::Mat + // result 为模型预测的输出结构体 + // conf_threshold 为后处理的参数 + // nms_iou_threshold 为后处理的参数 + virtual bool Predict(cv::Mat* im, DetectionResult* result, + float conf_threshold = 0.25, + float nms_iou_threshold = 0.5); + + // 以下为模型在预测时的一些参数,基本是前后处理所需 + // 用户在创建模型后,可根据模型的要求,以及自己的需求 + // 对参数进行修改 + // tuple of (width, height) + std::vector size; + // padding value, size should be same with Channels + std::vector padding_value; + // only pad to the minimum rectange which height and width is times of stride + bool is_mini_pad; + // while is_mini_pad = false and is_no_pad = true, will resize the image to + // the set size + bool is_no_pad; + // if is_scale_up is false, the input image only can be zoom out, the maximum + // resize scale cannot exceed 1.0 + bool is_scale_up; + // padding stride, for is_mini_pad + int stride; + // for offseting the boxes by classes when using NMS, default 4096 in meituan/YOLOv6 + float max_wh; + + private: + // 初始化函数,包括初始化后端,以及其它模型推理需要涉及的操作 + bool Initialize(); + + // 输入图像预处理操作 + // Mat为FastDeploy定义的数据结构 + // FDTensor为预处理后的Tensor数据,传给后端进行推理 + // im_info为预处理过程保存的数据,在后处理中需要用到 + bool Preprocess(Mat* mat, FDTensor* outputs, + std::map>* im_info); + + // 后端推理结果后处理,输出给用户 + // infer_result 为后端推理后的输出Tensor + // result 为模型预测的结果 + // im_info 为预处理记录的信息,后处理用于还原box + // conf_threshold 后处理时过滤box的置信度阈值 + // nms_iou_threshold 后处理时NMS设定的iou阈值 + bool Postprocess( + FDTensor& infer_result, DetectionResult* result, + const std::map>& im_info, + float conf_threshold, float nms_iou_threshold); + + // 查看输入是否为动态维度的 不建议直接使用 不同模型的逻辑可能不一致 + bool IsDynamicInput() const { return is_dynamic_input_; } + + // whether to inference with dynamic shape (e.g ONNX export with dynamic shape or not.) + // meituan/YOLOv6 official 'export_onnx.py' script will export static ONNX by default. + // while is_dynamic_input if 'false', is_mini_pad will force 'false'. This value will + // auto check by fastdeploy after the internal Runtime already initialized. + bool is_dynamic_input_; +}; + +} // namespace meituan +} // namespace vision +} // namespace fastdeploy \ No newline at end of file diff --git a/fastdeploy/vision/ppcls/model.h b/fastdeploy/vision/ppcls/model.h index f649ca1977f..36841d74c68 100644 --- a/fastdeploy/vision/ppcls/model.h +++ b/fastdeploy/vision/ppcls/model.h @@ -16,6 +16,10 @@ class FASTDEPLOY_DECL Model : public FastDeployModel { std::string ModelName() const { return "ppclas-classify"; } + // TODO(jiangjiajun) Batch is on the way + virtual bool Predict(cv::Mat* im, ClassifyResult* result, int topk = 1); + + private: bool Initialize(); bool BuildPreprocessPipelineFromConfig(); @@ -25,10 +29,6 @@ class FASTDEPLOY_DECL Model : public FastDeployModel { bool Postprocess(const FDTensor& infer_result, ClassifyResult* result, int topk = 1); - // TODO(jiangjiajun) Batch is on the way - virtual bool Predict(cv::Mat* im, ClassifyResult* result, int topk = 1); - - private: std::vector> processors_; std::string config_file_; }; diff --git a/fastdeploy/vision/ultralytics/__init__.py b/fastdeploy/vision/ultralytics/__init__.py index 3a5446e0f22..4dcd0d6d458 100644 --- a/fastdeploy/vision/ultralytics/__init__.py +++ b/fastdeploy/vision/ultralytics/__init__.py @@ -41,31 +41,35 @@ def predict(self, input_image, conf_threshold=0.25, nms_iou_threshold=0.5): # 多数是预处理相关,可通过修改如model.size = [1280, 1280]改变预处理时resize的大小(前提是模型支持) @property def size(self): - return self.model.size + return self._model.size @property def padding_value(self): - return self.model.padding_value + return self._model.padding_value @property def is_no_pad(self): - return self.model.is_no_pad + return self._model.is_no_pad @property def is_mini_pad(self): - return self.model.is_mini_pad + return self._model.is_mini_pad @property def is_scale_up(self): - return self.model.is_scale_up + return self._model.is_scale_up @property def stride(self): - return self.model.stride + return self._model.stride @property def max_wh(self): - return self.model.max_wh + return self._model.max_wh + + @property + def multi_label(self): + return self._model.multi_label @size.setter def size(self, wh): @@ -74,43 +78,50 @@ def size(self, wh): assert len(wh) == 2,\ "The value to set `size` must contatins 2 elements means [width, height], but now it contains {} elements.".format( len(wh)) - self.model.size = wh + self._model.size = wh @padding_value.setter def padding_value(self, value): assert isinstance( value, list), "The value to set `padding_value` must be type of list." - self.model.padding_value = value + self._model.padding_value = value @is_no_pad.setter def is_no_pad(self, value): assert isinstance( value, bool), "The value to set `is_no_pad` must be type of bool." - self.model.is_no_pad = value + self._model.is_no_pad = value @is_mini_pad.setter def is_mini_pad(self, value): assert isinstance( value, bool), "The value to set `is_mini_pad` must be type of bool." - self.model.is_mini_pad = value + self._model.is_mini_pad = value @is_scale_up.setter def is_scale_up(self, value): assert isinstance( value, bool), "The value to set `is_scale_up` must be type of bool." - self.model.is_scale_up = value + self._model.is_scale_up = value @stride.setter def stride(self, value): assert isinstance( value, int), "The value to set `stride` must be type of int." - self.model.stride = value + self._model.stride = value @max_wh.setter def max_wh(self, value): assert isinstance( value, float), "The value to set `max_wh` must be type of float." - self.model.max_wh = value + self._model.max_wh = value + + @multi_label.setter + def multi_label(self, value): + assert isinstance( + value, + bool), "The value to set `multi_label` must be type of bool." + self._model.multi_label = value diff --git a/fastdeploy/vision/ultralytics/ultralytics_pybind.cc b/fastdeploy/vision/ultralytics/ultralytics_pybind.cc index 3b73b586fee..c6021434962 100644 --- a/fastdeploy/vision/ultralytics/ultralytics_pybind.cc +++ b/fastdeploy/vision/ultralytics/ultralytics_pybind.cc @@ -36,6 +36,7 @@ void BindUltralytics(pybind11::module& m) { .def_readwrite("is_no_pad", &vision::ultralytics::YOLOv5::is_no_pad) .def_readwrite("is_scale_up", &vision::ultralytics::YOLOv5::is_scale_up) .def_readwrite("stride", &vision::ultralytics::YOLOv5::stride) - .def_readwrite("max_wh", &vision::ultralytics::YOLOv5::max_wh); + .def_readwrite("max_wh", &vision::ultralytics::YOLOv5::max_wh) + .def_readwrite("multi_label", &vision::ultralytics::YOLOv5::multi_label); } } // namespace fastdeploy diff --git a/fastdeploy/vision/ultralytics/yolov5.cc b/fastdeploy/vision/ultralytics/yolov5.cc index 632c825e598..561e917d4a8 100644 --- a/fastdeploy/vision/ultralytics/yolov5.cc +++ b/fastdeploy/vision/ultralytics/yolov5.cc @@ -67,11 +67,27 @@ bool YOLOv5::Initialize() { is_scale_up = false; stride = 32; max_wh = 7680.0; + multi_label = true; if (!InitRuntime()) { FDERROR << "Failed to initialize fastdeploy backend." << std::endl; return false; } + // Check if the input shape is dynamic after Runtime already initialized, + // Note that, We need to force is_mini_pad 'false' to keep static + // shape after padding (LetterBox) when the is_dynamic_shape is 'false'. + is_dynamic_input_ = false; + auto shape = InputInfoOfRuntime(0).shape; + for (int i = 0; i < shape.size(); ++i) { + // if height or width is dynamic + if (i >= 2 && shape[i] <= 0) { + is_dynamic_input_ = true; + break; + } + } + if (!is_dynamic_input_) { + is_mini_pad = false; + } return true; } @@ -113,10 +129,14 @@ bool YOLOv5::Preprocess(Mat* mat, FDTensor* output, bool YOLOv5::Postprocess( FDTensor& infer_result, DetectionResult* result, const std::map>& im_info, - float conf_threshold, float nms_iou_threshold) { + float conf_threshold, float nms_iou_threshold, bool multi_label) { FDASSERT(infer_result.shape[0] == 1, "Only support batch =1 now."); result->Clear(); - result->Reserve(infer_result.shape[1]); + if (multi_label) { + result->Reserve(infer_result.shape[1] * (infer_result.shape[2] - 5)); + } else { + result->Reserve(infer_result.shape[1]); + } if (infer_result.dtype != FDDataType::FP32) { FDERROR << "Only support post process with float32 data." << std::endl; return false; @@ -125,22 +145,44 @@ bool YOLOv5::Postprocess( for (size_t i = 0; i < infer_result.shape[1]; ++i) { int s = i * infer_result.shape[2]; float confidence = data[s + 4]; - float* max_class_score = - std::max_element(data + s + 5, data + s + infer_result.shape[2]); - confidence *= (*max_class_score); - // filter boxes by conf_threshold - if (confidence <= conf_threshold) { - continue; + if (multi_label) { + for (size_t j = 5; j < infer_result.shape[2]; ++j) { + confidence = data[s + 4]; + float* class_score = data + s + j; + confidence *= (*class_score); + // filter boxes by conf_threshold + if (confidence <= conf_threshold) { + continue; + } + int32_t label_id = std::distance(data + s + 5, class_score); + + // convert from [x, y, w, h] to [x1, y1, x2, y2] + result->boxes.emplace_back(std::array{ + data[s] - data[s + 2] / 2.0f + label_id * max_wh, + data[s + 1] - data[s + 3] / 2.0f + label_id * max_wh, + data[s + 0] + data[s + 2] / 2.0f + label_id * max_wh, + data[s + 1] + data[s + 3] / 2.0f + label_id * max_wh}); + result->label_ids.push_back(label_id); + result->scores.push_back(confidence); + } + } else { + float* max_class_score = + std::max_element(data + s + 5, data + s + infer_result.shape[2]); + confidence *= (*max_class_score); + // filter boxes by conf_threshold + if (confidence <= conf_threshold) { + continue; + } + int32_t label_id = std::distance(data + s + 5, max_class_score); + // convert from [x, y, w, h] to [x1, y1, x2, y2] + result->boxes.emplace_back(std::array{ + data[s] - data[s + 2] / 2.0f + label_id * max_wh, + data[s + 1] - data[s + 3] / 2.0f + label_id * max_wh, + data[s + 0] + data[s + 2] / 2.0f + label_id * max_wh, + data[s + 1] + data[s + 3] / 2.0f + label_id * max_wh}); + result->label_ids.push_back(label_id); + result->scores.push_back(confidence); } - int32_t label_id = std::distance(data + s + 5, max_class_score); - // convert from [x, y, w, h] to [x1, y1, x2, y2] - result->boxes.emplace_back(std::array{ - data[s] - data[s + 2] / 2.0f + label_id * max_wh, - data[s + 1] - data[s + 3] / 2.0f + label_id * max_wh, - data[s + 0] + data[s + 2] / 2.0f + label_id * max_wh, - data[s + 1] + data[s + 3] / 2.0f + label_id * max_wh}); - result->label_ids.push_back(label_id); - result->scores.push_back(confidence); } utils::NMS(result, nms_iou_threshold); @@ -214,7 +256,7 @@ bool YOLOv5::Predict(cv::Mat* im, DetectionResult* result, float conf_threshold, #endif if (!Postprocess(output_tensors[0], result, im_info, conf_threshold, - nms_iou_threshold)) { + nms_iou_threshold, multi_label)) { FDERROR << "Failed to post process." << std::endl; return false; } diff --git a/fastdeploy/vision/ultralytics/yolov5.h b/fastdeploy/vision/ultralytics/yolov5.h index fab44a6e837..573b0294f2b 100644 --- a/fastdeploy/vision/ultralytics/yolov5.h +++ b/fastdeploy/vision/ultralytics/yolov5.h @@ -30,28 +30,7 @@ class FASTDEPLOY_DECL YOLOv5 : public FastDeployModel { const Frontend& model_format = Frontend::ONNX); // 定义模型的名称 - virtual std::string ModelName() const { return "ultralytics/yolov5"; } - - // 初始化函数,包括初始化后端,以及其它模型推理需要涉及的操作 - virtual bool Initialize(); - - // 输入图像预处理操作 - // Mat为FastDeploy定义的数据结构 - // FDTensor为预处理后的Tensor数据,传给后端进行推理 - // im_info为预处理过程保存的数据,在后处理中需要用到 - virtual bool Preprocess(Mat* mat, FDTensor* outputs, - std::map>* im_info); - - // 后端推理结果后处理,输出给用户 - // infer_result 为后端推理后的输出Tensor - // result 为模型预测的结果 - // im_info 为预处理记录的信息,后处理用于还原box - // conf_threshold 后处理时过滤box的置信度阈值 - // nms_iou_threshold 后处理时NMS设定的iou阈值 - virtual bool Postprocess( - FDTensor& infer_result, DetectionResult* result, - const std::map>& im_info, - float conf_threshold, float nms_iou_threshold); + std::string ModelName() const { return "ultralytics/yolov5"; } // 模型预测接口,即用户调用的接口 // im 为用户的输入数据,目前对于CV均定义为cv::Mat @@ -60,7 +39,7 @@ class FASTDEPLOY_DECL YOLOv5 : public FastDeployModel { // nms_iou_threshold 为后处理的参数 virtual bool Predict(cv::Mat* im, DetectionResult* result, float conf_threshold = 0.25, - float nms_iou_threshold = 0.5); + float nms_iou_threshold = 0.5); // 以下为模型在预测时的一些参数,基本是前后处理所需 // 用户在创建模型后,可根据模型的要求,以及自己的需求 @@ -81,7 +60,42 @@ class FASTDEPLOY_DECL YOLOv5 : public FastDeployModel { int stride; // for offseting the boxes by classes when using NMS float max_wh; + // for different strategies to get boxes when postprocessing + bool multi_label; + + private: + // 初始化函数,包括初始化后端,以及其它模型推理需要涉及的操作 + bool Initialize(); + + // 输入图像预处理操作 + // Mat为FastDeploy定义的数据结构 + // FDTensor为预处理后的Tensor数据,传给后端进行推理 + // im_info为预处理过程保存的数据,在后处理中需要用到 + bool Preprocess(Mat* mat, FDTensor* outputs, + std::map>* im_info); + + // 后端推理结果后处理,输出给用户 + // infer_result 为后端推理后的输出Tensor + // result 为模型预测的结果 + // im_info 为预处理记录的信息,后处理用于还原box + // conf_threshold 后处理时过滤box的置信度阈值 + // nms_iou_threshold 后处理时NMS设定的iou阈值 + // multi_label 后处理时box选取是否采用多标签方式 + bool Postprocess( + FDTensor& infer_result, DetectionResult* result, + const std::map>& im_info, + float conf_threshold, float nms_iou_threshold, bool multi_label); + + // 查看输入是否为动态维度的 不建议直接使用 不同模型的逻辑可能不一致 + bool IsDynamicInput() const { return is_dynamic_input_; } + + // whether to inference with dynamic shape (e.g ONNX export with dynamic shape or not.) + // YOLOv5 official 'export_onnx.py' script will export dynamic ONNX by default. + // while is_dynamic_shape if 'false', is_mini_pad will force 'false'. This value will + // auto check by fastdeploy after the internal Runtime already initialized. + bool is_dynamic_input_; }; + } // namespace ultralytics } // namespace vision } // namespace fastdeploy diff --git a/fastdeploy/vision/vision_pybind.cc b/fastdeploy/vision/vision_pybind.cc index f3c3f0052da..23d0e91e0e2 100644 --- a/fastdeploy/vision/vision_pybind.cc +++ b/fastdeploy/vision/vision_pybind.cc @@ -18,6 +18,8 @@ namespace fastdeploy { void BindPpClsModel(pybind11::module& m); void BindUltralytics(pybind11::module& m); +void BindMeituan(pybind11::module& m); +void BindMegvii(pybind11::module& m); #ifdef ENABLE_VISION_VISUALIZE void BindVisualize(pybind11::module& m); #endif @@ -40,6 +42,10 @@ void BindVision(pybind11::module& m) { BindPpClsModel(m); BindUltralytics(m); + BindMeituan(m); + BindMegvii(m); +#ifdef ENABLE_VISION_VISUALIZE BindVisualize(m); +#endif } } // namespace fastdeploy diff --git a/model_zoo/.gitignore b/model_zoo/.gitignore new file mode 100644 index 00000000000..e3919c57f90 --- /dev/null +++ b/model_zoo/.gitignore @@ -0,0 +1,12 @@ +*.png +*.jpg +*.jpeg +*.onnx +*.zip +*.tar +*.pd* +*.engine +*.trt +*.nb +*.tgz +*.gz diff --git a/model_zoo/vision/yolov5/api.md b/model_zoo/vision/yolov5/api.md index 8c9d5675d04..66d6acdc772 100644 --- a/model_zoo/vision/yolov5/api.md +++ b/model_zoo/vision/yolov5/api.md @@ -23,7 +23,7 @@ YOLOv5模型加载和初始化,当model_format为`fd.Frontend.ONNX`时,只 > > **参数** > -> > * **image_data**(np.ndarray): 输入数据,注意需为HWC,RGB格式 +> > * **image_data**(np.ndarray): 输入数据,注意需为HWC,BGR格式 > > * **conf_threshold**(float): 检测框置信度过滤阈值 > > * **nms_iou_threshold**(float): NMS处理过程中iou阈值 @@ -49,9 +49,9 @@ YOLOv5模型加载和初始化,当model_format为`Frontend::ONNX`时,只需 > * **runtime_option**(RuntimeOption): 后端推理配置,默认为None,即采用默认配置 > * **model_format**(Frontend): 模型格式 -#### predict函数 +#### Predict函数 > ``` -> YOLOv5::predict(cv::Mat* im, DetectionResult* result, +> YOLOv5::Predict(cv::Mat* im, DetectionResult* result, > float conf_threshold = 0.25, > float nms_iou_threshold = 0.5) > ``` @@ -59,7 +59,7 @@ YOLOv5模型加载和初始化,当model_format为`Frontend::ONNX`时,只需 > > **参数** > -> > * **im**: 输入图像,注意需为HWC,RGB格式 +> > * **im**: 输入图像,注意需为HWC,BGR格式 > > * **result**: 检测结果,包括检测框,各个框的置信度 > > * **conf_threshold**: 检测框置信度过滤阈值 > > * **nms_iou_threshold**: NMS处理过程中iou阈值 diff --git a/model_zoo/vision/yolov5/cpp/CMakeLists.txt b/model_zoo/vision/yolov5/cpp/CMakeLists.txt index 5b909d02028..13ddc9d21f4 100644 --- a/model_zoo/vision/yolov5/cpp/CMakeLists.txt +++ b/model_zoo/vision/yolov5/cpp/CMakeLists.txt @@ -5,7 +5,7 @@ CMAKE_MINIMUM_REQUIRED (VERSION 3.16) # add_definitions(-D_GLIBCXX_USE_CXX11_ABI=0) # 指定下载解压后的fastdeploy库路径 -set(FASTDEPLOY_INSTALL_DIR ${PROJECT_SOURCE_DIR}/fastdeploy-linux-x64-0.0.3/) +set(FASTDEPLOY_INSTALL_DIR ${PROJECT_SOURCE_DIR}/fastdeploy-linux-x64-0.3.0/) include(${FASTDEPLOY_INSTALL_DIR}/FastDeploy.cmake) diff --git a/model_zoo/vision/yolov6/README.md b/model_zoo/vision/yolov6/README.md new file mode 100644 index 00000000000..5fa3578bfce --- /dev/null +++ b/model_zoo/vision/yolov6/README.md @@ -0,0 +1,45 @@ +# YOLOv6部署示例 + +本文档说明如何进行[YOLOv6](https://github.com/meituan/YOLOv6)的快速部署推理。本目录结构如下 +``` +. +├── cpp # C++ 代码目录 +│   ├── CMakeLists.txt # C++ 代码编译CMakeLists文件 +│   ├── README.md # C++ 代码编译部署文档 +│   └── yolov6.cc # C++ 示例代码 +├── README.md # YOLOv6 部署文档 +└── yolov6.py # Python示例代码 +``` + +## 安装FastDeploy + +使用如下命令安装FastDeploy,注意到此处安装的是`vision-cpu`,也可根据需求安装`vision-gpu` +``` +# 安装fastdeploy-python工具 +pip install fastdeploy-python + +# 安装vision-cpu模块 +fastdeploy install vision-cpu +``` + +## Python部署 + +执行如下代码即会自动下载YOLOv6模型和测试图片 +``` +python yolov6.py +``` + +执行完成后会将可视化结果保存在本地`vis_result.jpg`,同时输出检测结果如下 +``` +DetectionResult: [xmin, ymin, xmax, ymax, score, label_id] +11.772949,229.269287, 792.933838, 748.294189, 0.954794, 5 +667.140381,396.185455, 807.701721, 881.810120, 0.900997, 0 +223.271011,405.105743, 345.740723, 859.328552, 0.898938, 0 +50.135777,405.863129, 245.485519, 904.153809, 0.888936, 0 +0.000000,549.002869, 77.864723, 869.455017, 0.614145, 0 +``` + +## 其它文档 + +- [C++部署](./cpp/README.md) +- [YOLOv6 API文档](./api.md) diff --git a/model_zoo/vision/yolov6/api.md b/model_zoo/vision/yolov6/api.md new file mode 100644 index 00000000000..eca89f06aa4 --- /dev/null +++ b/model_zoo/vision/yolov6/api.md @@ -0,0 +1,71 @@ +# YOLOv6 API说明 + +## Python API + +### YOLOv6类 +``` +fastdeploy.vision.meituan.YOLOv6(model_file, params_file=None, runtime_option=None, model_format=fd.Frontend.ONNX) +``` +YOLOv6模型加载和初始化,当model_format为`fd.Frontend.ONNX`时,只需提供model_file,如`yolov6s.onnx`;当model_format为`fd.Frontend.PADDLE`时,则需同时提供model_file和params_file。 + +**参数** + +> * **model_file**(str): 模型文件路径 +> * **params_file**(str): 参数文件路径 +> * **runtime_option**(RuntimeOption): 后端推理配置,默认为None,即采用默认配置 +> * **model_format**(Frontend): 模型格式 + +#### predict函数 +> ``` +> YOLOv6.predict(image_data, conf_threshold=0.25, nms_iou_threshold=0.5) +> ``` +> 模型预测结口,输入图像直接输出检测结果。 +> +> **参数** +> +> > * **image_data**(np.ndarray): 输入数据,注意需为HWC,BGR格式 +> > * **conf_threshold**(float): 检测框置信度过滤阈值 +> > * **nms_iou_threshold**(float): NMS处理过程中iou阈值 + +示例代码参考[yolov6.py](./yolov6.py) + + +## C++ API + +### YOLOv6类 +``` +fastdeploy::vision::meituan::YOLOv6( + const string& model_file, + const string& params_file = "", + const RuntimeOption& runtime_option = RuntimeOption(), + const Frontend& model_format = Frontend::ONNX) +``` +YOLOv6模型加载和初始化,当model_format为`Frontend::ONNX`时,只需提供model_file,如`yolov6s.onnx`;当model_format为`Frontend::PADDLE`时,则需同时提供model_file和params_file。 + +**参数** + +> * **model_file**(str): 模型文件路径 +> * **params_file**(str): 参数文件路径 +> * **runtime_option**(RuntimeOption): 后端推理配置,默认为None,即采用默认配置 +> * **model_format**(Frontend): 模型格式 + +#### Predict函数 +> ``` +> YOLOv6::Predict(cv::Mat* im, DetectionResult* result, +> float conf_threshold = 0.25, +> float nms_iou_threshold = 0.5) +> ``` +> 模型预测接口,输入图像直接输出检测结果。 +> +> **参数** +> +> > * **im**: 输入图像,注意需为HWC,BGR格式 +> > * **result**: 检测结果,包括检测框,各个框的置信度 +> > * **conf_threshold**: 检测框置信度过滤阈值 +> > * **nms_iou_threshold**: NMS处理过程中iou阈值 + +示例代码参考[cpp/yolov6.cc](cpp/yolov6.cc) + +## 其它API使用 + +- [模型部署RuntimeOption配置](../../../docs/api/runtime_option.md) diff --git a/model_zoo/vision/yolov6/cpp/CMakeLists.txt b/model_zoo/vision/yolov6/cpp/CMakeLists.txt new file mode 100644 index 00000000000..28987f7f75c --- /dev/null +++ b/model_zoo/vision/yolov6/cpp/CMakeLists.txt @@ -0,0 +1,17 @@ +PROJECT(yolov6_demo C CXX) +CMAKE_MINIMUM_REQUIRED (VERSION 3.16) + +# 在低版本ABI环境中,通过如下代码进行兼容性编译 +# add_definitions(-D_GLIBCXX_USE_CXX11_ABI=0) + +# 指定下载解压后的fastdeploy库路径 +set(FASTDEPLOY_INSTALL_DIR ${PROJECT_SOURCE_DIR}/fastdeploy-linux-x64-0.0.3/) + +include(${FASTDEPLOY_INSTALL_DIR}/FastDeploy.cmake) + +# 添加FastDeploy依赖头文件 +include_directories(${FASTDEPLOY_INCS}) + +add_executable(yolov6_demo ${PROJECT_SOURCE_DIR}/yolov6.cc) +# 添加FastDeploy库依赖 +target_link_libraries(yolov6_demo ${FASTDEPLOY_LIBS}) diff --git a/model_zoo/vision/yolov6/cpp/README.md b/model_zoo/vision/yolov6/cpp/README.md new file mode 100644 index 00000000000..c7b4d4d7ab3 --- /dev/null +++ b/model_zoo/vision/yolov6/cpp/README.md @@ -0,0 +1,30 @@ +# 编译YOLOv6示例 + + +``` +# 下载和解压预测库 +wget https://bj.bcebos.com/paddle2onnx/fastdeploy/fastdeploy-linux-x64-0.0.3.tgz +tar xvf fastdeploy-linux-x64-0.0.3.tgz + +# 编译示例代码 +mkdir build & cd build +cmake .. +make -j + +# 下载模型和图片 +wget https://github.com/meituan/YOLOv6/releases/download/0.1.0/yolov6s.onnx +wget https://raw.githubusercontent.com/ultralytics/yolov5/master/data/images/bus.jpg + +# 执行 +./yolov6_demo +``` + +执行完后可视化的结果保存在本地`vis_result.jpg`,同时会将检测框输出在终端,如下所示 +``` +DetectionResult: [xmin, ymin, xmax, ymax, score, label_id] +11.772949,229.269287, 792.933838, 748.294189, 0.954794, 5 +667.140381,396.185455, 807.701721, 881.810120, 0.900997, 0 +223.271011,405.105743, 345.740723, 859.328552, 0.898938, 0 +50.135777,405.863129, 245.485519, 904.153809, 0.888936, 0 +0.000000,549.002869, 77.864723, 869.455017, 0.614145, 0 +``` diff --git a/model_zoo/vision/yolov6/cpp/yolov6.cc b/model_zoo/vision/yolov6/cpp/yolov6.cc new file mode 100644 index 00000000000..62d2fa0be35 --- /dev/null +++ b/model_zoo/vision/yolov6/cpp/yolov6.cc @@ -0,0 +1,40 @@ +// Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "fastdeploy/vision.h" + +int main() { + namespace vis = fastdeploy::vision; + auto model = vis::meituan::YOLOv6("yolov6s.onnx"); + if (!model.Initialized()) { + std::cerr << "Init Failed." << std::endl; + return -1; + } + cv::Mat im = cv::imread("bus.jpg"); + cv::Mat vis_im = im.clone(); + + vis::DetectionResult res; + if (!model.Predict(&im, &res)) { + std::cerr << "Prediction Failed." << std::endl; + return -1; + } + + // 输出预测框结果 + std::cout << res.Str() << std::endl; + + // 可视化预测结果 + vis::Visualize::VisDetection(&vis_im, res); + cv::imwrite("vis_result.jpg", vis_im); + return 0; +} diff --git a/model_zoo/vision/yolov6/yolov6.py b/model_zoo/vision/yolov6/yolov6.py new file mode 100644 index 00000000000..fa8aca07409 --- /dev/null +++ b/model_zoo/vision/yolov6/yolov6.py @@ -0,0 +1,23 @@ +import fastdeploy as fd +import cv2 + +# 下载模型和测试图片 +model_url = "https://github.com/meituan/YOLOv6/releases/download/0.1.0/yolov6s.onnx" +test_jpg_url = "https://raw.githubusercontent.com/ultralytics/yolov5/master/data/images/bus.jpg" +fd.download(model_url, ".", show_progress=True) +fd.download(test_jpg_url, ".", show_progress=True) + +# 加载模型 +model = fd.vision.meituan.YOLOv6("yolov6s.onnx") + +# 预测图片 +im = cv2.imread("bus.jpg") +result = model.predict(im, conf_threshold=0.25, nms_iou_threshold=0.5) + +# 可视化结果 +fd.vision.visualize.vis_detection(im, result) +cv2.imwrite("vis_result.jpg", im) + +# 输出预测结果 +print(result) +print(model.runtime_option) diff --git a/model_zoo/vision/yolox/README.md b/model_zoo/vision/yolox/README.md new file mode 100644 index 00000000000..52fca9de722 --- /dev/null +++ b/model_zoo/vision/yolox/README.md @@ -0,0 +1,45 @@ +# YOLOX部署示例 + +本文档说明如何进行[YOLOX](https://github.com/Megvii-BaseDetection/YOLOX)的快速部署推理。本目录结构如下 +``` +. +├── cpp # C++ 代码目录 +│   ├── CMakeLists.txt # C++ 代码编译CMakeLists文件 +│   ├── README.md # C++ 代码编译部署文档 +│   └── yolox.cc # C++ 示例代码 +├── README.md # YOLOX 部署文档 +└── yolox.py # Python示例代码 +``` + +## 安装FastDeploy + +使用如下命令安装FastDeploy,注意到此处安装的是`vision-cpu`,也可根据需求安装`vision-gpu` +``` +# 安装fastdeploy-python工具 +pip install fastdeploy-python + +# 安装vision-cpu模块 +fastdeploy install vision-cpu +``` + +## Python部署 + +执行如下代码即会自动下载YOLOX模型和测试图片 +``` +python yolox.py +``` + +执行完成后会将可视化结果保存在本地`vis_result.jpg`,同时输出检测结果如下 +``` +DetectionResult: [xmin, ymin, xmax, ymax, score, label_id] +17.151855,225.294434, 805.329712, 735.578613, 0.940478, 5 +671.162109,387.403961, 809.000000, 879.525513, 0.909566, 0 +54.373432,400.188110, 204.652756, 893.662537, 0.894507, 0 +221.339310,406.614960, 347.045593, 857.299927, 0.887144, 0 +0.083759,554.987305, 61.894527, 881.098816, 0.450202, 0 +``` + +## 其它文档 + +- [C++部署](./cpp/README.md) +- [YOLOX API文档](./api.md) diff --git a/model_zoo/vision/yolox/api.md b/model_zoo/vision/yolox/api.md new file mode 100644 index 00000000000..c7a6f254b1e --- /dev/null +++ b/model_zoo/vision/yolox/api.md @@ -0,0 +1,71 @@ +# YOLOX API说明 + +## Python API + +### YOLOX类 +``` +fastdeploy.vision.megvii.YOLOX(model_file, params_file=None, runtime_option=None, model_format=fd.Frontend.ONNX) +``` +YOLOX模型加载和初始化,当model_format为`fd.Frontend.ONNX`时,只需提供model_file,如`yolox_s.onnx`;当model_format为`fd.Frontend.PADDLE`时,则需同时提供model_file和params_file。 + +**参数** + +> * **model_file**(str): 模型文件路径 +> * **params_file**(str): 参数文件路径 +> * **runtime_option**(RuntimeOption): 后端推理配置,默认为None,即采用默认配置 +> * **model_format**(Frontend): 模型格式 + +#### predict函数 +> ``` +> YOLOX.predict(image_data, conf_threshold=0.25, nms_iou_threshold=0.5) +> ``` +> 模型预测结口,输入图像直接输出检测结果。 +> +> **参数** +> +> > * **image_data**(np.ndarray): 输入数据,注意需为HWC,BGR格式 +> > * **conf_threshold**(float): 检测框置信度过滤阈值 +> > * **nms_iou_threshold**(float): NMS处理过程中iou阈值 + +示例代码参考[yolox.py](./yolox.py) + + +## C++ API + +### YOLOX类 +``` +fastdeploy::vision::megvii::YOLOX( + const string& model_file, + const string& params_file = "", + const RuntimeOption& runtime_option = RuntimeOption(), + const Frontend& model_format = Frontend::ONNX) +``` +YOLOX模型加载和初始化,当model_format为`Frontend::ONNX`时,只需提供model_file,如`yolox_s.onnx`;当model_format为`Frontend::PADDLE`时,则需同时提供model_file和params_file。 + +**参数** + +> * **model_file**(str): 模型文件路径 +> * **params_file**(str): 参数文件路径 +> * **runtime_option**(RuntimeOption): 后端推理配置,默认为None,即采用默认配置 +> * **model_format**(Frontend): 模型格式 + +#### Predict函数 +> ``` +> YOLOX::Predict(cv::Mat* im, DetectionResult* result, +> float conf_threshold = 0.25, +> float nms_iou_threshold = 0.5) +> ``` +> 模型预测接口,输入图像直接输出检测结果。 +> +> **参数** +> +> > * **im**: 输入图像,注意需为HWC,BGR格式 +> > * **result**: 检测结果,包括检测框,各个框的置信度 +> > * **conf_threshold**: 检测框置信度过滤阈值 +> > * **nms_iou_threshold**: NMS处理过程中iou阈值 + +示例代码参考[cpp/yolox.cc](cpp/yolox.cc) + +## 其它API使用 + +- [模型部署RuntimeOption配置](../../../docs/api/runtime_option.md) diff --git a/model_zoo/vision/yolox/cpp/CMakeLists.txt b/model_zoo/vision/yolox/cpp/CMakeLists.txt new file mode 100644 index 00000000000..fe9668f6a0a --- /dev/null +++ b/model_zoo/vision/yolox/cpp/CMakeLists.txt @@ -0,0 +1,17 @@ +PROJECT(yolox_demo C CXX) +CMAKE_MINIMUM_REQUIRED (VERSION 3.16) + +# 在低版本ABI环境中,通过如下代码进行兼容性编译 +# add_definitions(-D_GLIBCXX_USE_CXX11_ABI=0) + +# 指定下载解压后的fastdeploy库路径 +set(FASTDEPLOY_INSTALL_DIR ${PROJECT_SOURCE_DIR}/fastdeploy-linux-x64-0.0.3/) + +include(${FASTDEPLOY_INSTALL_DIR}/FastDeploy.cmake) + +# 添加FastDeploy依赖头文件 +include_directories(${FASTDEPLOY_INCS}) + +add_executable(yolox_demo ${PROJECT_SOURCE_DIR}/yolox.cc) +# 添加FastDeploy库依赖 +target_link_libraries(yolox_demo ${FASTDEPLOY_LIBS}) diff --git a/model_zoo/vision/yolox/cpp/README.md b/model_zoo/vision/yolox/cpp/README.md new file mode 100644 index 00000000000..b63d93872b9 --- /dev/null +++ b/model_zoo/vision/yolox/cpp/README.md @@ -0,0 +1,30 @@ +# 编译YOLOX示例 + + +``` +# 下载和解压预测库 +wget https://bj.bcebos.com/paddle2onnx/fastdeploy/fastdeploy-linux-x64-0.0.3.tgz +tar xvf fastdeploy-linux-x64-0.0.3.tgz + +# 编译示例代码 +mkdir build & cd build +cmake .. +make -j + +# 下载模型和图片 +wget https://github.com/Megvii-BaseDetection/YOLOX/releases/download/0.1.1rc0/yolox_s.onnx +wget https://raw.githubusercontent.com/ultralytics/yolov5/master/data/images/bus.jpg + +# 执行 +./yolox_demo +``` + +执行完后可视化的结果保存在本地`vis_result.jpg`,同时会将检测框输出在终端,如下所示 +``` +DetectionResult: [xmin, ymin, xmax, ymax, score, label_id] +17.151855,225.294434, 805.329712, 735.578613, 0.940478, 5 +671.162109,387.403961, 809.000000, 879.525513, 0.909566, 0 +54.373432,400.188110, 204.652756, 893.662537, 0.894507, 0 +221.339310,406.614960, 347.045593, 857.299927, 0.887144, 0 +0.083759,554.987305, 61.894527, 881.098816, 0.450202, 0 +``` diff --git a/model_zoo/vision/yolox/cpp/yolox.cc b/model_zoo/vision/yolox/cpp/yolox.cc new file mode 100644 index 00000000000..934a50bea8e --- /dev/null +++ b/model_zoo/vision/yolox/cpp/yolox.cc @@ -0,0 +1,40 @@ +// Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "fastdeploy/vision.h" + +int main() { + namespace vis = fastdeploy::vision; + auto model = vis::megvii::YOLOX("yolox_s.onnx"); + if (!model.Initialized()) { + std::cerr << "Init Failed." << std::endl; + return -1; + } + cv::Mat im = cv::imread("bus.jpg"); + cv::Mat vis_im = im.clone(); + + vis::DetectionResult res; + if (!model.Predict(&im, &res)) { + std::cerr << "Prediction Failed." << std::endl; + return -1; + } + + // 输出预测框结果 + std::cout << res.Str() << std::endl; + + // 可视化预测结果 + vis::Visualize::VisDetection(&vis_im, res); + cv::imwrite("vis_result.jpg", vis_im); + return 0; +} diff --git a/model_zoo/vision/yolox/yolox.py b/model_zoo/vision/yolox/yolox.py new file mode 100644 index 00000000000..8fd1a8a021a --- /dev/null +++ b/model_zoo/vision/yolox/yolox.py @@ -0,0 +1,23 @@ +import fastdeploy as fd +import cv2 + +# 下载模型和测试图片 +model_url = "https://github.com/Megvii-BaseDetection/YOLOX/releases/download/0.1.1rc0/yolox_s.onnx" +test_jpg_url = "https://raw.githubusercontent.com/ultralytics/yolov5/master/data/images/bus.jpg" +fd.download(model_url, ".", show_progress=True) +fd.download(test_jpg_url, ".", show_progress=True) + +# 加载模型 +model = fd.vision.megvii.YOLOX("yolox_s.onnx") + +# 预测图片 +im = cv2.imread("bus.jpg") +result = model.predict(im, conf_threshold=0.25, nms_iou_threshold=0.5) + +# 可视化结果 +fd.vision.visualize.vis_detection(im, result) +cv2.imwrite("vis_result.jpg", im) + +# 输出预测结果 +print(result) +print(model.runtime_option)