提交 29f8fb83 编写于 作者: D dongshuilong

cpp shitu code format

上级 a96305c2
...@@ -35,8 +35,8 @@ using namespace paddle_infer; ...@@ -35,8 +35,8 @@ using namespace paddle_infer;
namespace Feature { namespace Feature {
class FeatureExtracter { class FeatureExtracter {
public: public:
explicit FeatureExtracter(const YAML::Node &config_file) { explicit FeatureExtracter(const YAML::Node &config_file) {
this->use_gpu_ = config_file["Global"]["use_gpu"].as<bool>(); this->use_gpu_ = config_file["Global"]["use_gpu"].as<bool>();
if (config_file["Global"]["gpu_id"].IsDefined()) if (config_file["Global"]["gpu_id"].IsDefined())
...@@ -59,15 +59,13 @@ public: ...@@ -59,15 +59,13 @@ public:
this->resize_size_ = this->resize_size_ =
config_file["RecPreProcess"]["transform_ops"][0]["ResizeImage"]["size"] config_file["RecPreProcess"]["transform_ops"][0]["ResizeImage"]["size"]
.as<int>(); .as<int>();
this->scale_ = config_file["RecPreProcess"]["transform_ops"][1] this->scale_ = config_file["RecPreProcess"]["transform_ops"][1]["NormalizeImage"]["scale"].as<float>();
["NormalizeImage"]["scale"]
.as<float>();
this->mean_ = config_file["RecPreProcess"]["transform_ops"][1] this->mean_ = config_file["RecPreProcess"]["transform_ops"][1]
["NormalizeImage"]["mean"] ["NormalizeImage"]["mean"]
.as<std::vector<float>>(); .as < std::vector < float >> ();
this->std_ = config_file["RecPreProcess"]["transform_ops"][1] this->std_ = config_file["RecPreProcess"]["transform_ops"][1]
["NormalizeImage"]["std"] ["NormalizeImage"]["std"]
.as<std::vector<float>>(); .as < std::vector < float >> ();
if (config_file["Global"]["rec_feature_normlize"].IsDefined()) if (config_file["Global"]["rec_feature_normlize"].IsDefined())
this->feature_norm = this->feature_norm =
config_file["Global"]["rec_feature_normlize"].as<bool>(); config_file["Global"]["rec_feature_normlize"].as<bool>();
...@@ -81,11 +79,12 @@ public: ...@@ -81,11 +79,12 @@ public:
// Run predictor // Run predictor
void Run(cv::Mat &img, std::vector<float> &out_data, void Run(cv::Mat &img, std::vector<float> &out_data,
std::vector<double> &times); std::vector<double> &times);
void FeatureNorm(std::vector<float> &feature); void FeatureNorm(std::vector<float> &feature);
std::shared_ptr<Predictor> predictor_; std::shared_ptr <Predictor> predictor_;
private: private:
bool use_gpu_ = false; bool use_gpu_ = false;
int gpu_id_ = 0; int gpu_id_ = 0;
int gpu_mem_ = 4000; int gpu_mem_ = 4000;
...@@ -106,6 +105,6 @@ private: ...@@ -106,6 +105,6 @@ private:
ResizeImg resize_op_; ResizeImg resize_op_;
Normalize normalize_op_; Normalize normalize_op_;
Permute permute_op_; Permute permute_op_;
}; };
} // namespace Feature } // namespace Feature
...@@ -17,7 +17,7 @@ ...@@ -17,7 +17,7 @@
#include <algorithm> #include <algorithm>
#include <include/object_detector.h> #include <include/object_detector.h>
template <typename T> template<typename T>
static inline bool SortScorePairDescend(const std::pair<float, T> &pair1, static inline bool SortScorePairDescend(const std::pair<float, T> &pair1,
const std::pair<float, T> &pair2) { const std::pair<float, T> &pair2) {
return pair1.first > pair2.first; return pair1.first > pair2.first;
...@@ -40,9 +40,9 @@ float RectOverlap(const Detection::ObjectResult &a, ...@@ -40,9 +40,9 @@ float RectOverlap(const Detection::ObjectResult &a,
// top_k: if -1, keep all; otherwise, keep at most top_k. // top_k: if -1, keep all; otherwise, keep at most top_k.
// score_index_vec: store the sorted (score, index) pair. // score_index_vec: store the sorted (score, index) pair.
inline void inline void
GetMaxScoreIndex(const std::vector<Detection::ObjectResult> &det_result, GetMaxScoreIndex(const std::vector <Detection::ObjectResult> &det_result,
const float threshold, const float threshold,
std::vector<std::pair<float, int>> &score_index_vec) { std::vector <std::pair<float, int>> &score_index_vec) {
// Generate index score pairs. // Generate index score pairs.
for (size_t i = 0; i < det_result.size(); ++i) { for (size_t i = 0; i < det_result.size(); ++i) {
if (det_result[i].confidence > threshold) { if (det_result[i].confidence > threshold) {
...@@ -61,12 +61,12 @@ GetMaxScoreIndex(const std::vector<Detection::ObjectResult> &det_result, ...@@ -61,12 +61,12 @@ GetMaxScoreIndex(const std::vector<Detection::ObjectResult> &det_result,
// } // }
} }
void NMSBoxes(const std::vector<Detection::ObjectResult> det_result, void NMSBoxes(const std::vector <Detection::ObjectResult> det_result,
const float score_threshold, const float nms_threshold, const float score_threshold, const float nms_threshold,
std::vector<int> &indices) { std::vector<int> &indices) {
int a = 1; int a = 1;
// Get top_k scores (with corresponding indices). // Get top_k scores (with corresponding indices).
std::vector<std::pair<float, int>> score_index_vec; std::vector <std::pair<float, int>> score_index_vec;
GetMaxScoreIndex(det_result, score_threshold, score_index_vec); GetMaxScoreIndex(det_result, score_threshold, score_index_vec);
// Do nms // Do nms
...@@ -74,7 +74,7 @@ void NMSBoxes(const std::vector<Detection::ObjectResult> det_result, ...@@ -74,7 +74,7 @@ void NMSBoxes(const std::vector<Detection::ObjectResult> det_result,
for (size_t i = 0; i < score_index_vec.size(); ++i) { for (size_t i = 0; i < score_index_vec.size(); ++i) {
const int idx = score_index_vec[i].second; const int idx = score_index_vec[i].second;
bool keep = true; bool keep = true;
for (int k = 0; k < (int)indices.size() && keep; ++k) { for (int k = 0; k < (int) indices.size() && keep; ++k) {
const int kept_idx = indices[k]; const int kept_idx = indices[k];
float overlap = RectOverlap(det_result[idx], det_result[kept_idx]); float overlap = RectOverlap(det_result[idx], det_result[kept_idx]);
keep = overlap <= nms_threshold; keep = overlap <= nms_threshold;
......
...@@ -33,26 +33,26 @@ using namespace paddle_infer; ...@@ -33,26 +33,26 @@ using namespace paddle_infer;
namespace Detection { namespace Detection {
// Object Detection Result // Object Detection Result
struct ObjectResult { struct ObjectResult {
// Rectangle coordinates of detected object: left, right, top, down // Rectangle coordinates of detected object: left, right, top, down
std::vector<int> rect; std::vector<int> rect;
// Class id of detected object // Class id of detected object
int class_id; int class_id;
// Confidence of detected object // Confidence of detected object
float confidence; float confidence;
}; };
// Generate visualization colormap for each class // Generate visualization colormap for each class
std::vector<int> GenerateColorMap(int num_class); std::vector<int> GenerateColorMap(int num_class);
// Visualiztion Detection Result // Visualiztion Detection Result
cv::Mat VisualizeResult(const cv::Mat &img, cv::Mat VisualizeResult(const cv::Mat &img,
const std::vector<ObjectResult> &results, const std::vector <ObjectResult> &results,
const std::vector<std::string> &lables, const std::vector <std::string> &lables,
const std::vector<int> &colormap, const bool is_rbox); const std::vector<int> &colormap, const bool is_rbox);
class ObjectDetector { class ObjectDetector {
public: public:
explicit ObjectDetector(const YAML::Node &config_file) { explicit ObjectDetector(const YAML::Node &config_file) {
this->use_gpu_ = config_file["Global"]["use_gpu"].as<bool>(); this->use_gpu_ = config_file["Global"]["use_gpu"].as<bool>();
if (config_file["Global"]["gpu_id"].IsDefined()) if (config_file["Global"]["gpu_id"].IsDefined())
...@@ -68,9 +68,9 @@ public: ...@@ -68,9 +68,9 @@ public:
this->threshold_ = config_file["Global"]["threshold"].as<float>(); this->threshold_ = config_file["Global"]["threshold"].as<float>();
this->max_det_results_ = config_file["Global"]["max_det_results"].as<int>(); this->max_det_results_ = config_file["Global"]["max_det_results"].as<int>();
this->image_shape_ = this->image_shape_ =
config_file["Global"]["image_shape"].as<std::vector<int>>(); config_file["Global"]["image_shape"].as < std::vector < int >> ();
this->label_list_ = this->label_list_ =
config_file["Global"]["labe_list"].as<std::vector<std::string>>(); config_file["Global"]["labe_list"].as < std::vector < std::string >> ();
this->ir_optim_ = config_file["Global"]["ir_optim"].as<bool>(); this->ir_optim_ = config_file["Global"]["ir_optim"].as<bool>();
this->batch_size_ = config_file["Global"]["batch_size"].as<int>(); this->batch_size_ = config_file["Global"]["batch_size"].as<int>();
...@@ -83,17 +83,19 @@ public: ...@@ -83,17 +83,19 @@ public:
const std::string &run_mode = "fluid"); const std::string &run_mode = "fluid");
// Run predictor // Run predictor
void Predict(const std::vector<cv::Mat> imgs, const int warmup = 0, void Predict(const std::vector <cv::Mat> imgs, const int warmup = 0,
const int repeats = 1, const int repeats = 1,
std::vector<ObjectResult> *result = nullptr, std::vector <ObjectResult> *result = nullptr,
std::vector<int> *bbox_num = nullptr, std::vector<int> *bbox_num = nullptr,
std::vector<double> *times = nullptr); std::vector<double> *times = nullptr);
const std::vector<std::string> &GetLabelList() const {
const std::vector <std::string> &GetLabelList() const {
return this->label_list_; return this->label_list_;
} }
const float &GetThreshold() const { return this->threshold_; } const float &GetThreshold() const { return this->threshold_; }
private: private:
bool use_gpu_ = true; bool use_gpu_ = true;
int gpu_id_ = 0; int gpu_id_ = 0;
int gpu_mem_ = 800; int gpu_mem_ = 800;
...@@ -107,7 +109,7 @@ private: ...@@ -107,7 +109,7 @@ private:
float threshold_ = 0.5; float threshold_ = 0.5;
float max_det_results_ = 5; float max_det_results_ = 5;
std::vector<int> image_shape_ = {3, 640, 640}; std::vector<int> image_shape_ = {3, 640, 640};
std::vector<std::string> label_list_; std::vector <std::string> label_list_;
bool ir_optim_ = true; bool ir_optim_ = true;
bool det_permute_ = true; bool det_permute_ = true;
bool det_postprocess_ = true; bool det_postprocess_ = true;
...@@ -120,16 +122,17 @@ private: ...@@ -120,16 +122,17 @@ private:
// Preprocess image and copy data to input buffer // Preprocess image and copy data to input buffer
void Preprocess(const cv::Mat &image_mat); void Preprocess(const cv::Mat &image_mat);
// Postprocess result // Postprocess result
void Postprocess(const std::vector<cv::Mat> mats, void Postprocess(const std::vector <cv::Mat> mats,
std::vector<ObjectResult> *result, std::vector<int> bbox_num, std::vector <ObjectResult> *result, std::vector<int> bbox_num,
bool is_rbox); bool is_rbox);
std::shared_ptr<Predictor> predictor_; std::shared_ptr <Predictor> predictor_;
Preprocessor preprocessor_; Preprocessor preprocessor_;
ImageBlob inputs_; ImageBlob inputs_;
std::vector<float> output_data_; std::vector<float> output_data_;
std::vector<int> out_bbox_num_data_; std::vector<int> out_bbox_num_data_;
}; };
} // namespace Detection } // namespace Detection
...@@ -31,27 +31,27 @@ using namespace std; ...@@ -31,27 +31,27 @@ using namespace std;
namespace Feature { namespace Feature {
class Normalize { class Normalize {
public: public:
virtual void Run(cv::Mat *im, const std::vector<float> &mean, virtual void Run(cv::Mat *im, const std::vector<float> &mean,
const std::vector<float> &std, float scale); const std::vector<float> &std, float scale);
}; };
// RGB -> CHW // RGB -> CHW
class Permute { class Permute {
public: public:
virtual void Run(const cv::Mat *im, float *data); virtual void Run(const cv::Mat *im, float *data);
}; };
class CenterCropImg { class CenterCropImg {
public: public:
virtual void Run(cv::Mat &im, const int crop_size = 224); virtual void Run(cv::Mat &im, const int crop_size = 224);
}; };
class ResizeImg { class ResizeImg {
public: public:
virtual void Run(const cv::Mat &img, cv::Mat &resize_img, int max_size_len, virtual void Run(const cv::Mat &img, cv::Mat &resize_img, int max_size_len,
int size = 0); int size = 0);
}; };
} // namespace Feature } // namespace Feature
...@@ -31,8 +31,8 @@ ...@@ -31,8 +31,8 @@
namespace Detection { namespace Detection {
// Object for storing all preprocessed data // Object for storing all preprocessed data
class ImageBlob { class ImageBlob {
public: public:
// image width and height // image width and height
std::vector<float> im_shape_; std::vector<float> im_shape_;
// Buffer for image data after preprocessing // Buffer for image data after preprocessing
...@@ -43,51 +43,54 @@ public: ...@@ -43,51 +43,54 @@ public:
// std::vector<float> eval_im_size_f_; // std::vector<float> eval_im_size_f_;
// Scale factor for image size to origin image size // Scale factor for image size to origin image size
std::vector<float> scale_factor_; std::vector<float> scale_factor_;
}; };
// Abstraction of preprocessing opration class // Abstraction of preprocessing opration class
class PreprocessOp { class PreprocessOp {
public: public:
virtual void Init(const YAML::Node &item) = 0; virtual void Init(const YAML::Node &item) = 0;
virtual void Run(cv::Mat *im, ImageBlob *data) = 0; virtual void Run(cv::Mat *im, ImageBlob *data) = 0;
}; };
class InitInfo : public PreprocessOp { class InitInfo : public PreprocessOp {
public: public:
virtual void Init(const YAML::Node &item) {} virtual void Init(const YAML::Node &item) {}
virtual void Run(cv::Mat *im, ImageBlob *data); virtual void Run(cv::Mat *im, ImageBlob *data);
}; };
class NormalizeImage : public PreprocessOp { class NormalizeImage : public PreprocessOp {
public: public:
virtual void Init(const YAML::Node &item) { virtual void Init(const YAML::Node &item) {
mean_ = item["mean"].as<std::vector<float>>(); mean_ = item["mean"].as < std::vector < float >> ();
scale_ = item["std"].as<std::vector<float>>(); scale_ = item["std"].as < std::vector < float >> ();
is_scale_ = item["is_scale"].as<bool>(); is_scale_ = item["is_scale"].as<bool>();
} }
virtual void Run(cv::Mat *im, ImageBlob *data); virtual void Run(cv::Mat *im, ImageBlob *data);
private: private:
// CHW or HWC // CHW or HWC
std::vector<float> mean_; std::vector<float> mean_;
std::vector<float> scale_; std::vector<float> scale_;
bool is_scale_; bool is_scale_;
}; };
class Permute : public PreprocessOp { class Permute : public PreprocessOp {
public: public:
virtual void Init(const YAML::Node &item) {} virtual void Init(const YAML::Node &item) {}
virtual void Run(cv::Mat *im, ImageBlob *data); virtual void Run(cv::Mat *im, ImageBlob *data);
}; };
class Resize : public PreprocessOp { class Resize : public PreprocessOp {
public: public:
virtual void Init(const YAML::Node &item) { virtual void Init(const YAML::Node &item) {
interp_ = item["interp"].as<int>(); interp_ = item["interp"].as<int>();
// max_size_ = item["target_size"].as<int>(); // max_size_ = item["target_size"].as<int>();
keep_ratio_ = item["keep_ratio"].as<bool>(); keep_ratio_ = item["keep_ratio"].as<bool>();
target_size_ = item["target_size"].as<std::vector<int>>(); target_size_ = item["target_size"].as < std::vector < int >> ();
} }
// Compute best resize scale for x-dimension, y-dimension // Compute best resize scale for x-dimension, y-dimension
...@@ -95,28 +98,28 @@ public: ...@@ -95,28 +98,28 @@ public:
virtual void Run(cv::Mat *im, ImageBlob *data); virtual void Run(cv::Mat *im, ImageBlob *data);
private: private:
int interp_ = 2; int interp_ = 2;
bool keep_ratio_; bool keep_ratio_;
std::vector<int> target_size_; std::vector<int> target_size_;
std::vector<int> in_net_shape_; std::vector<int> in_net_shape_;
}; };
// Models with FPN need input shape % stride == 0 // Models with FPN need input shape % stride == 0
class PadStride : public PreprocessOp { class PadStride : public PreprocessOp {
public: public:
virtual void Init(const YAML::Node &item) { virtual void Init(const YAML::Node &item) {
stride_ = item["stride"].as<int>(); stride_ = item["stride"].as<int>();
} }
virtual void Run(cv::Mat *im, ImageBlob *data); virtual void Run(cv::Mat *im, ImageBlob *data);
private: private:
int stride_; int stride_;
}; };
class Preprocessor { class Preprocessor {
public: public:
void Init(const YAML::Node &config_node) { void Init(const YAML::Node &config_node) {
// initialize image info at first // initialize image info at first
ops_["InitInfo"] = std::make_shared<InitInfo>(); ops_["InitInfo"] = std::make_shared<InitInfo>();
...@@ -145,11 +148,11 @@ public: ...@@ -145,11 +148,11 @@ public:
void Run(cv::Mat *im, ImageBlob *data); void Run(cv::Mat *im, ImageBlob *data);
public: public:
static const std::vector<std::string> RUN_ORDER; static const std::vector <std::string> RUN_ORDER;
private: private:
std::unordered_map<std::string, std::shared_ptr<PreprocessOp>> ops_; std::unordered_map <std::string, std::shared_ptr<PreprocessOp>> ops_;
}; };
} // namespace Detection } // namespace Detection
...@@ -26,7 +26,7 @@ ...@@ -26,7 +26,7 @@
#include <map> #include <map>
struct SearchResult { struct SearchResult {
std::vector<faiss::Index::idx_t> I; std::vector <faiss::Index::idx_t> I;
std::vector<float> D; std::vector<float> D;
int return_k; int return_k;
}; };
...@@ -46,10 +46,15 @@ public: ...@@ -46,10 +46,15 @@ public:
this->I.resize(this->return_k * this->max_query_number); this->I.resize(this->return_k * this->max_query_number);
this->D.resize(this->return_k * this->max_query_number); this->D.resize(this->return_k * this->max_query_number);
}; };
void LoadIdMap(); void LoadIdMap();
void LoadIndexFile(); void LoadIndexFile();
const SearchResult &Search(float *feature, int query_number); const SearchResult &Search(float *feature, int query_number);
const std::string &GetLabel(faiss::Index::idx_t ind); const std::string &GetLabel(faiss::Index::idx_t ind);
const float &GetThreshold() { return this->score_thres; } const float &GetThreshold() { return this->score_thres; }
private: private:
...@@ -60,6 +65,6 @@ private: ...@@ -60,6 +65,6 @@ private:
faiss::Index *index; faiss::Index *index;
int max_query_number = 6; int max_query_number = 6;
std::vector<float> D; std::vector<float> D;
std::vector<faiss::Index::idx_t> I; std::vector <faiss::Index::idx_t> I;
SearchResult sr; SearchResult sr;
}; };
...@@ -45,9 +45,14 @@ public: ...@@ -45,9 +45,14 @@ public:
explicit YamlConfig(const std::string &path) { explicit YamlConfig(const std::string &path) {
config_file = ReadYamlConfig(path); config_file = ReadYamlConfig(path);
} }
static std::vector<std::string> ReadDict(const std::string &path);
static std::vector <std::string> ReadDict(const std::string &path);
static std::map<int, std::string> ReadIndexId(const std::string &path); static std::map<int, std::string> ReadIndexId(const std::string &path);
static YAML::Node ReadYamlConfig(const std::string &path); static YAML::Node ReadYamlConfig(const std::string &path);
void PrintConfigInfo(); void PrintConfigInfo();
YAML::Node config_file; YAML::Node config_file;
}; };
...@@ -6,10 +6,7 @@ ...@@ -6,10 +6,7 @@
## 1. 准备环境 ## 1. 准备环境
### 运行准备 ### 运行准备
- Linux环境,推荐使用docker。 - Linux环境,推荐使用ubuntu docker。
- Windows环境,目前支持基于`Visual Studio 2019 Community`进行编译;此外,如果您希望通过生成`sln解决方案`的方式进行编译,可以参考该文档:[https://zhuanlan.zhihu.com/p/145446681](https://zhuanlan.zhihu.com/p/145446681)
* 该文档主要介绍基于Linux环境下的PaddleClas C++预测流程,如果需要在Windows环境下使用预测库进行C++预测,具体编译方法请参考[Windows下编译教程](./docs/windows_vs2019_build.md)
### 1.1 编译opencv库 ### 1.1 编译opencv库
...@@ -103,7 +100,7 @@ make -j ...@@ -103,7 +100,7 @@ make -j
make inference_lib_dist make inference_lib_dist
``` ```
更多编译参数选项可以参考Paddle C++预测库官网:[https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/05_inference_deployment/inference/build_and_install_lib_cn.html#id16](https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/05_inference_deployment/inference/build_and_install_lib_cn.html#id16) 更多编译参数选项可以参考[Paddle C++预测库官网](https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/05_inference_deployment/inference/build_and_install_lib_cn.html#id16)
* 编译完成之后,可以在`build/paddle_inference_install_dir/`文件下看到生成了以下文件及文件夹。 * 编译完成之后,可以在`build/paddle_inference_install_dir/`文件下看到生成了以下文件及文件夹。
...@@ -137,6 +134,7 @@ tar -xvf paddle_inference.tgz ...@@ -137,6 +134,7 @@ tar -xvf paddle_inference.tgz
### 1.3 安装faiss库 ### 1.3 安装faiss库
```shell ```shell
# 下载 faiss
git clone https://github.com/facebookresearch/faiss.git git clone https://github.com/facebookresearch/faiss.git
cd faiss cd faiss
cmake -B build . -DFAISS_ENABLE_PYTHON=OFF -DCMAKE_INSTALL_PREFIX=${faiss_install_path} cmake -B build . -DFAISS_ENABLE_PYTHON=OFF -DCMAKE_INSTALL_PREFIX=${faiss_install_path}
...@@ -144,22 +142,19 @@ tar -xvf paddle_inference.tgz ...@@ -144,22 +142,19 @@ tar -xvf paddle_inference.tgz
make -C build install make -C build install
``` ```
## 2 开始运行 在安装`faiss`前,请安装`openblas``ubuntu`系统中安装命令如下:
### 2.1 将模型导出为inference model ```shell
apt-get install libopenblas-dev
```
* 可以参考[模型导出](../../tools/export_model.py),导出`inference model`,用于模型预测。得到预测模型后,假设模型文件放在`inference`目录下,则目录结构如下 注意本教程以安装faiss cpu版本为例,安装时请参考[faiss](https://github.com/facebookresearch/faiss)官网文档,根据需求自行安装
``` ## 2 代码编译
inference/
|--cls_infer.pdmodel
|--cls_infer.pdiparams
```
**注意**:上述文件中,`cls_infer.pdmodel`文件存储了模型结构信息,`cls_infer.pdiparams`文件存储了模型参数信息。注意两个文件的路径需要与配置文件`tools/config.txt`中的`cls_model_path``cls_params_path`参数对应一致。
### 2.2 编译PaddleClas C++预测demo ### 2.2 编译PaddleClas C++预测demo
* 编译命令如下,其中Paddle C++预测库、opencv等其他依赖库的地址需要换成自己机器上的实际地址 编译命令如下,其中Paddle C++预测库、opencv等其他依赖库的地址需要换成自己机器上的实际地址。同时,编译过程中需要下载编译`yaml-cpp`等C++库,请保持联网环境
```shell ```shell
...@@ -169,11 +164,12 @@ sh tools/build.sh ...@@ -169,11 +164,12 @@ sh tools/build.sh
具体地,`tools/build.sh`中内容如下。 具体地,`tools/build.sh`中内容如下。
```shell ```shell
OPENCV_DIR=your_opencv_dir OPENCV_DIR=${opencv_install_dir}
LIB_DIR=your_paddle_inference_dir LIB_DIR=${paddle_inference_dir}
CUDA_LIB_DIR=your_cuda_lib_dir CUDA_LIB_DIR=/usr/local/cuda/lib64
CUDNN_LIB_DIR=your_cudnn_lib_dir CUDNN_LIB_DIR=/usr/lib/x86_64-linux-gnu/
TENSORRT_DIR=your_tensorrt_lib_dir FAISS_DIR=${faiss_install_dir}
FAISS_WITH_MKL=OFF
BUILD_DIR=build BUILD_DIR=build
rm -rf ${BUILD_DIR} rm -rf ${BUILD_DIR}
...@@ -182,14 +178,14 @@ cd ${BUILD_DIR} ...@@ -182,14 +178,14 @@ cd ${BUILD_DIR}
cmake .. \ cmake .. \
-DPADDLE_LIB=${LIB_DIR} \ -DPADDLE_LIB=${LIB_DIR} \
-DWITH_MKL=ON \ -DWITH_MKL=ON \
-DDEMO_NAME=clas_system \
-DWITH_GPU=OFF \ -DWITH_GPU=OFF \
-DWITH_STATIC_LIB=OFF \ -DWITH_STATIC_LIB=OFF \
-DWITH_TENSORRT=OFF \ -DUSE_TENSORRT=OFF \
-DTENSORRT_DIR=${TENSORRT_DIR} \
-DOPENCV_DIR=${OPENCV_DIR} \ -DOPENCV_DIR=${OPENCV_DIR} \
-DCUDNN_LIB=${CUDNN_LIB_DIR} \ -DCUDNN_LIB=${CUDNN_LIB_DIR} \
-DCUDA_LIB=${CUDA_LIB_DIR} \ -DCUDA_LIB=${CUDA_LIB_DIR} \
-DFAISS_DIR=${FAISS_DIR} \
-DFAISS_WITH_MKL=${FAISS_WITH_MKL}
make -j make -j
``` ```
...@@ -197,47 +193,75 @@ make -j ...@@ -197,47 +193,75 @@ make -j
上述命令中, 上述命令中,
* `OPENCV_DIR`为opencv编译安装的地址(本例中为`opencv-3.4.7/opencv3`文件夹的路径); * `OPENCV_DIR`为opencv编译安装的地址(本例中为`opencv-3.4.7/opencv3`文件夹的路径);
* `LIB_DIR`为下载的Paddle预测库(`paddle_inference`文件夹),或编译生成的Paddle预测库(`build/paddle_inference_install_dir`文件夹)的路径; * `LIB_DIR`为下载的Paddle预测库(`paddle_inference`文件夹),或编译生成的Paddle预测库(`build/paddle_inference_install_dir`文件夹)的路径;
* `CUDA_LIB_DIR`为cuda库文件地址,在docker中为`/usr/local/cuda/lib64` * `CUDA_LIB_DIR`为cuda库文件地址,在docker中为`/usr/local/cuda/lib64`
* `CUDNN_LIB_DIR`为cudnn库文件地址,在docker中为`/usr/lib/x86_64-linux-gnu/` * `CUDNN_LIB_DIR`为cudnn库文件地址,在docker中为`/usr/lib/x86_64-linux-gnu/`
* `TENSORRT_DIR`是tensorrt库文件地址,在dokcer中为`/usr/local/TensorRT6-cuda10.0-cudnn7/`,TensorRT需要结合GPU使用。 * `TENSORRT_DIR`是tensorrt库文件地址,在dokcer中为`/usr/local/TensorRT6-cuda10.0-cudnn7/`,TensorRT需要结合GPU使用。
* `FAISS_DIR`是faiss的安装地址
* `FAISS_WITH_MKL`是指在编译faiss的过程中,是否使用了mkldnn,本文档中编译faiss,没有使用,而使用了openblas,故设置为`OFF`,若使用了mkldnn,则为`ON`.
在执行上述命令,编译完成之后,会在当前路径下生成`build`文件夹,其中生成一个名为`clas_system`的可执行文件。
在执行上述命令,编译完成之后,会在当前路径下生成`build`文件夹,其中生成一个名为`pp_shitu`的可执行文件。
### 运行demo ## 3 运行demo
* 首先修改`tools/config.txt`中对应字段:
* use_gpu:是否使用GPU;
* gpu_id:使用的GPU卡号;
* gpu_mem:显存;
* cpu_math_library_num_threads:底层科学计算库所用线程的数量;
* use_mkldnn:是否使用MKLDNN加速;
* use_tensorrt: 是否使用tensorRT进行加速;
* use_fp16:是否使用半精度浮点数进行计算,该选项仅在use_tensorrt为true时有效;
* cls_model_path:预测模型结构文件路径;
* cls_params_path:预测模型参数文件路径;
* resize_short_size:预处理时图像缩放大小;
* crop_size:预处理时图像裁剪后的大小。
* 然后修改`tools/run.sh` - 请参考[识别快速开始文档](../../docs/zh_CN/quick_start/quick_start_recognition.md),下载好相应的 轻量级通用主体检测模型、轻量级通用识别模型及瓶装饮料测试数据并解压。
* `./build/clas_system ./tools/config.txt ./docs/imgs/ILSVRC2012_val_00000666.JPEG`
* 上述命令中分别为:编译得到的可执行文件`clas_system`;运行时的配置文件`config.txt`;待预测的图像。
* 最后执行以下命令,完成对一幅图像的分类。 ```shell
mkdir models
cd models
wget https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/rec/models/inference/picodet_PPLCNet_x2_5_mainbody_lite_v1.0_infer.tar
tar -xf picodet_PPLCNet_x2_5_mainbody_lite_v1.0_infer.tar
wget https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/rec/models/inference/general_PPLCNet_x2_5_lite_v1.0_infer.tar
tar -xf general_PPLCNet_x2_5_lite_v1.0_infer.tar
cd ..
```shell mkdir data
sh tools/run.sh cd data
``` wget https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/rec/data/drink_dataset_v1.0.tar
tar -xf drink_dataset_v1.0.tar
cd ..
```
- 将相应的yaml文件拷到`test`文件夹下
```shell
cp ../configs/inference_drink.yaml .
```
-`inference_drink.yaml`中的相对路径,改成基于本目录的路径或者绝对路径。涉及到的参数有
- Global.infer_imgs :此参数可以是具体的图像地址,也可以是图像集所在的目录
- Global.det_inference_model_dir : 检测模型存储目录
- Global.rec_inference_model_dir : 识别模型存储目录
- IndexProcess.index_dir : 检索库的存储目录,在示例中,检索库在下载的demo数据中。
- 字典转换
由于python的检索库的字典,使用`pickle`进行的序列化存储,导致C++不方便读取,因此进行转换
```shell
python tools/transform_id_map.py -c inference_drink.yaml
```
转换成功后,在`IndexProcess.index_dir`目录下生成`id_map.txt`,方便c++ 读取。
- 执行程序
```shell
./build/pp_shitu -c inference_drink.yaml
# or
./build/pp_shitu -config inference_drink.yaml
```
若对图像集进行检索,则可能得到,如下结果。注意,此结果只做展示,具体以实际运行结果为准。
同时,需注意的是,由于opencv 版本问题,会导致图像在预处理的过程中,resize产生细微差别,导致python 和c++结果,轻微不同,如bbox相差几个像素,检索结果小数点后3位diff等。但不会改变最终检索label。
* 最终屏幕上会输出结果,如下图所示。 ![](../../docs/images/quick_start/shitu_c++_result.png)
<div align="center"> ## 4 使用自己模型
<img src="./docs/imgs/cpp_infer_result.png" width="600">
</div>
使用自己训练的模型,可以参考[模型导出](../../docs/zh_CN/inference_deployment/export_model.md),导出`inference model`,用于模型预测。
其中`class id`表示置信度最高的类别对应的id,score表示图片属于该类别的概率 同时注意修改`yaml`文件中具体参数
...@@ -18,7 +18,7 @@ ...@@ -18,7 +18,7 @@
namespace Feature { namespace Feature {
void FeatureExtracter::LoadModel(const std::string &model_path, void FeatureExtracter::LoadModel(const std::string &model_path,
const std::string &params_path) { const std::string &params_path) {
paddle_infer::Config config; paddle_infer::Config config;
config.SetModel(model_path, params_path); config.SetModel(model_path, params_path);
...@@ -52,9 +52,9 @@ void FeatureExtracter::LoadModel(const std::string &model_path, ...@@ -52,9 +52,9 @@ void FeatureExtracter::LoadModel(const std::string &model_path,
config.DisableGlogInfo(); config.DisableGlogInfo();
this->predictor_ = CreatePredictor(config); this->predictor_ = CreatePredictor(config);
} }
void FeatureExtracter::Run(cv::Mat &img, std::vector<float> &out_data, void FeatureExtracter::Run(cv::Mat &img, std::vector<float> &out_data,
std::vector<double> &times) { std::vector<double> &times) {
cv::Mat resize_img; cv::Mat resize_img;
std::vector<double> time; std::vector<double> time;
...@@ -108,12 +108,12 @@ void FeatureExtracter::Run(cv::Mat &img, std::vector<float> &out_data, ...@@ -108,12 +108,12 @@ void FeatureExtracter::Run(cv::Mat &img, std::vector<float> &out_data,
times[0] += time[0]; times[0] += time[0];
times[1] += time[1]; times[1] += time[1];
times[2] += time[2]; times[2] += time[2];
} }
void FeatureExtracter::FeatureNorm(std::vector<float> &featuer) { void FeatureExtracter::FeatureNorm(std::vector<float> &featuer) {
float featuer_sqrt = std::sqrt(std::inner_product( float featuer_sqrt = std::sqrt(std::inner_product(
featuer.begin(), featuer.end(), featuer.begin(), 0.0f)); featuer.begin(), featuer.end(), featuer.begin(), 0.0f));
for (int i = 0; i < featuer.size(); ++i) for (int i = 0; i < featuer.size(); ++i)
featuer[i] /= featuer_sqrt; featuer[i] /= featuer_sqrt;
} }
} // namespace Feature } // namespace Feature
...@@ -37,13 +37,15 @@ ...@@ -37,13 +37,15 @@
using namespace std; using namespace std;
using namespace cv; using namespace cv;
DEFINE_string(config, "", "Path of yaml file"); DEFINE_string(config,
DEFINE_string(c, "", "Path of yaml file"); "", "Path of yaml file");
DEFINE_string(c,
"", "Path of yaml file");
void DetPredictImage(const std::vector<cv::Mat> &batch_imgs, void DetPredictImage(const std::vector <cv::Mat> &batch_imgs,
const std::vector<std::string> &all_img_paths, const std::vector <std::string> &all_img_paths,
const int batch_size, Detection::ObjectDetector *det, const int batch_size, Detection::ObjectDetector *det,
std::vector<Detection::ObjectResult> &im_result, std::vector <Detection::ObjectResult> &im_result,
std::vector<int> &im_bbox_num, std::vector<double> &det_t, std::vector<int> &im_bbox_num, std::vector<double> &det_t,
const bool visual_det = false, const bool visual_det = false,
const bool run_benchmark = false, const bool run_benchmark = false,
...@@ -63,7 +65,7 @@ void DetPredictImage(const std::vector<cv::Mat> &batch_imgs, ...@@ -63,7 +65,7 @@ void DetPredictImage(const std::vector<cv::Mat> &batch_imgs,
// } // }
// Store all detected result // Store all detected result
std::vector<Detection::ObjectResult> result; std::vector <Detection::ObjectResult> result;
std::vector<int> bbox_num; std::vector<int> bbox_num;
std::vector<double> det_times; std::vector<double> det_times;
bool is_rbox = false; bool is_rbox = false;
...@@ -134,7 +136,7 @@ void DetPredictImage(const std::vector<cv::Mat> &batch_imgs, ...@@ -134,7 +136,7 @@ void DetPredictImage(const std::vector<cv::Mat> &batch_imgs,
} }
void PrintResult(std::string &img_path, void PrintResult(std::string &img_path,
std::vector<Detection::ObjectResult> &det_result, std::vector <Detection::ObjectResult> &det_result,
std::vector<int> &indeices, VectorSearch &vector_search, std::vector<int> &indeices, VectorSearch &vector_search,
SearchResult &search_result) { SearchResult &search_result) {
printf("%s:\n", img_path.c_str()); printf("%s:\n", img_path.c_str());
...@@ -194,9 +196,9 @@ int main(int argc, char **argv) { ...@@ -194,9 +196,9 @@ int main(int argc, char **argv) {
// load image_file_path // load image_file_path
std::string path = std::string path =
config.config_file["Global"]["infer_imgs"].as<std::string>(); config.config_file["Global"]["infer_imgs"].as<std::string>();
std::vector<std::string> img_files_list; std::vector <std::string> img_files_list;
if (cv::utils::fs::isDirectory(path)) { if (cv::utils::fs::isDirectory(path)) {
std::vector<cv::String> filenames; std::vector <cv::String> filenames;
cv::glob(path, filenames); cv::glob(path, filenames);
for (auto f : filenames) { for (auto f : filenames) {
img_files_list.push_back(f); img_files_list.push_back(f);
...@@ -209,10 +211,10 @@ int main(int argc, char **argv) { ...@@ -209,10 +211,10 @@ int main(int argc, char **argv) {
std::vector<double> cls_times = {0, 0, 0}; std::vector<double> cls_times = {0, 0, 0};
std::vector<double> det_times = {0, 0, 0}; std::vector<double> det_times = {0, 0, 0};
// for read images // for read images
std::vector<cv::Mat> batch_imgs; std::vector <cv::Mat> batch_imgs;
std::vector<std::string> img_paths; std::vector <std::string> img_paths;
// for detection // for detection
std::vector<Detection::ObjectResult> det_result; std::vector <Detection::ObjectResult> det_result;
std::vector<int> det_bbox_num; std::vector<int> det_bbox_num;
// for vector search // for vector search
std::vector<float> features; std::vector<float> features;
......
...@@ -22,7 +22,7 @@ using namespace paddle_infer; ...@@ -22,7 +22,7 @@ using namespace paddle_infer;
namespace Detection { namespace Detection {
// Load Model and create model predictor // Load Model and create model predictor
void ObjectDetector::LoadModel(const std::string &model_dir, void ObjectDetector::LoadModel(const std::string &model_dir,
const int batch_size, const int batch_size,
const std::string &run_mode) { const std::string &run_mode) {
paddle_infer::Config config; paddle_infer::Config config;
...@@ -64,11 +64,11 @@ void ObjectDetector::LoadModel(const std::string &model_dir, ...@@ -64,11 +64,11 @@ void ObjectDetector::LoadModel(const std::string &model_dir,
this->trt_max_shape_}; this->trt_max_shape_};
const std::vector<int> opt_input_shape = {1, 3, this->trt_opt_shape_, const std::vector<int> opt_input_shape = {1, 3, this->trt_opt_shape_,
this->trt_opt_shape_}; this->trt_opt_shape_};
const std::map<std::string, std::vector<int>> map_min_input_shape = { const std::map <std::string, std::vector<int>> map_min_input_shape = {
{"image", min_input_shape}}; {"image", min_input_shape}};
const std::map<std::string, std::vector<int>> map_max_input_shape = { const std::map <std::string, std::vector<int>> map_max_input_shape = {
{"image", max_input_shape}}; {"image", max_input_shape}};
const std::map<std::string, std::vector<int>> map_opt_input_shape = { const std::map <std::string, std::vector<int>> map_opt_input_shape = {
{"image", opt_input_shape}}; {"image", opt_input_shape}};
config.SetTRTDynamicShapeInfo(map_min_input_shape, map_max_input_shape, config.SetTRTDynamicShapeInfo(map_min_input_shape, map_max_input_shape,
...@@ -94,12 +94,12 @@ void ObjectDetector::LoadModel(const std::string &model_dir, ...@@ -94,12 +94,12 @@ void ObjectDetector::LoadModel(const std::string &model_dir,
// Memory optimization // Memory optimization
config.EnableMemoryOptim(); config.EnableMemoryOptim();
predictor_ = std::move(CreatePredictor(config)); predictor_ = std::move(CreatePredictor(config));
} }
// Visualiztion MaskDetector results // Visualiztion MaskDetector results
cv::Mat VisualizeResult(const cv::Mat &img, cv::Mat VisualizeResult(const cv::Mat &img,
const std::vector<ObjectResult> &results, const std::vector <ObjectResult> &results,
const std::vector<std::string> &lables, const std::vector <std::string> &lables,
const std::vector<int> &colormap, const std::vector<int> &colormap,
const bool is_rbox = false) { const bool is_rbox = false) {
cv::Mat vis_img = img.clone(); cv::Mat vis_img = img.clone();
...@@ -151,17 +151,17 @@ cv::Mat VisualizeResult(const cv::Mat &img, ...@@ -151,17 +151,17 @@ cv::Mat VisualizeResult(const cv::Mat &img,
cv::Scalar(255, 255, 255), thickness); cv::Scalar(255, 255, 255), thickness);
} }
return vis_img; return vis_img;
} }
void ObjectDetector::Preprocess(const cv::Mat &ori_im) { void ObjectDetector::Preprocess(const cv::Mat &ori_im) {
// Clone the image : keep the original mat for postprocess // Clone the image : keep the original mat for postprocess
cv::Mat im = ori_im.clone(); cv::Mat im = ori_im.clone();
cv::cvtColor(im, im, cv::COLOR_BGR2RGB); cv::cvtColor(im, im, cv::COLOR_BGR2RGB);
preprocessor_.Run(&im, &inputs_); preprocessor_.Run(&im, &inputs_);
} }
void ObjectDetector::Postprocess(const std::vector<cv::Mat> mats, void ObjectDetector::Postprocess(const std::vector <cv::Mat> mats,
std::vector<ObjectResult> *result, std::vector <ObjectResult> *result,
std::vector<int> bbox_num, std::vector<int> bbox_num,
bool is_rbox = false) { bool is_rbox = false) {
result->clear(); result->clear();
...@@ -215,11 +215,11 @@ void ObjectDetector::Postprocess(const std::vector<cv::Mat> mats, ...@@ -215,11 +215,11 @@ void ObjectDetector::Postprocess(const std::vector<cv::Mat> mats,
} }
start_idx += bbox_num[im_id]; start_idx += bbox_num[im_id];
} }
} }
void ObjectDetector::Predict(const std::vector<cv::Mat> imgs, const int warmup, void ObjectDetector::Predict(const std::vector <cv::Mat> imgs, const int warmup,
const int repeats, const int repeats,
std::vector<ObjectResult> *result, std::vector <ObjectResult> *result,
std::vector<int> *bbox_num, std::vector<int> *bbox_num,
std::vector<double> *times) { std::vector<double> *times) {
auto preprocess_start = std::chrono::steady_clock::now(); auto preprocess_start = std::chrono::steady_clock::now();
...@@ -344,9 +344,9 @@ void ObjectDetector::Predict(const std::vector<cv::Mat> imgs, const int warmup, ...@@ -344,9 +344,9 @@ void ObjectDetector::Predict(const std::vector<cv::Mat> imgs, const int warmup,
std::chrono::duration<float> postprocess_diff = std::chrono::duration<float> postprocess_diff =
postprocess_end - postprocess_start; postprocess_end - postprocess_start;
times->push_back(double(postprocess_diff.count() * 1000)); times->push_back(double(postprocess_diff.count() * 1000));
} }
std::vector<int> GenerateColorMap(int num_class) { std::vector<int> GenerateColorMap(int num_class) {
auto colormap = std::vector<int>(3 * num_class, 0); auto colormap = std::vector<int>(3 * num_class, 0);
for (int i = 0; i < num_class; ++i) { for (int i = 0; i < num_class; ++i) {
int j = 0; int j = 0;
...@@ -360,6 +360,6 @@ std::vector<int> GenerateColorMap(int num_class) { ...@@ -360,6 +360,6 @@ std::vector<int> GenerateColorMap(int num_class) {
} }
} }
return colormap; return colormap;
} }
} // namespace Detection } // namespace Detection
...@@ -32,16 +32,16 @@ ...@@ -32,16 +32,16 @@
namespace Feature { namespace Feature {
void Permute::Run(const cv::Mat *im, float *data) { void Permute::Run(const cv::Mat *im, float *data) {
int rh = im->rows; int rh = im->rows;
int rw = im->cols; int rw = im->cols;
int rc = im->channels(); int rc = im->channels();
for (int i = 0; i < rc; ++i) { for (int i = 0; i < rc; ++i) {
cv::extractChannel(*im, cv::Mat(rh, rw, CV_32FC1, data + i * rh * rw), i); cv::extractChannel(*im, cv::Mat(rh, rw, CV_32FC1, data + i * rh * rw), i);
} }
} }
void Normalize::Run(cv::Mat *im, const std::vector<float> &mean, void Normalize::Run(cv::Mat *im, const std::vector<float> &mean,
const std::vector<float> &std, float scale) { const std::vector<float> &std, float scale) {
(*im).convertTo(*im, CV_32FC3, scale); (*im).convertTo(*im, CV_32FC3, scale);
for (int h = 0; h < im->rows; h++) { for (int h = 0; h < im->rows; h++) {
...@@ -54,18 +54,18 @@ void Normalize::Run(cv::Mat *im, const std::vector<float> &mean, ...@@ -54,18 +54,18 @@ void Normalize::Run(cv::Mat *im, const std::vector<float> &mean,
(im->at<cv::Vec3f>(h, w)[2] - mean[2]) / std[2]; (im->at<cv::Vec3f>(h, w)[2] - mean[2]) / std[2];
} }
} }
} }
void CenterCropImg::Run(cv::Mat &img, const int crop_size) { void CenterCropImg::Run(cv::Mat &img, const int crop_size) {
int resize_w = img.cols; int resize_w = img.cols;
int resize_h = img.rows; int resize_h = img.rows;
int w_start = int((resize_w - crop_size) / 2); int w_start = int((resize_w - crop_size) / 2);
int h_start = int((resize_h - crop_size) / 2); int h_start = int((resize_h - crop_size) / 2);
cv::Rect rect(w_start, h_start, crop_size, crop_size); cv::Rect rect(w_start, h_start, crop_size, crop_size);
img = img(rect); img = img(rect);
} }
void ResizeImg::Run(const cv::Mat &img, cv::Mat &resize_img, void ResizeImg::Run(const cv::Mat &img, cv::Mat &resize_img,
int resize_short_size, int size) { int resize_short_size, int size) {
int resize_h = 0; int resize_h = 0;
int resize_w = 0; int resize_w = 0;
...@@ -86,6 +86,6 @@ void ResizeImg::Run(const cv::Mat &img, cv::Mat &resize_img, ...@@ -86,6 +86,6 @@ void ResizeImg::Run(const cv::Mat &img, cv::Mat &resize_img,
resize_w = round(float(w) * ratio); resize_w = round(float(w) * ratio);
} }
cv::resize(img, resize_img, cv::Size(resize_w, resize_h)); cv::resize(img, resize_img, cv::Size(resize_w, resize_h));
} }
} // namespace Feature } // namespace Feature
...@@ -19,15 +19,15 @@ ...@@ -19,15 +19,15 @@
namespace Detection { namespace Detection {
void InitInfo::Run(cv::Mat *im, ImageBlob *data) { void InitInfo::Run(cv::Mat *im, ImageBlob *data) {
data->im_shape_ = {static_cast<float>(im->rows), data->im_shape_ = {static_cast<float>(im->rows),
static_cast<float>(im->cols)}; static_cast<float>(im->cols)};
data->scale_factor_ = {1., 1.}; data->scale_factor_ = {1., 1.};
data->in_net_shape_ = {static_cast<float>(im->rows), data->in_net_shape_ = {static_cast<float>(im->rows),
static_cast<float>(im->cols)}; static_cast<float>(im->cols)};
} }
void NormalizeImage::Run(cv::Mat *im, ImageBlob *data) { void NormalizeImage::Run(cv::Mat *im, ImageBlob *data) {
double e = 1.0; double e = 1.0;
if (is_scale_) { if (is_scale_) {
e /= 255.0; e /= 255.0;
...@@ -43,9 +43,9 @@ void NormalizeImage::Run(cv::Mat *im, ImageBlob *data) { ...@@ -43,9 +43,9 @@ void NormalizeImage::Run(cv::Mat *im, ImageBlob *data) {
(im->at<cv::Vec3f>(h, w)[2] - mean_[2]) / scale_[2]; (im->at<cv::Vec3f>(h, w)[2] - mean_[2]) / scale_[2];
} }
} }
} }
void Permute::Run(cv::Mat *im, ImageBlob *data) { void Permute::Run(cv::Mat *im, ImageBlob *data) {
int rh = im->rows; int rh = im->rows;
int rw = im->cols; int rw = im->cols;
int rc = im->channels(); int rc = im->channels();
...@@ -54,9 +54,9 @@ void Permute::Run(cv::Mat *im, ImageBlob *data) { ...@@ -54,9 +54,9 @@ void Permute::Run(cv::Mat *im, ImageBlob *data) {
for (int i = 0; i < rc; ++i) { for (int i = 0; i < rc; ++i) {
cv::extractChannel(*im, cv::Mat(rh, rw, CV_32FC1, base + i * rh * rw), i); cv::extractChannel(*im, cv::Mat(rh, rw, CV_32FC1, base + i * rh * rw), i);
} }
} }
void Resize::Run(cv::Mat *im, ImageBlob *data) { void Resize::Run(cv::Mat *im, ImageBlob *data) {
auto resize_scale = GenerateScale(*im); auto resize_scale = GenerateScale(*im);
data->im_shape_ = {static_cast<float>(im->cols * resize_scale.first), data->im_shape_ = {static_cast<float>(im->cols * resize_scale.first),
static_cast<float>(im->rows * resize_scale.second)}; static_cast<float>(im->rows * resize_scale.second)};
...@@ -70,9 +70,9 @@ void Resize::Run(cv::Mat *im, ImageBlob *data) { ...@@ -70,9 +70,9 @@ void Resize::Run(cv::Mat *im, ImageBlob *data) {
data->scale_factor_ = { data->scale_factor_ = {
resize_scale.second, resize_scale.first, resize_scale.second, resize_scale.first,
}; };
} }
std::pair<double, double> Resize::GenerateScale(const cv::Mat &im) { std::pair<double, double> Resize::GenerateScale(const cv::Mat &im) {
std::pair<double, double> resize_scale; std::pair<double, double> resize_scale;
int origin_w = im.cols; int origin_w = im.cols;
int origin_h = im.rows; int origin_h = im.rows;
...@@ -97,9 +97,9 @@ std::pair<double, double> Resize::GenerateScale(const cv::Mat &im) { ...@@ -97,9 +97,9 @@ std::pair<double, double> Resize::GenerateScale(const cv::Mat &im) {
static_cast<double>(target_size_[0]) / static_cast<double>(origin_h); static_cast<double>(target_size_[0]) / static_cast<double>(origin_h);
} }
return resize_scale; return resize_scale;
} }
void PadStride::Run(cv::Mat *im, ImageBlob *data) { void PadStride::Run(cv::Mat *im, ImageBlob *data) {
if (stride_ <= 0) { if (stride_ <= 0) {
return; return;
} }
...@@ -113,18 +113,18 @@ void PadStride::Run(cv::Mat *im, ImageBlob *data) { ...@@ -113,18 +113,18 @@ void PadStride::Run(cv::Mat *im, ImageBlob *data) {
data->in_net_shape_ = { data->in_net_shape_ = {
static_cast<float>(im->rows), static_cast<float>(im->cols), static_cast<float>(im->rows), static_cast<float>(im->cols),
}; };
} }
// Preprocessor op running order // Preprocessor op running order
const std::vector<std::string> Preprocessor::RUN_ORDER = { const std::vector <std::string> Preprocessor::RUN_ORDER = {
"InitInfo", "Resize", "NormalizeImage", "PadStride", "Permute"}; "InitInfo", "Resize", "NormalizeImage", "PadStride", "Permute"};
void Preprocessor::Run(cv::Mat *im, ImageBlob *data) { void Preprocessor::Run(cv::Mat *im, ImageBlob *data) {
for (const auto &name : RUN_ORDER) { for (const auto &name : RUN_ORDER) {
if (ops_.find(name) != ops_.end()) { if (ops_.find(name) != ops_.end()) {
ops_[name]->Run(im, data); ops_[name]->Run(im, data);
} }
} }
} }
} // namespace Detection } // namespace Detection
...@@ -29,11 +29,11 @@ void VectorSearch::LoadIdMap() { ...@@ -29,11 +29,11 @@ void VectorSearch::LoadIdMap() {
std::string file_path = this->index_dir + OS_PATH_SEP + "id_map.txt"; std::string file_path = this->index_dir + OS_PATH_SEP + "id_map.txt";
std::ifstream in(file_path); std::ifstream in(file_path);
std::string line; std::string line;
std::vector<std::string> m_vec; std::vector <std::string> m_vec;
if (in) { if (in) {
while (getline(in, line)) { while (getline(in, line)) {
std::regex ws_re("\\s+"); std::regex ws_re("\\s+");
std::vector<std::string> v( std::vector <std::string> v(
std::sregex_token_iterator(line.begin(), line.end(), ws_re, -1), std::sregex_token_iterator(line.begin(), line.end(), ws_re, -1),
std::sregex_token_iterator()); std::sregex_token_iterator());
if (v.size() != 2) { if (v.size() != 2) {
......
...@@ -19,10 +19,10 @@ ...@@ -19,10 +19,10 @@
#include <include/yaml_config.h> #include <include/yaml_config.h>
std::vector<std::string> YamlConfig::ReadDict(const std::string &path) { std::vector <std::string> YamlConfig::ReadDict(const std::string &path) {
std::ifstream in(path); std::ifstream in(path);
std::string line; std::string line;
std::vector<std::string> m_vec; std::vector <std::string> m_vec;
if (in) { if (in) {
while (getline(in, line)) { while (getline(in, line)) {
m_vec.push_back(line); m_vec.push_back(line);
...@@ -42,7 +42,7 @@ std::map<int, std::string> YamlConfig::ReadIndexId(const std::string &path) { ...@@ -42,7 +42,7 @@ std::map<int, std::string> YamlConfig::ReadIndexId(const std::string &path) {
if (in) { if (in) {
while (getline(in, line)) { while (getline(in, line)) {
std::regex ws_re("\\s+"); std::regex ws_re("\\s+");
std::vector<std::string> v( std::vector <std::string> v(
std::sregex_token_iterator(line.begin(), line.end(), ws_re, -1), std::sregex_token_iterator(line.begin(), line.end(), ws_re, -1),
std::sregex_token_iterator()); std::sregex_token_iterator());
if (v.size() != 3) { if (v.size() != 3) {
......
OPENCV_DIR=/work/project/project/cpp_infer/opencv-3.4.7/opencv3 OPENCV_DIR=${opencv_install_dir}
LIB_DIR=/work/project/project/cpp_infer/paddle_inference/ LIB_DIR=${paddle_inference_dir}
CUDA_LIB_DIR=/usr/local/cuda/lib64 CUDA_LIB_DIR=/usr/local/cuda/lib64
CUDNN_LIB_DIR=/usr/lib/x86_64-linux-gnu/ CUDNN_LIB_DIR=/usr/lib/x86_64-linux-gnu/
FAISS_DIR=/work/project/project/cpp_infer/faiss/faiss_install FAISS_DIR=${faiss_install_dir}
FAISS_WITH_MKL=OFF FAISS_WITH_MKL=OFF
BUILD_DIR=build BUILD_DIR=build
......
# model load config
use_gpu 0
gpu_id 0
gpu_mem 4000
cpu_threads 10
use_mkldnn 1
use_tensorrt 0
use_fp16 0
# cls config
cls_model_path /PaddleClas/inference/cls_infer.pdmodel
cls_params_path /PaddleClas/inference/cls_infer.pdiparams
resize_short_size 256
crop_size 224
# for log env info
benchmark 0
./build/clas_system ../configs/inference_rec.yaml
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册