mirror of
https://github.com/PaddlePaddle/FastDeploy.git
synced 2026-04-23 00:17:25 +08:00
Add UltraFace Model support (#43)
* update .gitignore * Added checking for cmake include dir * fixed missing trt_backend option bug when init from trt * remove un-need data layout and add pre-check for dtype * changed RGB2BRG to BGR2RGB in ppcls model * add model_zoo yolov6 c++/python demo * fixed CMakeLists.txt typos * update yolov6 cpp/README.md * add yolox c++/pybind and model_zoo demo * move some helpers to private * fixed CMakeLists.txt typos * add normalize with alpha and beta * add version notes for yolov5/yolov6/yolox * add copyright to yolov5.cc * revert normalize * fixed some bugs in yolox * Add UltraFace Model support
This commit is contained in:
@@ -14,3 +14,4 @@ fastdeploy/LICENSE*
|
||||
fastdeploy/ThirdPartyNotices*
|
||||
*.so*
|
||||
fastdeploy/libs/third_libs
|
||||
csrcs/fastdeploy/core/config.h
|
||||
@@ -16,6 +16,7 @@
|
||||
#include "fastdeploy/core/config.h"
|
||||
#ifdef ENABLE_VISION
|
||||
#include "fastdeploy/vision/deepcam/yolov5face.h"
|
||||
#include "fastdeploy/vision/linzaer/ultraface.h"
|
||||
#include "fastdeploy/vision/megvii/yolox.h"
|
||||
#include "fastdeploy/vision/meituan/yolov6.h"
|
||||
#include "fastdeploy/vision/ppcls/model.h"
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
// 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 BindLinzaer(pybind11::module& m) {
|
||||
auto linzaer_module = m.def_submodule(
|
||||
"linzaer",
|
||||
"https://github.com/Linzaer/Ultra-Light-Fast-Generic-Face-Detector-1MB");
|
||||
pybind11::class_<vision::linzaer::UltraFace, FastDeployModel>(linzaer_module,
|
||||
"UltraFace")
|
||||
.def(pybind11::init<std::string, std::string, RuntimeOption, Frontend>())
|
||||
.def("predict",
|
||||
[](vision::linzaer::UltraFace& self, pybind11::array& data,
|
||||
float conf_threshold, float nms_iou_threshold) {
|
||||
auto mat = PyArrayToCvMat(data);
|
||||
vision::FaceDetectionResult res;
|
||||
self.Predict(&mat, &res, conf_threshold, nms_iou_threshold);
|
||||
return res;
|
||||
})
|
||||
.def_readwrite("size", &vision::linzaer::UltraFace::size);
|
||||
}
|
||||
} // namespace fastdeploy
|
||||
@@ -0,0 +1,220 @@
|
||||
// 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/linzaer/ultraface.h"
|
||||
#include "fastdeploy/utils/perf.h"
|
||||
#include "fastdeploy/vision/utils/utils.h"
|
||||
|
||||
namespace fastdeploy {
|
||||
|
||||
namespace vision {
|
||||
|
||||
namespace linzaer {
|
||||
|
||||
UltraFace::UltraFace(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 UltraFace::Initialize() {
|
||||
// parameters for preprocess
|
||||
size = {320, 240};
|
||||
|
||||
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 UltraFace::Preprocess(
|
||||
Mat* mat, FDTensor* output,
|
||||
std::map<std::string, std::array<float, 2>>* im_info) {
|
||||
// ultraface's preprocess steps
|
||||
// 1. resize
|
||||
// 2. BGR->RGB
|
||||
// 3. HWC->CHW
|
||||
int resize_w = size[0];
|
||||
int resize_h = size[1];
|
||||
if (resize_h != mat->Height() || resize_w != mat->Width()) {
|
||||
Resize::Run(mat, resize_w, resize_h);
|
||||
}
|
||||
|
||||
BGR2RGB::Run(mat);
|
||||
// Compute `result = mat * alpha + beta` directly by channel
|
||||
// Reference: detect_imgs_onnx.py#L73
|
||||
std::vector<float> alpha = {1.0f / 128.0f, 1.0f / 128.0f, 1.0f / 128.0f};
|
||||
std::vector<float> beta = {-127.0f * (1.0f / 128.0f),
|
||||
-127.0f * (1.0f / 128.0f),
|
||||
-127.0f * (1.0f / 128.0f)}; // RGB;
|
||||
Convert::Run(mat, alpha, beta);
|
||||
|
||||
// Record output shape of preprocessed image
|
||||
(*im_info)["output_shape"] = {static_cast<float>(mat->Height()),
|
||||
static_cast<float>(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 UltraFace::Postprocess(
|
||||
std::vector<FDTensor>& infer_result, FaceDetectionResult* result,
|
||||
const std::map<std::string, std::array<float, 2>>& im_info,
|
||||
float conf_threshold, float nms_iou_threshold) {
|
||||
// ultraface has 2 output tensors, scores & boxes
|
||||
FDASSERT(
|
||||
(infer_result.size() == 2),
|
||||
"The default number of output tensor must be 2 according to ultraface.");
|
||||
FDTensor& scores_tensor = infer_result.at(0); // (1,4420,2)
|
||||
FDTensor& boxes_tensor = infer_result.at(1); // (1,4420,4)
|
||||
FDASSERT((scores_tensor.shape[0] == 1), "Only support batch =1 now.");
|
||||
FDASSERT((boxes_tensor.shape[0] == 1), "Only support batch =1 now.");
|
||||
|
||||
result->Clear();
|
||||
// must be setup landmarks_per_face before reserve.
|
||||
// ultraface detector does not detect landmarks by default.
|
||||
result->landmarks_per_face = 0;
|
||||
if (scores_tensor.dtype != FDDataType::FP32) {
|
||||
FDERROR << "Only support post process with float32 data." << std::endl;
|
||||
return false;
|
||||
}
|
||||
if (boxes_tensor.dtype != FDDataType::FP32) {
|
||||
FDERROR << "Only support post process with float32 data." << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
float* scores_ptr = static_cast<float*>(scores_tensor.Data());
|
||||
float* boxes_ptr = static_cast<float*>(boxes_tensor.Data());
|
||||
const size_t num_bboxes = boxes_tensor.shape[1]; // e.g 4420
|
||||
// fetch original image shape
|
||||
auto iter_ipt = im_info.find("input_shape");
|
||||
FDASSERT((iter_ipt != im_info.end()),
|
||||
"Cannot find input_shape from im_info.");
|
||||
float ipt_h = iter_ipt->second[0];
|
||||
float ipt_w = iter_ipt->second[1];
|
||||
|
||||
// decode bounding boxes
|
||||
for (size_t i = 0; i < num_bboxes; ++i) {
|
||||
float confidence = scores_ptr[2 * i + 1];
|
||||
// filter boxes by conf_threshold
|
||||
if (confidence <= conf_threshold) {
|
||||
continue;
|
||||
}
|
||||
float x1 = boxes_ptr[4 * i + 0] * ipt_w;
|
||||
float y1 = boxes_ptr[4 * i + 1] * ipt_h;
|
||||
float x2 = boxes_ptr[4 * i + 2] * ipt_w;
|
||||
float y2 = boxes_ptr[4 * i + 3] * ipt_h;
|
||||
result->boxes.emplace_back(std::array<float, 4>{x1, y1, x2, y2});
|
||||
result->scores.push_back(confidence);
|
||||
}
|
||||
|
||||
if (result->boxes.size() == 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
utils::NMS(result, nms_iou_threshold);
|
||||
|
||||
// scale and clip box
|
||||
for (size_t i = 0; i < result->boxes.size(); ++i) {
|
||||
result->boxes[i][0] = std::max(result->boxes[i][0], 0.0f);
|
||||
result->boxes[i][1] = std::max(result->boxes[i][1], 0.0f);
|
||||
result->boxes[i][2] = std::max(result->boxes[i][2], 0.0f);
|
||||
result->boxes[i][3] = std::max(result->boxes[i][3], 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 UltraFace::Predict(cv::Mat* im, FaceDetectionResult* result,
|
||||
float conf_threshold, float nms_iou_threshold) {
|
||||
#ifdef FASTDEPLOY_DEBUG
|
||||
TIMERECORD_START(0)
|
||||
#endif
|
||||
|
||||
Mat mat(*im);
|
||||
std::vector<FDTensor> input_tensors(1);
|
||||
|
||||
std::map<std::string, std::array<float, 2>> im_info;
|
||||
|
||||
// Record the shape of image and the shape of preprocessed image
|
||||
im_info["input_shape"] = {static_cast<float>(mat.Height()),
|
||||
static_cast<float>(mat.Width())};
|
||||
im_info["output_shape"] = {static_cast<float>(mat.Height()),
|
||||
static_cast<float>(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<FDTensor> 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, 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 linzaer
|
||||
} // namespace vision
|
||||
} // namespace fastdeploy
|
||||
@@ -0,0 +1,84 @@
|
||||
// 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 linzaer {
|
||||
|
||||
class FASTDEPLOY_DECL UltraFace : public FastDeployModel {
|
||||
public:
|
||||
// 当model_format为ONNX时,无需指定params_file
|
||||
// 当model_format为Paddle时,则需同时指定model_file & params_file
|
||||
UltraFace(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 "Linzaer/Ultra-Light-Fast-Generic-Face-Detector-1MB";
|
||||
}
|
||||
|
||||
// 模型预测接口,即用户调用的接口
|
||||
// im 为用户的输入数据,目前对于CV均定义为cv::Mat
|
||||
// result 为模型预测的输出结构体
|
||||
// conf_threshold 为后处理的参数
|
||||
// nms_iou_threshold 为后处理的参数
|
||||
virtual bool Predict(cv::Mat* im, FaceDetectionResult* result,
|
||||
float conf_threshold = 0.7f,
|
||||
float nms_iou_threshold = 0.3f);
|
||||
|
||||
// 以下为模型在预测时的一些参数,基本是前后处理所需
|
||||
// 用户在创建模型后,可根据模型的要求,以及自己的需求
|
||||
// 对参数进行修改
|
||||
// tuple of (width, height), default (320, 240)
|
||||
std::vector<int> size;
|
||||
|
||||
private:
|
||||
// 初始化函数,包括初始化后端,以及其它模型推理需要涉及的操作
|
||||
bool Initialize();
|
||||
|
||||
// 输入图像预处理操作
|
||||
// Mat为FastDeploy定义的数据结构
|
||||
// FDTensor为预处理后的Tensor数据,传给后端进行推理
|
||||
// im_info为预处理过程保存的数据,在后处理中需要用到
|
||||
bool Preprocess(Mat* mat, FDTensor* outputs,
|
||||
std::map<std::string, std::array<float, 2>>* im_info);
|
||||
|
||||
// 后端推理结果后处理,输出给用户
|
||||
// infer_result 为后端推理后的输出Tensor
|
||||
// result 为模型预测的结果
|
||||
// im_info 为预处理记录的信息,后处理用于还原box
|
||||
// conf_threshold 后处理时过滤box的置信度阈值
|
||||
// nms_iou_threshold 后处理时NMS设定的iou阈值
|
||||
bool Postprocess(std::vector<FDTensor>& infer_result,
|
||||
FaceDetectionResult* result,
|
||||
const std::map<std::string, std::array<float, 2>>& im_info,
|
||||
float conf_threshold, float nms_iou_threshold);
|
||||
|
||||
// 查看输入是否为动态维度的 不建议直接使用 不同模型的逻辑可能不一致
|
||||
bool IsDynamicInput() const { return is_dynamic_input_; }
|
||||
|
||||
bool is_dynamic_input_;
|
||||
};
|
||||
|
||||
} // namespace linzaer
|
||||
} // namespace vision
|
||||
} // namespace fastdeploy
|
||||
@@ -25,6 +25,7 @@ void BindMeituan(pybind11::module& m);
|
||||
void BindMegvii(pybind11::module& m);
|
||||
void BindDeepCam(pybind11::module& m);
|
||||
void BindRangiLyu(pybind11::module& m);
|
||||
void BindLinzaer(pybind11::module& m);
|
||||
#ifdef ENABLE_VISION_VISUALIZE
|
||||
void BindVisualize(pybind11::module& m);
|
||||
#endif
|
||||
@@ -69,6 +70,7 @@ void BindVision(pybind11::module& m) {
|
||||
BindMegvii(m);
|
||||
BindDeepCam(m);
|
||||
BindRangiLyu(m);
|
||||
BindLinzaer(m);
|
||||
#ifdef ENABLE_VISION_VISUALIZE
|
||||
BindVisualize(m);
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
// 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/version-RFB-320.onnx";
|
||||
std::string img_path = "../resources/images/test_face_det_0.jpg";
|
||||
std::string vis_path =
|
||||
"../resources/outputs/linzaer_ultraface_vis_result.jpg";
|
||||
|
||||
auto model = vis::linzaer::UltraFace(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::FaceDetectionResult res;
|
||||
if (!model.Predict(&im, &res, 0.7f, 0.3f)) {
|
||||
std::cerr << "Prediction Failed." << std::endl;
|
||||
return -1;
|
||||
} else {
|
||||
std::cout << "Prediction Done!" << std::endl;
|
||||
}
|
||||
|
||||
// 输出预测框结果
|
||||
std::cout << res.Str() << std::endl;
|
||||
|
||||
// 可视化预测结果
|
||||
vis::Visualize::VisFaceDetection(&vis_im, res, 2, 0.3f);
|
||||
cv::imwrite(vis_path, vis_im);
|
||||
std::cout << "Detect Done! Saved: " << vis_path << std::endl;
|
||||
return 0;
|
||||
}
|
||||
@@ -24,3 +24,4 @@ from . import visualize
|
||||
from . import wongkinyiu
|
||||
from . import deepcam
|
||||
from . import rangilyu
|
||||
from . import linzaer
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
# 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 UltraFace(FastDeployModel):
|
||||
def __init__(self,
|
||||
model_file,
|
||||
params_file="",
|
||||
runtime_option=None,
|
||||
model_format=Frontend.ONNX):
|
||||
# 调用基函数进行backend_option的初始化
|
||||
# 初始化后的option保存在self._runtime_option
|
||||
super(UltraFace, self).__init__(runtime_option)
|
||||
|
||||
self._model = C.vision.linzaer.UltraFace(
|
||||
model_file, params_file, self._runtime_option, model_format)
|
||||
# 通过self.initialized判断整个模型的初始化是否成功
|
||||
assert self.initialized, "UltraFace initialize failed."
|
||||
|
||||
def predict(self, input_image, conf_threshold=0.7, nms_iou_threshold=0.3):
|
||||
return self._model.predict(input_image, conf_threshold,
|
||||
nms_iou_threshold)
|
||||
|
||||
# 一些跟UltraFace模型有关的属性封装
|
||||
# 多数是预处理相关,可通过修改如model.size = [640, 480]改变预处理时resize的大小(前提是模型支持)
|
||||
@property
|
||||
def size(self):
|
||||
return self._model.size
|
||||
|
||||
@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
|
||||
@@ -0,0 +1,49 @@
|
||||
# UltraFace部署示例
|
||||
|
||||
当前支持模型版本为:[UltraFace CommitID:dffdddd](https://github.com/Linzaer/Ultra-Light-Fast-Generic-Face-Detector-1MB/commit/dffdddd)
|
||||
|
||||
本文档说明如何进行[UltraFace](https://github.com/Linzaer/Ultra-Light-Fast-Generic-Face-Detector-1MB/)的快速部署推理。本目录结构如下
|
||||
|
||||
```
|
||||
.
|
||||
├── cpp # C++ 代码目录
|
||||
│ ├── CMakeLists.txt # C++ 代码编译CMakeLists文件
|
||||
│ ├── README.md # C++ 代码编译部署文档
|
||||
│ └── ultraface.cc # C++ 示例代码
|
||||
├── api.md # API 说明文档
|
||||
├── README.md # UltraFace 部署文档
|
||||
└── ultraface.py # Python示例代码
|
||||
```
|
||||
|
||||
## 安装FastDeploy
|
||||
|
||||
使用如下命令安装FastDeploy,注意到此处安装的是`vision-cpu`,也可根据需求安装`vision-gpu`
|
||||
```bash
|
||||
# 安装fastdeploy-python工具
|
||||
pip install fastdeploy-python
|
||||
|
||||
# 安装vision-cpu模块
|
||||
fastdeploy install vision-cpu
|
||||
```
|
||||
|
||||
## Python部署
|
||||
|
||||
执行如下代码即会自动下载YOLOv5Face模型和测试图片
|
||||
```bash
|
||||
python ultraface.py
|
||||
```
|
||||
|
||||
执行完成后会将可视化结果保存在本地`vis_result.jpg`,同时输出检测结果如下
|
||||
```
|
||||
FaceDetectionResult: [xmin, ymin, xmax, ymax, score]
|
||||
742.528931,261.309937, 837.749146, 365.145599, 0.999833
|
||||
408.159332,253.410889, 484.747284, 353.378052, 0.999832
|
||||
549.409424,225.051819, 636.311890, 337.824707, 0.999782
|
||||
185.562805,233.364044, 252.001801, 323.948669, 0.999709
|
||||
304.065918,180.468140, 377.097961, 278.932861, 0.999645
|
||||
```
|
||||
|
||||
## 其它文档
|
||||
|
||||
- [C++部署](./cpp/README.md)
|
||||
- [UltraFace API文档](./api.md)
|
||||
@@ -0,0 +1,71 @@
|
||||
# UltraFace API说明
|
||||
|
||||
## Python API
|
||||
|
||||
### UltraFace类
|
||||
```
|
||||
fastdeploy.vision.linzaer.UltraFace(model_file, params_file=None, runtime_option=None, model_format=fd.Frontend.ONNX)
|
||||
```
|
||||
UltraFace模型加载和初始化,当model_format为`fd.Frontend.ONNX`时,只需提供model_file,如`version-RFB-320.onnx`;当model_format为`fd.Frontend.PADDLE`时,则需同时提供model_file和params_file。
|
||||
|
||||
**参数**
|
||||
|
||||
> * **model_file**(str): 模型文件路径
|
||||
> * **params_file**(str): 参数文件路径
|
||||
> * **runtime_option**(RuntimeOption): 后端推理配置,默认为None,即采用默认配置
|
||||
> * **model_format**(Frontend): 模型格式
|
||||
|
||||
#### predict函数
|
||||
> ```
|
||||
> UltraFace.predict(image_data, conf_threshold=0.7, nms_iou_threshold=0.3)
|
||||
> ```
|
||||
> 模型预测结口,输入图像直接输出检测结果。
|
||||
>
|
||||
> **参数**
|
||||
>
|
||||
> > * **image_data**(np.ndarray): 输入数据,注意需为HWC,BGR格式
|
||||
> > * **conf_threshold**(float): 检测框置信度过滤阈值
|
||||
> > * **nms_iou_threshold**(float): NMS处理过程中iou阈值
|
||||
|
||||
示例代码参考[ultraface.py](./ultraface.py)
|
||||
|
||||
|
||||
## C++ API
|
||||
|
||||
### UltraFace类
|
||||
```
|
||||
fastdeploy::vision::linzaer::UltraFace(
|
||||
const string& model_file,
|
||||
const string& params_file = "",
|
||||
const RuntimeOption& runtime_option = RuntimeOption(),
|
||||
const Frontend& model_format = Frontend::ONNX)
|
||||
```
|
||||
UltraFace模型加载和初始化,当model_format为`Frontend::ONNX`时,只需提供model_file,如`version-RFB-320.onnx`;当model_format为`Frontend::PADDLE`时,则需同时提供model_file和params_file。
|
||||
|
||||
**参数**
|
||||
|
||||
> * **model_file**(str): 模型文件路径
|
||||
> * **params_file**(str): 参数文件路径
|
||||
> * **runtime_option**(RuntimeOption): 后端推理配置,默认为None,即采用默认配置
|
||||
> * **model_format**(Frontend): 模型格式
|
||||
|
||||
#### Predict函数
|
||||
> ```
|
||||
> UltraFace::Predict(cv::Mat* im, FaceDetectionResult* result,
|
||||
> float conf_threshold = 0.7,
|
||||
> float nms_iou_threshold = 0.3)
|
||||
> ```
|
||||
> 模型预测接口,输入图像直接输出检测结果。
|
||||
>
|
||||
> **参数**
|
||||
>
|
||||
> > * **im**: 输入图像,注意需为HWC,BGR格式
|
||||
> > * **result**: 检测结果,包括检测框,各个框的置信度
|
||||
> > * **conf_threshold**: 检测框置信度过滤阈值
|
||||
> > * **nms_iou_threshold**: NMS处理过程中iou阈值
|
||||
|
||||
示例代码参考[cpp/ultraface.cc](cpp/ultraface.cc)
|
||||
|
||||
## 其它API使用
|
||||
|
||||
- [模型部署RuntimeOption配置](../../../docs/api/runtime_option.md)
|
||||
@@ -0,0 +1,17 @@
|
||||
PROJECT(ultraface_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.3.0/)
|
||||
|
||||
include(${FASTDEPLOY_INSTALL_DIR}/FastDeploy.cmake)
|
||||
|
||||
# 添加FastDeploy依赖头文件
|
||||
include_directories(${FASTDEPLOY_INCS})
|
||||
|
||||
add_executable(ultraface_demo ${PROJECT_SOURCE_DIR}/ultraface.cc)
|
||||
# 添加FastDeploy库依赖
|
||||
target_link_libraries(ultraface_demo ${FASTDEPLOY_LIBS})
|
||||
@@ -0,0 +1,36 @@
|
||||
# 编译UltraFace示例
|
||||
|
||||
当前支持模型版本为:[UltraFace CommitID:dffdddd](https://github.com/Linzaer/Ultra-Light-Fast-Generic-Face-Detector-1MB/commit/dffdddd)
|
||||
|
||||
## 下载和解压预测库
|
||||
```bash
|
||||
wget https://bj.bcebos.com/paddle2onnx/fastdeploy/fastdeploy-linux-x64-0.0.3.tgz
|
||||
tar xvf fastdeploy-linux-x64-0.0.3.tgz
|
||||
```
|
||||
|
||||
## 编译示例代码
|
||||
```bash
|
||||
mkdir build & cd build
|
||||
cmake ..
|
||||
make -j
|
||||
```
|
||||
|
||||
## 下载模型和图片
|
||||
wget https://github.com/Linzaer/Ultra-Light-Fast-Generic-Face-Detector-1MB/raw/master/models/onnx/version-RFB-320.onnx
|
||||
wget https://github.com/Linzaer/Ultra-Light-Fast-Generic-Face-Detector-1MB/raw/master/imgs/3.jpg
|
||||
|
||||
|
||||
## 执行
|
||||
```bash
|
||||
./ultraface_demo
|
||||
```
|
||||
|
||||
执行完后可视化的结果保存在本地`vis_result.jpg`,同时会将检测框输出在终端,如下所示
|
||||
```
|
||||
FaceDetectionResult: [xmin, ymin, xmax, ymax, score]
|
||||
742.528931,261.309937, 837.749146, 365.145599, 0.999833
|
||||
408.159332,253.410889, 484.747284, 353.378052, 0.999832
|
||||
549.409424,225.051819, 636.311890, 337.824707, 0.999782
|
||||
185.562805,233.364044, 252.001801, 323.948669, 0.999709
|
||||
304.065918,180.468140, 377.097961, 278.932861, 0.999645
|
||||
```
|
||||
@@ -0,0 +1,48 @@
|
||||
// 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::linzaer::UltraFace("version-RFB-320.onnx");
|
||||
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("3.jpg");
|
||||
cv::Mat vis_im = im.clone();
|
||||
|
||||
vis::FaceDetectionResult res;
|
||||
if (!model.Predict(&im, &res, 0.7f, 0.3f)) {
|
||||
std::cerr << "Prediction Failed." << std::endl;
|
||||
return -1;
|
||||
} else {
|
||||
std::cout << "Prediction Done!" << std::endl;
|
||||
}
|
||||
|
||||
// 输出预测框结果
|
||||
std::cout << res.Str() << std::endl;
|
||||
|
||||
// 可视化预测结果
|
||||
vis::Visualize::VisFaceDetection(&vis_im, res, 2, 0.3f);
|
||||
cv::imwrite("vis_result.jpg", vis_im);
|
||||
std::cout << "Detect Done! Saved: " << vis_path << std::endl;
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import fastdeploy as fd
|
||||
import cv2
|
||||
|
||||
# 下载模型
|
||||
model_url = "https://github.com/Linzaer/Ultra-Light-Fast-Generic-Face-Detector-1MB/raw/master/models/onnx/version-RFB-320.onnx"
|
||||
test_img_url = "https://github.com/Linzaer/Ultra-Light-Fast-Generic-Face-Detector-1MB/raw/master/imgs/3.jpg"
|
||||
fd.download(model_url, ".", show_progress=True)
|
||||
fd.download(test_img_url, ".", show_progress=True)
|
||||
|
||||
# 加载模型
|
||||
model = fd.vision.linzaer.UltraFace("version-RFB-320.onnx")
|
||||
|
||||
# 预测图片
|
||||
im = cv2.imread("3.jpg")
|
||||
result = model.predict(im, conf_threshold=0.7, nms_iou_threshold=0.3)
|
||||
|
||||
# 可视化结果
|
||||
fd.vision.visualize.vis_face_detection(im, result)
|
||||
cv2.imwrite("vis_result.jpg", im)
|
||||
|
||||
# 输出预测结果
|
||||
print(result)
|
||||
print(model.runtime_option)
|
||||
@@ -50,7 +50,7 @@ make -j
|
||||
|
||||
执行完后可视化的结果保存在本地`vis_result.jpg`,同时会将检测框输出在终端,如下所示
|
||||
```
|
||||
aceDetectionResult: [xmin, ymin, xmax, ymax, score, (x, y) x 5]
|
||||
FaceDetectionResult: [xmin, ymin, xmax, ymax, score, (x, y) x 5]
|
||||
749.575256,375.122162, 775.008850, 407.858215, 0.851824, (756.933838,388.423157), (767.810974,387.932922), (762.617065,394.212341), (758.053101,399.073639), (767.370300,398.769470)
|
||||
897.833862,380.372864, 924.725281, 409.566803, 0.847505, (903.757202,390.221741), (914.575867,389.495911), (908.998901,395.983307), (905.803223,400.871429), (914.674438,400.268066)
|
||||
281.558197,367.739349, 305.474701, 397.860535, 0.840915, (287.018768,379.771088), (297.285004,378.755280), (292.057831,385.207367), (289.110962,390.010437), (297.535339,389.412048)
|
||||
|
||||
Reference in New Issue
Block a user