c语言 2027年最新OpenVINO计算机视觉模型加速-从零到几大案例实践 - auto next_infer_request = executable_network
c语言 2024年最新OpenVINO计算机视觉模型加速-从零到几大案例实践
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上C C++开发知识点,真正体系化!
由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新
如果你需要这些资料,可以戳这里获取
cv::imshow("input", src);
cv::waitKey(0);
return 0;
}
void load_plate_recog_model(InferenceEngine::InferRequest& plate_request, std::string& plate_input_name1, std::string& plate_input_name2, std::string& plate_output_name) { //1、初始化Core ie InferenceEngine::Core ie;//IE的核心类 其实就是IE
//2、ie.ReadNetwork 读取CNN网络 需要模型里面的两个文件 resnet18.bin resnet18.xml
std::string xmlFilename = "D:/code/OpenVINO/license-plate-recognition-barrier-0001/FP32/license-plate-recognition-barrier-0001.xml";
std::string binFilename = "D:/code/OpenVINO/license-plate-recognition-barrier-0001/FP32/license-plate-recognition-barrier-0001.bin";
InferenceEngine::CNNNetwork network = ie.ReadNetwork(xmlFilename, binFilename);//读取到加载CNN网络就会自动解析网络结构然后就可以获取输入输出了
//3、获取输入与输出格式并设置精度
InferenceEngine::InputsDataMap inputs = network.getInputsInfo();//InputsDataMap本质是一个vector的数组,如果你有多个输入的话则对应每个
InferenceEngine::OutputsDataMap outputs = network.getOutputsInfo();
std::string input_name = "";
std::string output_name = "";
int cnt = 0;
for (auto item : inputs)//因为这个模型有两个输入 则会循环两次的
{
if (cnt == 0)
{
plate_input_name1 = item.first;
auto input_data = item.second;//是一个数据结构 暂采用C++11的auto自动推断 因为只有一个输入则暂时这样定义在里面设置它的精度
input_data->setPrecision(Precision::U8);//输入图片数据格式为unsigned char 就是8位的精度
//这个也是根据模型设置的输入数据模式
input_data->setLayout(Layout::NCHW);
//也是根据模型设置输入的ColorFormat
input_data->getPreProcess().setColorFormat(ColorFormat::BGR);//该模型规定输入图片为BGR
}
if (cnt == 1)
{
plate_input_name2 = item.first;
auto input_data = item.second;
input_data->setPrecision(Precision::FP32);
}
//input_name = item.first; 拼多多帮助力入口
std::cout << "input name " << cnt+1 << " = " << item.first << std::endl;
cnt++;
}
for (auto item : outputs)
{
plate_output_name = item.first;
auto output_data = item.second;//是一个数据结构 暂采用C++11的auto自动推断 因为只有一个输入则暂时这样定义在里面设置它的精度
output_data->setPrecision(Precision::FP32);//输出还是浮点数输出的
std::cout << "output name = " << plate_output_name << std::endl;
}
//4、获取可执行网络并链接硬件
auto executable_network = ie.LoadNetwork(network, "CPU");//会加载网络到CPU这个硬件,也可以设置成GPU
//5、创建推理请求 创建之后就可以尝试进行推理了,但是实际在推理之前还有很多事情要做,如格式设置
plate_request = executable_network.CreateInferRequest();
}
void fetch_plate_text(InferenceEngine::InferRequest& plate_request, std::string& plate_input_name1, std::string& plate_input_name2, std::string& plate_output_name, cv::Mat& image, cv::Mat plateROI) { //设置输入 auto input1 = plate_request.GetBlob(plate_input_name1); size_t num_channels = input1->getTensorDesc().getDims()[1]; size_t h = input1->getTensorDesc().getDims()[2]; size_t w = input1->getTensorDesc().getDims()[3]; size_t image_size = h * w; cv::Mat blob_image;//转换为网络可以解析图片格式 cv::resize(plateROI, blob_image, cv::Size(w, h));//转换大小 unsigned char* data = static_cast(input1->buffer());//这就是直接将数据转换后填充到input那指定空间里面去了 //注意;opencv返回的mat图像的顺序是HWC 要将他转换为 NCHW 就是要将HWC类型的矩阵转换为NCHW类型 就是矩阵填充的问题 // HWC =》NCHW 转换 for (size_t row = 0; row < h; row++) { for (size_t col = 0; col < w; col++) { for (size_t ch = 0; ch < num_channels; ch++) { //blob_image 是opencv过来的HWC格式 -》 转换为NCHW就是每一个通道变成一张图 按照通道顺序来的。第几个通道的就是第几张图的这种存放 data[image_size * ch + row * w + col] = blob_image.atcv::Vec3b(row, col)[ch]; } } } auto input2 = plate_request.GetBlob(plate_input_name2); int max_sequence = input2->getTensorDesc().getDims()[0];//第二个输入的第一维是序列的长度 float* blob2 = input2->buffer().as(); blob2[0] = 0.0f; std::fill(blob2 + 1, blob2 + max_sequence, 1.0f);
//执行推理
plate_request.Infer();
//输出结果
auto output = plate_request.GetBlob(plate_output_name);
const float* plate_data = static_cast::value_type*>(output->buffer());//检测的输出结果std::string result;
for (int i = 0; i < max_sequence; i++)
{
if (plate_data[i] == -1)
break;
result += items[std::size_t(plate_data[i])];
}
cv::putText(image, result.c_str(), cv::Point(50, 50), cv::FONT_HERSHEY_SIMPLEX, 1.0, cv::Scalar(0, 0, 255), 2, 8);
}
### 3、行人检测
### 3.1、模型介绍



>
> 图 19 20 21
>
>
>
### 3.2、程序执行流程
因为都是SSD模型并且与车辆检测模型的输入输出格式一致都是BCHW的输入,1 1 N 7格式的输出,因此可以直接将车辆检测的整体代码直接拿过来用,只需要改一下模型路径即可。
### 3.3、程序演示部分

>
> 图22
>
>
>
### 3.4、视频当中的行人检测
代码流程差不多,只是将推理部分抽出成一个函数,通过传参的方式传入的,输入改为读取视频每帧都进行图像推理之后再显示。
可以看出对视频使用openVINO模型检测。对于速度方面是没有什么影响的,对于这个宽高不是很大的视频而言。openVINO模型对视频处理都是有每秒上百帧的效果的,也可以指定openVINO使用模型之后对模型也有很显著的加速效果的。
实践效果

>
> 图23
>
>
>
代码实践
#include “inference_engine.hpp” #include “opencv2/opencv.hpp” #include
using namespace InferenceEngine; void infer_process(cv::Mat &src, InferenceEngine::InferRequest & infer_request, std::string& input_name, std::string& output_name); //图像行人检测 int main(int argc, char** argv) { //1、初始化Core ie InferenceEngine::Core ie;//IE的核心类 其实就是IE
//2、ie.ReadNetwork 读取CNN网络 需要模型里面的两个文件 resnet18.bin resnet18.xml
std::string xmlFilename = "D:/code/OpenVINO/pedestrian-detection-adas-0002/FP32/pedestrian-detection-adas-0002.xml";
std::string binFilename = "D:/code/OpenVINO/pedestrian-detection-adas-0002/FP32/pedestrian-detection-adas-0002.bin";
InferenceEngine::CNNNetwork network = ie.ReadNetwork(xmlFilename, binFilename);//读取到加载CNN网络就会自动解析网络结构然后就可以获取输入输出了
//3、获取输入与输出格式并设置精度
InferenceEngine::InputsDataMap inputs = network.getInputsInfo();//InputsDataMap本质是一个vector的数组,如果你有多个输入的话则对应每个
InferenceEngine::OutputsDataMap outputs = network.getOutputsInfo();
std::string input_name = "";
std::string output_name = "";
for (auto item : inputs)
{
input_name = item.first;
auto input_data = item.second;//是一个数据结构 暂采用C++11的auto自动推断 因为只有一个输入则暂时这样定义在里面设置它的精度
input_data->setPrecision(Precision::U8);//输入图片数据格式为unsigned char 就是8位的精度
//这个也是根据模型设置的输入数据模式
input_data->setLayout(Layout::NCHW);
//也是根据模型设置输入的ColorFormat
input_data->getPreProcess().setColorFormat(ColorFormat::BGR);//该模型规定输入图片为BGR
std::cout << "input name = " << input_name << std::endl;
}
for (auto item : outputs)
{
output_name = item.first;
auto output_data = item.second;//是一个数据结构 暂采用C++11的auto自动推断 因为只有一个输入则暂时这样定义在里面设置它的精度
output_data->setPrecision(Precision::FP32);//输出还是浮点数输出的
std::cout << "output name = " << output_name << std::endl;
}
//4、获取可执行网络并链接硬件
auto executable_network = ie.LoadNetwork(network, "CPU");//会加载网络到CPU这个硬件,也可以设置成GPU
//5、创建推理请求 创建之后就可以尝试进行推理了,但是实际在推理之前还有很多事情要做,如格式设置
auto infer_request = executable_network.CreateInferRequest();
//6、创建视频流/加载视频文件
cv::VideoCapture capture("D:/padestrian_detection.mp4");
cv::Mat src;
while (true)
{
bool ret = capture.read(src);
if (ret == false)
break;
//7、循环执行推理
infer_process(src, infer_request, input_name, output_name);
cv::imshow("src", src);
char c = cv::waitKey(1);
if (c == 27)//按下esc
break;
}
//cv::imshow("pedestrian_detection_demo", src);
cv::waitKey(0);
return 0;
}
void infer_process(cv::Mat& src, InferenceEngine::InferRequest& infer_request, std::string& input_name, std::string& output_name) { //1、通过传入的推理引擎;获取输入的Blob 格式转换类对象 auto input = infer_request.GetBlob(input_name);//获取input的Blob(进行输入的格式设置的类对象) size_t num_channels = input->getTensorDesc().getDims()[1]; size_t h = input->getTensorDesc().getDims()[2]; size_t w = input->getTensorDesc().getDims()[3]; size_t image_size = h * w;
//2、对输入图像转换
int im_h = src.rows;
int im_w = src.cols;
cv::Mat blob_image;//转换为网络可以解析图片格式
cv::resize(src, blob_image, cv::Size(w, h));//转换大小
//3、将设置好的数据设置到输入的Blob中 ->实际上GetBlob()的时候就已经开辟好了存储输入图像数据内存空间
unsigned char* data = static_cast(input->buffer());//这就是直接将数据转换后填充到input那指定空间里面去了
//注意;opencv返回的mat图像的顺序是HWC 要将他转换为 NCHW 就是要将HWC类型的矩阵转换为NCHW类型 就是矩阵填充的问题
// HWC =》NCHW 转换
for (size_t row = 0; row < h; row++) {
for (size_t col = 0; col < w; col++) {
for (size_t ch = 0; ch < num_channels; ch++) {
//blob_image 是opencv过来的HWC格式 -》 转换为NCHW就是每一个通道变成一张图 按照通道顺序来的。第几个通道的就是第几张图的这种存放
data[image_size * ch + row * w + col] = blob_image.at(row, col)[ch];
}
}
}
//4、执行推理
infer_request.Infer();
//5、获取我们的output
auto output = infer_request.GetBlob(output_name);
const float* detection_out = static_cast::value_type*>(output->buffer());//检测的输出结果//6、最后需要获取输出的维度信息 解析数据
const SizeVector outputDims = output->getTensorDesc().getDims();
//std::cout << outputDims[2] << "X" << outputDims[3] << std::endl;
const int max_num = outputDims[2];//是输出的那个N
const int object_size = outputDims[3];//是输出的那个7
for (int n = 0; n < max_num; n++)
{
float lable = detection_out[n * object_size + 1];// +1表示输出的是7个里面的第二个lableID
float confidence = detection_out[n * object_size + 2];
float xmin = detection_out[n * object_size + 3] * im_w; //输出得到的都是0-1的浮点数坐标 要乘以原宽高才是实际坐标
float ymin = detection_out[n * object_size + 4] * im_h;
float xmax = detection_out[n * object_size + 5] * im_w;
float ymax = detection_out[n * object_size + 6] * im_h;
if (confidence > 0.5)
{
//printf("lable id = %d\n", static_cast(lable));
cv::Rect box;
box.x = static_cast(xmin);
box.y = static_cast(ymin);
box.width = static_cast(xmax - xmin);
box.height = static_cast(ymax - ymin);
cv::rectangle(src, box, cv::Scalar(0, 255, 0), 2, 8, 0);
cv::putText(src, cv::format("%.2f", confidence), box.tl(), cv::FONT_HERSHEY_SIMPLEX, 1.0, cv::Scalar(0, 0, 255), 1, 8);
}
}
}
### 4、实时人脸检测之异步推理
### 4.1、模型介绍
在OpenVINO当中自带了一系列的人脸检测的轻量级模型,多数都是可以达到100或更高的fps,所以说可以更适合部署在边缘端侧设备上的。



>
> 图24,25,26
>
>
>
可以与OpenCV做一个对比,opencv都是一个个算法都是传统模块,而OpenVINO了也是一个个算法所不同的是这里的一个个算法都是基于深度学习的模块,所提供的一个个模型,你根据这个模型去围绕开展就可以得到不同的算法表现
### 4.2、同步/异步执行
之前的模型实践都是使用的infer\_request.Infer()都是同步的模型,而异步的是有所差异的,
### 4.3、代码演示

>
> 图30
>
>
>
同步实现
异步实现

>
> 图27
>
>
>
代码实践
#include “inference_engine.hpp” #include “opencv2/opencv.hpp” #include
using namespace InferenceEngine; //将mat过来的数据U8类型的 转为Blob,因为Blob是任意类型的因此也声明为模板、 template void matU8ToBlob(const cv::Mat& orig_image, InferenceEngine::Blob::Ptr& blob, int batchIndex = 0) { InferenceEngine::SizeVector blobSize = blob->getTensorDesc().getDims(); const size_t width = blobSize[3]; const size_t height = blobSize[2]; const size_t channels = blobSize[1]; InferenceEngine::MemoryBlob::Ptr mblob = InferenceEngine::asInferenceEngine::MemoryBlob(blob); if (!mblob) { THROW_IE_EXCEPTION << "We expect blob to be inherited from MemoryBlob in matU8ToBlob, " << “but by fact we were not able to cast inputBlob to MemoryBlob”; } // locked memory holder should be alive all time while access to its buffer happens auto mblobHolder = mblob->wmap();
T* blob_data = mblobHolder.as();
cv::Mat resized_image(orig_image);
if (static_cast(width) != orig_image.size().width ||
static_cast(height) != orig_image.size().height) {
cv::resize(orig_image, resized_image, cv::Size(width, height));
}
int batchOffset = batchIndex * width * height * channels;
for (size_t c = 0; c < channels; c++) {
for (size_t h = 0; h < height; h++) {
for (size_t w = 0; w < width; w++) {
blob_data[batchOffset + c * width * height + h * width + w] =
resized_image.at(h, w)[c];
}
}
}
}
void infer_process(cv::Mat& src, std::shared_ptrInferenceEngine::InferRequest& infer_request, std::string& output_name); void frameToBlob(cv::Mat& src, std::shared_ptrInferenceEngine::InferRequest& infer_request, std::string& input_name);
int main(int argc, char** argv) { //1、初始化Core ie InferenceEngine::Core ie;//IE的核心类 其实就是IE
//2、ie.ReadNetwork 读取CNN网络 需要模型里面的两个文件 resnet18.bin resnet18.xml
std::string xmlFilename = "D:/code/OpenVINO/face-detection-0202/FP32/face-detection-0202.xml";
std::string binFilename = "D:/code/OpenVINO/face-detection-0202/FP32/face-detection-0202.bin";
InferenceEngine::CNNNetwork network = ie.ReadNetwork(xmlFilename, binFilename);//读取到加载CNN网络就会自动解析网络结构然后就可以获取输入输出了
//3、获取输入与输出格式并设置精度
InferenceEngine::InputsDataMap inputs = network.getInputsInfo();//InputsDataMap本质是一个vector的数组,如果你有多个输入的话则对应每个
InferenceEngine::OutputsDataMap outputs = network.getOutputsInfo();
std::string input_name = "";
std::string output_name = "";
for (auto item : inputs)
{
input_name = item.first;
auto input_data = item.second;//是一个数据结构 暂采用C++11的auto自动推断 因为只有一个输入则暂时这样定义在里面设置它的精度
input_data->setPrecision(Precision::U8);//输入图片数据格式为unsigned char 就是8位的精度
//这个也是根据模型设置的输入数据模式
input_data->setLayout(Layout::NCHW);
//也是根据模型设置输入的ColorFormat
input_data->getPreProcess().setColorFormat(ColorFormat::BGR);//该模型规定输入图片为BGR
std::cout << "input name = " << input_name << std::endl;
}
for (auto item : outputs)
{
output_name = item.first;
auto output_data = item.second;//是一个数据结构 暂采用C++11的auto自动推断 因为只有一个输入则暂时这样定义在里面设置它的精度
output_data->setPrecision(Precision::FP32);//输出还是浮点数输出的
std::cout << "output name = " << output_name << std::endl;
}
//4、获取可执行网络并链接硬件
auto executable_network = ie.LoadNetwork(network, "CPU");//会加载网络到CPU这个硬件,也可以设置成GPU
//5、创建推理请求 创建之后就可以尝试进行推理了,但是实际在推理之前还有很多事情要做,如格式设置
auto curr_infer_request = executable_network.CreateInferRequestPtr();
auto next_infer_request = executable_network.CreateInferRequestPtr();
//6、输入图像数据预处理(包括BGR->RGB,大小 浮点数 计算转换 图像顺序转换HWC->NCHW)
cv::VideoCapture capture(0);
cv::Mat curr_frame;
cv::Mat next_frame;
capture.read(curr_frame);
frameToBlob(curr_frame, curr_infer_request, input_name);
bool first_frame = true;
bool last_frame = false;
while (true)
{
bool ret = capture.read(next_frame);
if (ret == false)//是最后一帧了
{
last_frame = true;//不在输入设置了
}
if (!last_frame)//不是最后一帧就设置下一帧
{
frameToBlob(next_frame, next_infer_request, input_name);
}
if (first_frame)
{
curr_infer_request->StartAsync();//开始进行推理
next_infer_request->StartAsync();
first_frame = false;
}
else
{
if (!last_frame)//每次开始都是下一帧准备异步 下面有交换
{
next_infer_request->StartAsync();
}
}
//7、循环执行推理 每次推理都是当前帧 等待推理成功就进行解析
if (InferenceEngine::OK == curr_infer_request->Wait(InferenceEngine::IInferRequest::WaitMode::RESULT_READY))
{
infer_process(curr_frame, curr_infer_request, output_name);
}
cv::imshow("src", curr_frame);
char c = cv::waitKey(1);
if (c == 27)//按下esc
break;
if (last_frame)
{
break;
}
// 异步交互
next_frame.copyTo(curr_frame);
curr_infer_request.swap(next_infer_request);//指针域里面的函数
}
return 0;
} // SSD MobileNetV2 模型输入推理设置函数封装 因为要修改infer_request 所有还是需要传指针,智能指针 void frameToBlob(cv::Mat& src, std::shared_ptrInferenceEngine::InferRequest& infer_request, std::string& input_name) { //1、通过传入的推理引擎;获取输入的Blob 格式转换类对象 auto input = infer_request->GetBlob(input_name);//获取input的Blob(进行输入的格式设置的类对象) matU8ToBlob(src, input); return; } // SSD MobileNetV2 模型输出推理函数封装 void infer_process(cv::Mat& src, std::shared_ptrInferenceEngine::InferRequest& infer_request, std::string& output_name) { //1、执行推理 //infer_request->Infer(); 异步推理就不需要这一步了
//2、获取我们的output
auto output = infer_request->GetBlob(output_name);
const float* detection_out = static_cast::value_type*>(output->buffer());//检测的输出结果//3、最后需要获取输出的维度信息 解析数据
const SizeVector outputDims = output->getTensorDesc().getDims();
//std::cout << outputDims[2] << "X" << outputDims[3] << std::endl;
const int max_num = outputDims[2];//是输出的那个N
const int object_size = outputDims[3];//是输出的那个7
int im_h = src.rows;
int im_w = src.cols;
for (int n = 0; n < max_num; n++)
{
float lable = detection_out[n * object_size + 1];// +1表示输出的是7个里面的第二个lableID
float confidence = detection_out[n * object_size + 2];
float xmin = detection_out[n * object_size + 3] * im_w; //输出得到的都是0-1的浮点数坐标 要乘以原宽高才是实际坐标
float ymin = detection_out[n * object_size + 4] * im_h;
float xmax = detection_out[n * object_size + 5] * im_w;
float ymax = detection_out[n * object_size + 6] * im_h;
if (confidence > 0.5)
{
//printf("lable id = %d\n", static_cast(lable));
cv::Rect box;
box.x = static_cast(xmin);
box.y = static_cast(ymin);
box.width = static_cast(xmax - xmin);
box.height = static_cast(ymax - ymin);
cv::rectangle(src, box, cv::Scalar(0, 255, 0), 2, 8, 0);
cv::putText(src, cv::format("%.2f", confidence), box.tl(), cv::FONT_HERSHEY_SIMPLEX, 1.0, cv::Scalar(0, 0, 255), 1, 8);
}
}
}
### 5、实时人脸表情识别
主要是基于人脸检测的前提下加载人脸表情识别的模型对人脸常见的5种表情进行识别。
### 5.1、模型介绍


>
> 图28、29
>
>
>
### 5.2、程序执行流程
就是基于人脸检测之后将人脸检测的ROI区域送给表情识别模型,再进行检测输出结果。
注意;做一下保护 保证人脸检测获取到的矩形在图像内, 做大小判断而不是坐标判断,否则人脸表情检测的时候进行设置输入时会奔溃。
### 5.3、代码演示

>
> 图31
>
>
>
代码实践
#include “inference_engine.hpp” #include “opencv2/opencv.hpp” #include
using namespace InferenceEngine; //将mat过来的数据U8类型的 转为Blob,因为Blob是任意类型的因此也声明为模板、 template void matU8ToBlob(const cv::Mat& orig_image, InferenceEngine::Blob::Ptr& blob, int batchIndex = 0) { InferenceEngine::SizeVector blobSize = blob->getTensorDesc().getDims(); const size_t width = blobSize[3]; const size_t height = blobSize[2]; const size_t channels = blobSize[1]; InferenceEngine::MemoryBlob::Ptr mblob = InferenceEngine::asInferenceEngine::MemoryBlob(blob); if (!mblob) { THROW_IE_EXCEPTION << "We expect blob to be inherited from MemoryBlob in matU8ToBlob, " << “but by fact we were not able to cast inputBlob to MemoryBlob”; } // locked memory holder should be alive all time while access to its buffer happens auto mblobHolder = mblob->wmap();
T* blob_data = mblobHolder.as();
cv::Mat resized_image(orig_image);
if (static_cast(width) != orig_image.size().width ||
static_cast(height) != orig_image.size().height) {
cv::resize(orig_image, resized_image, cv::Size(width, height));
}
int batchOffset = batchIndex * width * height * channels;
for (size_t c = 0; c < channels; c++) {
for (size_t h = 0; h < height; h++) {
for (size_t w = 0; w < width; w++) {
blob_data[batchOffset + c * width * height + h * width + w] =
resized_image.at(h, w)[c];
}
}
}
}
//表情的几个值 static const char* const items[] = { “neutral”, “happy”, “sad”, “surprise”, “anger” };
//加载人脸表情识别的模型 传出 推理以及输入输出名称 void load_face_emotion_model(std::shared_ptrInferenceEngine::InferRequest& face_emotion_request, std::string& face_emotion_input_name, std::string& face_emotion_output_name);
//人脸表情检测 设置输入 推理 解析输出 std::string text_recognization_text(std::shared_ptrInferenceEngine::InferRequest& face_emotion_request, std::string& face_emotion_input_name, std::string& face_emotion_output_name, cv::Mat& image, cv::Rect& face_roi);
//人脸检测 异步推理之后对结果进行处理 cv::Rect infer_process(cv::Mat& src, std::shared_ptrInferenceEngine::InferRequest& infer_request, std::string& output_name);
//SSD MobileNetV2 模型输入推理设置函数 就是将输入的src转换为对应格式设置到 infer_request的Blob中 void frameToBlob(cv::Mat& src, std::shared_ptrInferenceEngine::InferRequest& infer_request, std::string& input_name);
int main(int argc, char** argv) { //加载人脸表情识别的模型 std::shared_ptrInferenceEngine::InferRequest face_emotion_request; std::string face_emotion_input_name; std::string face_emotion_output_name; load_face_emotion_model(face_emotion_request, face_emotion_input_name, face_emotion_output_name);
//1、初始化Core ie
InferenceEngine::Core ie;//IE的核心类 其实就是IE
//2、ie.ReadNetwork 读取CNN网络 需要模型里面的两个文件 resnet18.bin resnet18.xml
std::string xmlFilename = "D:/code/OpenVINO/face-detection-0202/FP32/face-detection-0202.xml";
std::string binFilename = "D:/code/OpenVINO/face-detection-0202/FP32/face-detection-0202.bin";
InferenceEngine::CNNNetwork network = ie.ReadNetwork(xmlFilename, binFilename);//读取到加载CNN网络就会自动解析网络结构然后就可以获取输入输出了
//3、获取输入与输出格式并设置精度
InferenceEngine::InputsDataMap inputs = network.getInputsInfo();//InputsDataMap本质是一个vector的数组,如果你有多个输入的话则对应每个
InferenceEngine::OutputsDataMap outputs = network.getOutputsInfo();
std::string input_name = "";
std::string output_name = "";
for (auto item : inputs)
{
input_name = item.first;
auto input_data = item.second;//是一个数据结构 暂采用C++11的auto自动推断 因为只有一个输入则暂时这样定义在里面设置它的精度
input_data->setPrecision(Precision::U8);//输入图片数据格式为unsigned char 就是8位的精度
//这个也是根据模型设置的输入数据模式
input_data->setLayout(Layout::NCHW);
//也是根据模型设置输入的ColorFormat
input_data->getPreProcess().setColorFormat(ColorFormat::BGR);//该模型规定输入图片为BGR
std::cout << "input name = " << input_name << std::endl;
}
for (auto item : outputs)
{
output_name = item.first;
auto output_data = item.second;//是一个数据结构 暂采用C++11的auto自动推断 因为只有一个输入则暂时这样定义在里面设置它的精度
output_data->setPrecision(Precision::FP32);//输出还是浮点数输出的
std::cout << "output name = " << output_name << std::endl;
}
//4、获取可执行网络并链接硬件
auto executable_network = ie.LoadNetwork(network, "CPU");//会加载网络到CPU这个硬件,也可以设置成GPU
//5、创建推理请求 创建之后就可以尝试进行推理了,但是实际在推理之前还有很多事情要做,如格式设置
auto curr_infer_request = executable_network.CreateInferRequestPtr();
auto next_infer_request = executable_network.CreateInferRequestPtr();
//6、输入图像数据预处理(包括BGR->RGB,大小 浮点数 计算转换 图像顺序转换HWC->NCHW)
cv::VideoCapture capture(0);
cv::Mat curr_frame;
cv::Mat next_frame;
capture.read(curr_frame);
frameToBlob(curr_frame, curr_infer_request, input_name);
bool first_frame = true;
bool last_frame = false;
while (true)
{
bool ret = capture.read(next_frame);
if (ret == false)//是最后一帧了
{
last_frame = true;//不在输入设置了
}
if (!last_frame)//不是最后一帧就设置下一帧
{
frameToBlob(next_frame, next_infer_request, input_name);
}
if (first_frame)
{
curr_infer_request->StartAsync();//开始进行推理
next_infer_request->StartAsync();
first_frame = false;
}
else
{
if (!last_frame)//每次开始都是下一帧准备异步 下面有交换
{
next_infer_request->StartAsync();
}
}
//7、循环执行推理 每次推理都是当前帧 等待推理成功就进行解析
if (InferenceEngine::OK == curr_infer_request->Wait(InferenceEngine::IInferRequest::WaitMode::RESULT_READY))
{
//人脸检测的推理 返回人脸矩形框
cv::Rect face_box = infer_process(curr_frame, curr_infer_request, output_name);
//对返回的人脸位置矩形框进行表情识别 设置输入 进行推理 解析输出
if(face_box.width > 64 && face_box.height > 64 && face_box.x > 0 && face_box.y > 0)//要做保护 不然容易奔溃
text_recognization_text(face_emotion_request, face_emotion_input_name, face_emotion_output_name, curr_frame, face_box);
}
cv::imshow("src", curr_frame);
char c = cv::waitKey(1);
if (c == 27)//按下esc
break;
if (last_frame)
{
break;
}
// 异步交互
next_frame.copyTo(curr_frame);
curr_infer_request.swap(next_infer_request);//指针域里面的函数
}
return 0;
} // SSD MobileNetV2 模型输入推理设置函数封装 因为要修改infer_request 所有还是需要传指针,智能指针 void frameToBlob(cv::Mat& src, std::shared_ptrInferenceEngine::InferRequest& infer_request, std::string& input_name) { //1、通过传入的推理引擎;获取输入的Blob 格式转换类对象 auto input = infer_request->GetBlob(input_name);//获取input的Blob(进行输入的格式设置的类对象) matU8ToBlob(src, input); return; } // SSD MobileNetV2 模型输出推理函数封装 cv::Rect infer_process(cv::Mat& src, std::shared_ptrInferenceEngine::InferRequest& infer_request, std::string& output_name) { //1、执行推理 //infer_request->Infer(); 异步推理就不需要这一步了 cv::Rect box; //2、获取我们的output auto output = infer_request->GetBlob(output_name); const float* detection_out = static_cast(output->buffer());//检测的输出结果
//3、最后需要获取输出的维度信息 解析数据
const SizeVector outputDims = output->getTensorDesc().getDims();
//std::cout << outputDims[2] << "X" << outputDims[3] << std::endl;
const int max_num = outputDims[2];//是输出的那个N
const int object_size = outputDims[3];//是输出的那个7
int im_h = src.rows;
int im_w = src.cols;
for (int n = 0; n < max_num; n++)
{
float lable = detection_out[n * object_size + 1];// +1表示输出的是7个里面的第二个lableID
float confidence = detection_out[n * object_size + 2];
float xmin = detection_out[n * object_size + 3] * im_w; //输出得到的都是0-1的浮点数坐标 要乘以原宽高才是实际坐标
float ymin = detection_out[n * object_size + 4] * im_h;
float xmax = detection_out[n * object_size + 5] * im_w;
float ymax = detection_out[n * object_size + 6] * im_h;
if (confidence > 0.9)
{
//printf("lable id = %d\n", static_cast(lable));、
//做一下保护 保证矩形在图像类 做大小判断而不是坐标判断
xmin = std::min(std::max(0.0f, xmin), static_cast(im_w));
ymin = std::min(std::max(0.0f, ymin), static_cast(im_h));
xmax = std::min(std::max(0.0f, xmax), static_cast(im_w));
ymax = std::min(std::max(0.0f, ymax), static_cast(im_h));
box.x = static_cast(xmin);
box.y = static_cast(ymin);
box.width = static_cast(xmax - xmin);
box.height = static_cast(ymax - ymin);
//std::cout << box.x << " " << box.y << " " << box.width << " " << box.height;
cv::rectangle(src, box, cv::Scalar(0, 255, 0), 2, 8, 0);
return box;
//cv::putText(src, cv::format("%.2f", confidence), box.tl(), cv::FONT_HERSHEY_SIMPLEX, 1.0, cv::Scalar(0, 0, 255), 1, 8);
}
}
return box;
} void load_face_emotion_model(std::shared_ptrInferenceEngine::InferRequest& face_emotion_request, std::string& face_emotion_input_name, std::string& face_emotion_output_name) { //1、初始化Core ie InferenceEngine::Core ie;//IE的核心类 其实就是IE
//2、ie.ReadNetwork 读取CNN网络 需要模型里面的两个文件 resnet18.bin resnet18.xml
std::string xmlFilename = "D:/code/OpenVINO/emotions-recognition-retail-0003/FP32/emotions-recognition-retail-0003.xml";
std::string binFilename = "D:/code/OpenVINO/emotions-recognition-retail-0003/FP32/emotions-recognition-retail-0003.bin";
InferenceEngine::CNNNetwork network = ie.ReadNetwork(xmlFilename, binFilename);//读取到加载CNN网络就会自动解析网络结构然后就可以获取输入输出了
//3、获取输入与输出格式并设置精度
InferenceEngine::InputsDataMap inputs = network.getInputsInfo();//InputsDataMap本质是一个vector的数组,如果你有多个输入的话则对应每个
InferenceEngine::OutputsDataMap outputs = network.getOutputsInfo();
std::string input_name = "";
std::string output_name = "";
for (auto item : inputs)//因为这个模型有两个输入 则会循环两次的
{
face_emotion_input_name = item.first;
auto input_data = item.second;//是一个数据结构 暂采用C++11的auto自动推断 因为只有一个输入则暂时这样定义在里面设置它的精度
input_data->setPrecision(Precision::U8);//输入图片数据格式为unsigned char 就是8位的精度
//这个也是根据模型设置的输入数据模式
input_data->setLayout(Layout::NCHW);
//也是根据模型设置输入的ColorFormat
input_data->getPreProcess().setColorFormat(ColorFormat::BGR);//该模型规定输入图片为BGR
}
for (auto item : outputs)
{
face_emotion_output_name = item.first;
auto output_data = item.second;//是一个数据结构 暂采用C++11的auto自动推断 因为只有一个输入则暂时这样定义在里面设置它的精度
output_data->setPrecision(Precision::FP32);//输出还是浮点数输出的
std::cout << "output name = " << face_emotion_output_name << std::endl;
}
//4、获取可执行网络并链接硬件
auto executable_network = ie.LoadNetwork(network, "CPU");//会加载网络到CPU这个硬件,也可以设置成GPU
//5、创建推理请求 创建之后就可以尝试进行推理了,但是实际在推理之前还有很多事情要做,如格式设置
face_emotion_request = executable_network.CreateInferRequestPtr();
}
std::string text_recognization_text(std::shared_ptrInferenceEngine::InferRequest& face_emotion_request, std::string& face_emotion_input_name, std::string& face_emotion_output_name, cv::Mat& image, cv::Rect& face_roi) { //设置输入 cv::Mat faceROI = image(face_roi); frameToBlob(faceROI, face_emotion_request, face_emotion_input_name);
//执行推理
face_emotion_request->Infer();
//输出string结果返回
auto output = face_emotion_request->GetBlob(face_emotion_output_name);
const float* probs = static_cast::value_type*>(output->buffer());//将输出数据转换 Precision精度//10、最后需要获取输出的维度信息 解析数据 并输出最大的那个就是我们resnet18图像识别出来的结果
const SizeVector outputDims = output->getTensorDesc().getDims();
float max = probs[0];
int max_index = 0;
for (int i = 1; i < outputDims[1]; i++)
{
if (max < probs[i])
{
max = probs[i];
max_index = i;
}
}
cv::putText(image, items[max_index], face_roi.tl(), cv::FONT_HERSHEY_SIMPLEX, 1.0, cv::Scalar(0, 0, 255), 2, 8);
return items[max_index];
}
### 6、人脸关键点landmark检测
### 6.1、模型介绍


>
> 图 32、33
>
>
>
### 6.2、程序执行流程
完成人脸检测获取ROI区域直接直接进行landMark检测即可。与人脸表情流程一致.
### 6.3、代码演示

>
> 图34
>
>
>
根本在于查看输入有几个是什么结构,输出是什么结构怎么解析、多个网络同时在一起怎么调用,同步与异步的使用。
代码实践
#include “inference_engine.hpp” #include “opencv2/opencv.hpp” #include
using namespace InferenceEngine; //将mat过来的数据U8类型的 转为Blob,因为Blob是任意类型的因此也声明为模板、 template void matU8ToBlob(const cv::Mat& orig_image, InferenceEngine::Blob::Ptr& blob, int batchIndex = 0) { InferenceEngine::SizeVector blobSize = blob->getTensorDesc().getDims(); const size_t width = blobSize[3]; const size_t height = blobSize[2]; const size_t channels = blobSize[1]; InferenceEngine::MemoryBlob::Ptr mblob = InferenceEngine::asInferenceEngine::MemoryBlob(blob); if (!mblob) { THROW_IE_EXCEPTION << "We expect blob to be inherited from MemoryBlob in matU8ToBlob, " << “but by fact we were not able to cast inputBlob to MemoryBlob”; } // locked memory holder should be alive all time while access to its buffer happens auto mblobHolder = mblob->wmap();
T* blob_data = mblobHolder.as();
cv::Mat resized_image(orig_image);
if (static_cast(width) != orig_image.size().width ||
static_cast(height) != orig_image.size().height) {
cv::resize(orig_image, resized_image, cv::Size(width, height));
}
int batchOffset = batchIndex * width * height * channels;
for (size_t c = 0; c < channels; c++) {
for (size_t h = 0; h < height; h++) {
for (size_t w = 0; w < width; w++) {
blob_data[batchOffset + c * width * height + h * width + w] =
resized_image.at(h, w)[c];
}
}
}
}
//表情的几个值 static const char* const items[] = { “neutral”, “happy”, “sad”, “surprise”, “anger” };
//加载人脸表情识别的模型 传出 推理以及输入输出名称 void load_textRecognization_model(std::string xmlFilename, std::string binFilename, std::shared_ptrInferenceEngine::InferRequest& face_request, std::string& face_input_name, std::string& face_output_name);
//人脸表情检测 设置输入 推理 解析输出 void text_recognization_text(std::shared_ptrInferenceEngine::InferRequest& face_emotion_request, std::string& face_emotion_input_name, std::string& face_emotion_output_name, cv::Mat& image, cv::Rect& face_roi);
//人脸检测 异步推理之后对结果进行处理 void infer_process(cv::Mat& src, std::shared_ptrInferenceEngine::InferRequest& infer_request, std::string& output_name, std::vectorcv::Rect& vc_RoiRect);
//SSD MobileNetV2 模型输入推理设置函数 就是将输入的src转换为对应格式设置到 infer_request的Blob中 void frameToBlob(cv::Mat& src, std::shared_ptrInferenceEngine::InferRequest& infer_request, std::string& input_name);
int main(int argc, char** argv) { //加载人脸表情识别的模型 std::shared_ptrInferenceEngine::InferRequest face_landmarks_request; std::string face_landmarks_input_name; std::string face_landmarks_output_name; std::string facial_landmarks_xmlFilename = “D:/code/OpenVINO/facial-landmarks-35-adas-0002/FP32/facial-landmarks-35-adas-0002.xml”; std::string facial_landmarks_binFilename = “D:/code/OpenVINO/facial-landmarks-35-adas-0002/FP32/facial-landmarks-35-adas-0002.bin”; load_textRecognization_model(facial_landmarks_xmlFilename, facial_landmarks_binFilename, face_landmarks_request, face_landmarks_input_name, face_landmarks_output_name);
//1、初始化Core ie
InferenceEngine::Core ie;//IE的核心类 其实就是IE
//2、ie.ReadNetwork 读取CNN网络 需要模型里面的两个文件 resnet18.bin resnet18.xml
std::string xmlFilename = "D:/code/OpenVINO/face-detection-0202/FP32/face-detection-0202.xml";
std::string binFilename = "D:/code/OpenVINO/face-detection-0202/FP32/face-detection-0202.bin";
InferenceEngine::CNNNetwork network = ie.ReadNetwork(xmlFilename, binFilename);//读取到加载CNN网络就会自动解析网络结构然后就可以获取输入输出了
//3、获取输入与输出格式并设置精度
InferenceEngine::InputsDataMap inputs = network.getInputsInfo();//InputsDataMap本质是一个vector的数组,如果你有多个输入的话则对应每个
InferenceEngine::OutputsDataMap outputs = network.getOutputsInfo();
std::string input_name = "";
std::string output_name = "";
for (auto item : inputs)
{
input_name = item.first;
auto input_data = item.second;//是一个数据结构 暂采用C++11的auto自动推断 因为只有一个输入则暂时这样定义在里面设置它的精度
input_data->setPrecision(Precision::U8);//输入图片数据格式为unsigned char 就是8位的精度
//这个也是根据模型设置的输入数据模式
input_data->setLayout(Layout::NCHW);
//也是根据模型设置输入的ColorFormat
input_data->getPreProcess().setColorFormat(ColorFormat::BGR);//该模型规定输入图片为BGR
std::cout << "input name = " << input_name << std::endl;
}
for (auto item : outputs)
{
output_name = item.first;
auto output_data = item.second;//是一个数据结构 暂采用C++11的auto自动推断 因为只有一个输入则暂时这样定义在里面设置它的精度
output_data->setPrecision(Precision::FP32);//输出还是浮点数输出的
std::cout << "output name = " << output_name << std::endl;
}
//4、获取可执行网络并链接硬件
auto executable_network = ie.LoadNetwork(network, "CPU");//会加载网络到CPU这个硬件,也可以设置成GPU
//5、创建推理请求 创建之后就可以尝试进行推理了,但是实际在推理之前还有很多事情要做,如格式设置
auto curr_infer_request = executable_network.CreateInferRequestPtr();
auto next_infer_request = executable_network.CreateInferRequestPtr();
//6、输入图像数据预处理(包括BGR->RGB,大小 浮点数 计算转换 图像顺序转换HWC->NCHW)
//图片读取
#if 1 cv::Mat curr_frame = cv::imread(“D:/face_emotion.jpg”); std::vectorcv::Rect vc_RoiRect; frameToBlob(curr_frame, curr_infer_request, input_name); curr_infer_request->Infer(); infer_process(curr_frame, curr_infer_request, output_name, vc_RoiRect); //对返回的人脸位置矩形框进行表情识别 设置输入 进行推理 解析输出 for (int i = 0; i < vc_RoiRect.size(); i++) { if (vc_RoiRect[i].width > 64 && vc_RoiRect[i].height > 64 && vc_RoiRect[i].x > 0 && vc_RoiRect[i].y > 0)//要做保护 不然容易奔溃 text_recognization_text(face_landmarks_request, face_landmarks_input_name, face_landmarks_output_name, curr_frame, vc_RoiRect[i]); } cv::imshow(“src”, curr_frame); char c = cv::waitKey(0); #endif #if 0 //视频读取 cv::VideoCapture capture(0); cv::Mat curr_frame; cv::Mat next_frame; capture.read(curr_frame); frameToBlob(curr_frame, curr_infer_request, input_name); bool first_frame = true; bool last_frame = false; std::vectorcv::Rect vc_RoiRect; while (true) { vc_RoiRect.clear(); bool ret = capture.read(next_frame); if (ret == false)//是最后一帧了 { last_frame = true;//不在输入设置了 } if (!last_frame)//不是最后一帧就设置下一帧 { frameToBlob(next_frame, next_infer_request, input_name); } if (first_frame) { curr_infer_request->StartAsync();//开始进行推理 next_infer_request->StartAsync(); first_frame = false; } else { if (!last_frame)//每次开始都是下一帧准备异步 下面有交换 { next_infer_request->StartAsync(); } } //7、循环执行推理 每次推理都是当前帧 等待推理成功就进行解析 if (InferenceEngine::OK == curr_infer_request->Wait(InferenceEngine::IInferRequest::WaitMode::RESULT_READY)) { //人脸检测的推理 返回人脸矩形框 infer_process(curr_frame, curr_infer_request, output_name, vc_RoiRect); //对返回的人脸位置矩形框进行表情识别 设置输入 进行推理 解析输出 for (int i = 0; i < vc_RoiRect.size(); i++) { if (vc_RoiRect[i].width > 64 && vc_RoiRect[i].height > 64 && vc_RoiRect[i].x > 0 && vc_RoiRect[i].y > 0)//要做保护 不然容易奔溃 face_lanmarks_text(face_landmarks_request, face_landmarks_input_name, face_landmarks_output_name, curr_frame, vc_RoiRect[i]); } } cv::imshow(“src”, curr_frame); char c = cv::waitKey(1); if (c == 27)//按下esc break; if (last_frame) { break; } // 异步交互 next_frame.copyTo(curr_frame); curr_infer_request.swap(next_infer_request);//指针域里面的函数 } #endif return 0; }
// SSD MobileNetV2 模型输入推理设置函数封装 因为要修改infer_request 所有还是需要传指针,智能指针 void frameToBlob(cv::Mat& src, std::shared_ptrInferenceEngine::InferRequest& infer_request, std::string& input_name) { //1、通过传入的推理引擎;获取输入的Blob 格式转换类对象 auto input = infer_request->GetBlob(input_name);//获取input的Blob(进行输入的格式设置的类对象) matU8ToBlob(src, input); return; } // SSD MobileNetV2 模型输出推理函数封装 void infer_process(cv::Mat& src, std::shared_ptrInferenceEngine::InferRequest& infer_request, std::string& output_name, std::vectorcv::Rect &vc_RoiRect) { //1、执行推理 //infer_request->Infer(); 异步推理就不需要这一步了 cv::Rect box; //2、获取我们的output auto output = infer_request->GetBlob(output_name); const float* detection_out = static_cast(output->buffer());//检测的输出结果
//3、最后需要获取输出的维度信息 解析数据
const SizeVector outputDims = output->getTensorDesc().getDims();
//std::cout << outputDims[2] << "X" << outputDims[3] << std::endl;
const int max_num = outputDims[2];//是输出的那个N
const int object_size = outputDims[3];//是输出的那个7
int im_h = src.rows;
int im_w = src.cols;
for (int n = 0; n < max_num; n++)
{
float lable = detection_out[n * object_size + 1];// +1表示输出的是7个里面的第二个lableID
float confidence = detection_out[n * object_size + 2];
float xmin = detection_out[n * object_size + 3] * im_w; //输出得到的都是0-1的浮点数坐标 要乘以原宽高才是实际坐标
float ymin = detection_out[n * object_size + 4] * im_h;
float xmax = detection_out[n * object_size + 5] * im_w;
float ymax = detection_out[n * object_size + 6] * im_h;
if (confidence > 0.95)
{
//printf("lable id = %d\n", static_cast(lable));、
//做一下保护 保证矩形在图像类 做大小判断而不是坐标判断
xmin = std::min(std::max(0.0f, xmin), static_cast(im_w));
ymin = std::min(std::max(0.0f, ymin), static_cast(im_h));
xmax = std::min(std::max(0.0f, xmax), static_cast(im_w));
ymax = std::min(std::max(0.0f, ymax), static_cast(im_h));
box.x = static_cast(xmin);
box.y = static_cast(ymin);
box.width = static_cast(xmax - xmin);
box.height = static_cast(ymax - ymin);
//std::cout << box.x << " " << box.y << " " << box.width << " " << box.height;
cv::rectangle(src, box, cv::Scalar(0, 255, 0), 2, 8, 0);
vc_RoiRect.push_back(box);
//cv::putText(src, cv::format("%.2f", confidence), box.tl(), cv::FONT_HERSHEY_SIMPLEX, 1.0, cv::Scalar(0, 0, 255), 1, 8);
}
}
return ;
}
void load_textRecognization_model(std::string xmlFilename, std::string binFilename, std::shared_ptrInferenceEngine::InferRequest& face_emotion_request, std::string& face_emotion_input_name, std::string& face_emotion_output_name) { //1、初始化Core ie InferenceEngine::Core ie;//IE的核心类 其实就是IE
//2、ie.ReadNetwork 读取CNN网络 需要模型里面的两个文件 resnet18.bin resnet18.xml
/*std::string xmlFilename = "D:/code/OpenVINO/facial-landmarks-35-adas-0002/FP32/facial-landmarks-35-adas-0002.xml";
std::string binFilename = "D:/code/OpenVINO/facial-landmarks-35-adas-0002/FP32/facial-landmarks-35-adas-0002.bin";*/
InferenceEngine::CNNNetwork network = ie.ReadNetwork(xmlFilename, binFilename);//读取到加载CNN网络就会自动解析网络结构然后就可以获取输入输出了
//3、获取输入与输出格式并设置精度
InferenceEngine::InputsDataMap inputs = network.getInputsInfo();//InputsDataMap本质是一个vector的数组,如果你有多个输入的话则对应每个
InferenceEngine::OutputsDataMap outputs = network.getOutputsInfo();
std::string input_name = "";
std::string output_name = "";
for (auto item : inputs)//因为这个模型有两个输入 则会循环两次的
{
face_emotion_input_name = item.first;
auto input_data = item.second;//是一个数据结构 暂采用C++11的auto自动推断 因为只有一个输入则暂时这样定义在里面设置它的精度
input_data->setPrecision(Precision::U8);//输入图片数据格式为unsigned char 就是8位的精度
//这个也是根据模型设置的输入数据模式
input_data->setLayout(Layout::NCHW);
//也是根据模型设置输入的ColorFormat
input_data->getPreProcess().setColorFormat(ColorFormat::BGR);//该模型规定输入图片为BGR
}
for (auto item : outputs)
{
face_emotion_output_name = item.first;
auto output_data = item.second;//是一个数据结构 暂采用C++11的auto自动推断 因为只有一个输入则暂时这样定义在里面设置它的精度
output_data->setPrecision(Precision::FP32);//输出还是浮点数输出的
std::cout << "output name = " << face_emotion_output_name << std::endl;
}
//4、获取可执行网络并链接硬件
auto executable_network = ie.LoadNetwork(network, "CPU");//会加载网络到CPU这个硬件,也可以设置成GPU
//5、创建推理请求 创建之后就可以尝试进行推理了,但是实际在推理之前还有很多事情要做,如格式设置
face_emotion_request = executable_network.CreateInferRequestPtr();
}
void text_recognization_text(std::shared_ptrInferenceEngine::InferRequest& face_lanmarks_request, std::string& face_lanmarks_input_name, std::string& face_lanmarks_output_name, cv::Mat& image, cv::Rect& face_roi) { //设置输入 cv::Mat faceROI = image(face_roi); frameToBlob(faceROI, face_lanmarks_request, face_lanmarks_input_name);
//执行推理
face_lanmarks_request->Infer();
//输出string结果返回
auto output = face_lanmarks_request->GetBlob(face_lanmarks_output_name);
const float* probs = static_cast::value_type*>(output->buffer());//将输出数据转换 Precision精度//10、最后需要获取输出的维度信息 解析数据 这里获取的坐标是相当于人脸的坐标 最后绘制点是需要以图片的坐标
const SizeVector outputDims = output->getTensorDesc().getDims();//
int i_width = face_roi.width;
int i_height = face_roi.height;
for (int i = 0; i < outputDims[1]; i+=2)
{
float x = probs[i] * i_width + face_roi.x;
float y = probs[i + 1] * i_height + face_roi.y;
cv::circle(image, cv::Point(x, y), 3, cv::Scalar(255, 0, 0), 2, 8, 0);//绘制圈
}
//cv::putText(image, items[max_index], face_roi.tl(), cv::FONT_HERSHEY_SIMPLEX, 1.0, cv::Scalar(0, 0, 255), 2, 8);
return ;
}
### 7、实时语义道路分割模型
OpenVINO也对语义道路分割模型进行了一个支持,这个支持也就是语义道路分割模型,它分割的道路为四个部分:背景,道路,路边,标记线(车道线等)。
### 7.1、模型介绍


>
> 图35、36
>
>
>
### 7.2、程序流程

>
> 图37
>
>
>
### 7.3、代码演示
关键就是在于如何解析分割网络中的多通道输出

>
> 图38
>
>
>
代码实践
#include “inference_engine.hpp” #include “opencv2/opencv.hpp” #include
using namespace InferenceEngine; //将mat过来的数据U8类型的 转为Blob,因为Blob是任意类型的因此也声明为模板、 template void matU8ToBlob(const cv::Mat& orig_image, InferenceEngine::Blob::Ptr& blob, int batchIndex = 0) { InferenceEngine::SizeVector blobSize = blob->getTensorDesc().getDims(); const size_t width = blobSize[3]; const size_t height = blobSize[2]; const size_t channels = blobSize[1]; InferenceEngine::MemoryBlob::Ptr mblob = InferenceEngine::asInferenceEngine::MemoryBlob(blob); if (!mblob) { THROW_IE_EXCEPTION << "We expect blob to be inherited from MemoryBlob in matU8ToBlob, " << “but by fact we were not able to cast inputBlob to MemoryBlob”; } // locked memory holder should be alive all time while access to its buffer happens auto mblobHolder = mblob->wmap();
T* blob_data = mblobHolder.as();
cv::Mat resized_image(orig_image);
if (static_cast(width) != orig_image.size().width ||
static_cast(height) != orig_image.size().height) {
cv::resize(orig_image, resized_image, cv::Size(width, height));
}
int batchOffset = batchIndex * width * height * channels;
for (size_t c = 0; c < channels; c++) {
for (size_t h = 0; h < height; h++) {
for (size_t w = 0; w < width; w++) {
blob_data[batchOffset + c * width * height + h * width + w] =
resized_image.at(h, w)[c];
}
}
}
} // SSD MobileNetV2 模型输入推理设置函数封装 因为要修改infer_request 所有还是需要传指针,智能指针 void infer_process(cv::Mat& src, std::shared_ptrInferenceEngine::InferRequest& infer_request, std::string& output_name); // SSD MobileNetV2 模型输出推理函数封装 void frameToBlob(cv::Mat& src, std::shared_ptrInferenceEngine::InferRequest& infer_request, std::string& input_name); std::vectorcv::Vec3b color_tab; int main(int argc, char** argv) { //1、初始化Core ie InferenceEngine::Core ie;//IE的核心类 其实就是IE
//2、ie.ReadNetwork 读取CNN网络 需要模型里面的两个文件 resnet18.bin resnet18.xml
std::string xmlFilename = "D:/code/OpenVINO/road-segmentation-adas-0001/FP32/road-segmentation-adas-0001.xml";
std::string binFilename = "D:/code/OpenVINO/road-segmentation-adas-0001/FP32/road-segmentation-adas-0001.bin";
InferenceEngine::CNNNetwork network = ie.ReadNetwork(xmlFilename, binFilename);//读取到加载CNN网络就会自动解析网络结构然后就可以获取输入输出了
//3、获取输入与输出格式并设置精度
InferenceEngine::InputsDataMap inputs = network.getInputsInfo();//InputsDataMap本质是一个vector的数组,如果你有多个输入的话则对应每个
InferenceEngine::OutputsDataMap outputs = network.getOutputsInfo();
std::string input_name = "";
std::string output_name = "";
for (auto item : inputs)
{
input_name = item.first;
auto input_data = item.second;//是一个数据结构 暂采用C++11的auto自动推断 因为只有一个输入则暂时这样定义在里面设置它的精度
input_data->setPrecision(Precision::U8);//输入图片数据格式为unsigned char 就是8位的精度
//这个也是根据模型设置的输入数据模式
input_data->setLayout(Layout::NCHW);
//也是根据模型设置输入的ColorFormat
input_data->getPreProcess().setColorFormat(ColorFormat::BGR);//该模型规定输入图片为BGR
std::cout << "input name = " << input_name << std::endl;
}
for (auto item : outputs)
{
output_name = item.first;
auto output_data = item.second;//是一个数据结构 暂采用C++11的auto自动推断 因为只有一个输入则暂时这样定义在里面设置它的精度
output_data->setPrecision(Precision::FP32);//输出还是浮点数输出的
std::cout << "output name = " << output_name << std::endl;
}
//4、获取可执行网络并链接硬件
auto executable_network = ie.LoadNetwork(network, "CPU");//会加载网络到CPU这个硬件,也可以设置成GPU
//5、创建推理请求 创建之后就可以尝试进行推理了,但是实际在推理之前还有很多事情要做,如格式设置
auto curr_infer_request = executable_network.CreateInferRequestPtr();
auto next_infer_request = executable_network.CreateInferRequestPtr();
//6、输入图像数据预处理(包括BGR->RGB,大小 浮点数 计算转换 图像顺序转换HWC->NCHW)
cv::VideoCapture capture("D:/lane.avi");
cv::Mat curr_frame;
cv::Mat next_frame;
capture.read(curr_frame);
//设置推理输入
frameToBlob(curr_frame, curr_infer_request, input_name);
bool first_frame = true;
bool last_frame = false;
color_tab.push_back(cv::Vec3b(0, 0, 0));//对应BG
color_tab.push_back(cv::Vec3b(255, 0, 0));//对应road
color_tab.push_back(cv::Vec3b(0, 0, 255));//对应curb
color_tab.push_back(cv::Vec3b(0, 255, 255));//对应mark
while (true)
{
bool ret = capture.read(next_frame);
if (ret == false)//是最后一帧了
{
last_frame = true;//不在输入设置了
}
if (!last_frame)//不是最后一帧就设置下一帧
{
frameToBlob(next_frame, next_infer_request, input_name);
}
if (first_frame)
{
curr_infer_request->StartAsync();//开始进行推理
next_infer_request->StartAsync();
first_frame = false;
}
else
{
if (!last_frame)//每次开始都是下一帧准备异步 下面有交换
{
next_infer_request->StartAsync();
}
}
//7、循环执行推理 每次推理都是当前帧 等待推理成功就进行解析
if (InferenceEngine::OK == curr_infer_request->Wait(InferenceEngine::IInferRequest::WaitMode::RESULT_READY))
{
infer_process(curr_frame, curr_infer_request, output_name);
}
cv::imshow("道路分割异步显示", curr_frame);
char c = cv::waitKey(1);
if (c == 27)//按下esc
break;
if (last_frame)
{
break;
}
// 异步交互
next_frame.copyTo(curr_frame);
curr_infer_request.swap(next_infer_request);//指针域里面的函数
}
return 0;
}
// SSD MobileNetV2 模型输入推理设置函数封装 因为要修改infer_request 所有还是需要传指针,智能指针 void frameToBlob(cv::Mat& src, std::shared_ptrInferenceEngine::InferRequest& infer_request, std::string& input_name) { //1、通过传入的推理引擎;获取输入的Blob 格式转换类对象 auto input = infer_request->GetBlob(input_name);//获取input的Blob(进行输入的格式设置的类对象) matU8ToBlob(src, input); return; }
// SSD MobileNetV2 模型输出推理函数封装 void infer_process(cv::Mat& src, std::shared_ptrInferenceEngine::InferRequest& infer_request, std::string& output_name) { //1、执行推理 //infer_request->Infer(); 异步推理就不需要这一步了
//2、获取我们的output
auto output = infer_request->GetBlob(output_name);
const float* detection_out = static_cast::value_type*>(output->buffer());//检测的输出结果//3、最后需要获取输出的维度信息 解析数据
//detection_out 是4*w*h个值的集合 我们要分析出h*w每个对应像素的四个值中的最大值保持下来
const SizeVector outputDims = output->getTensorDesc().getDims();
const int out_c = outputDims[1];//每个像素点的四个类型的值
const int out_h = outputDims[2];
const int out_w = outputDims[3];
cv::Mat result = cv::Mat::zeros(cv::Size(out_w, out_h), CV_8UC3);//存放结果
int step = out_h * out_w;
for (int row = 0; row < out_h; row++)
{
for (int col = 0; col < out_w; col++)
{
int max_index = 0;
float max_pord = detection_out[row * out_w + col];//该像素的第0个类别的权值
for (int cn = 1; cn < out_c; cn++)
{
float pord = detection_out[cn * step + row * out_w + col];//该像素的第i个类别的权值
if (pord > max_pord)
{
max_index = cn;
max_pord = pord;
}
}
result.at(row, col) = color_tab[max_index];//设置像素点的颜色值
}
}
cv::resize(result, result, cv::Size(src.cols, src.rows));//尺寸转换便于叠加
cv::addWeighted(src, 0.5, result, 0.5, 0, src);//叠加
return;
}
### 8、实例分割
我们最常见的实例分割模型就是:Mask R-CNN模型,而openVINO当中也支持多种Mask R-CNN,不同级别,不同分辨率的都是支持的。
### 8.1、实例分割模型


>
> 图39 40
>
>
>
### 8.2、程序执行流程
流程的关键还是在与处理输出,特别是解析raw\_masks的mask矩阵属性,需很利于opencv的相关知识进行转换叠加处理。
### 8.3、代码演示

>
> 图41
>
>
>
代码实践
#include “inference_engine.hpp” #include “opencv2/opencv.hpp” #include
using namespace InferenceEngine; //将mat过来的数据U8类型的 转为Blob,因为Blob是任意类型的因此也声明为模板、 template void matU8ToBlob(const cv::Mat& orig_image, InferenceEngine::Blob::Ptr& blob, int batchIndex = 0) { InferenceEngine::SizeVector blobSize = blob->getTensorDesc().getDims(); const size_t width = blobSize[3]; const size_t height = blobSize[2]; const size_t channels = blobSize[1]; InferenceEngine::MemoryBlob::Ptr mblob = InferenceEngine::asInferenceEngine::MemoryBlob(blob); if (!mblob) { THROW_IE_EXCEPTION << "We expect blob to be inherited from MemoryBlob in matU8ToBlob, " << “but by fact we were not able to cast inputBlob to MemoryBlob”; } // locked memory holder should be alive all time while access to its buffer happens auto mblobHolder = mblob->wmap();
T* blob_data = mblobHolder.as();
cv::Mat resized_image(orig_image);
if (static_cast(width) != orig_image.size().width ||
static_cast(height) != orig_image.size().height) {
cv::resize(orig_image, resized_image, cv::Size(width, height));
}
int batchOffset = batchIndex * width * height * channels;
for (size_t c = 0; c < channels; c++) {
for (size_t h = 0; h < height; h++) {
for (size_t w = 0; w < width; w++) {
blob_data[batchOffset + c * width * height + h * width + w] =
resized_image.at(h, w)[c];
}
}
}
} void read_coco_labels(std::vectorstd::string& labels) { std::string label_file = “coco_labels.txt”; std::ifstream fp(label_file); if (!fp.is_open()) { printf(“could not open file…\n”); exit(-1); } std::string name; while (!fp.eof()) { std::getline(fp, name); if (name.length()) labels.push_back(name); } fp.close(); } // SSD MobileNetV2 模型输入推理设置函数封装 因为要修改infer_request 所有还是需要传指针,智能指针 void infer_process(cv::Mat& src, std::shared_ptrInferenceEngine::InferRequest& infer_request); // SSD MobileNetV2 模型输出推理函数封装 void frameToBlob(cv::Mat& src, std::shared_ptrInferenceEngine::InferRequest& infer_request, std::string& input_name); std::vectorstd::string coco_labels; int main(int argc, char** argv) {
read_coco_labels(coco_labels);
//1、初始化Core ie
InferenceEngine::Core ie;//IE的核心类 其实就是IE
//2、ie.ReadNetwork 读取CNN网络 需要模型里面的两个文件 resnet18.bin resnet18.xml
std::string xmlFilename = "D:/code/OpenVINO/instance-segmentation-security-0050/FP32/instance-segmentation-security-0050.xml";
std::string binFilename = "D:/code/OpenVINO/instance-segmentation-security-0050/FP32/instance-segmentation-security-0050.bin";
InferenceEngine::CNNNetwork network = ie.ReadNetwork(xmlFilename, binFilename);//读取到加载CNN网络就会自动解析网络结构然后就可以获取输入输出了
//3、获取输入与输出格式并设置精度
InferenceEngine::InputsDataMap inputs = network.getInputsInfo();//InputsDataMap本质是一个vector的数组,如果你有多个输入的话则对应每个
InferenceEngine::OutputsDataMap outputs = network.getOutputsInfo();
std::string input_name = "";
std::string info_name = "";
int in_index = 0;
for (auto item : inputs)
{
if (in_index == 0)
{
input_name = item.first;
auto input_data = item.second;
input_data->setPrecision(Precision::U8);
input_data->setLayout(Layout::NCHW);
input_data->getPreProcess().setColorFormat(ColorFormat::BGR);
std::cout << "input name = " << input_name << std::endl;
}
else
{
info_name = item.first;
auto input_data = item.second;
input_data->setPrecision(Precision::FP32);
std::cout << "info_name name = " << info_name << std::endl;
}
in_index++;
}
for (auto item : outputs)//因为该模型是名字是准确的到时候访问的时候直接可以根据官方文档给的名字指定
{
std::string output_name = item.first;
auto output_data = item.second;//是一个数据结构 暂采用C++11的auto自动推断 因为只有一个输入则暂时这样定义在里面设置它的精度
output_data->setPrecision(Precision::FP32);//输出还是浮点数输出的
std::cout << "output name = " << output_name << std::endl;
}
//4、获取可执行网络并链接硬件
auto executable_network = ie.LoadNetwork(network, "CPU");//会加载网络到CPU这个硬件,也可以设置成GPU
//5、创建推理请求 创建之后就可以尝试进行推理了,但是实际在推理之前还有很多事情要做,如格式设置
auto curr_infer_request = executable_network.CreateInferRequestPtr();
//6、输入图像数据预处理(包括BGR->RGB,大小 浮点数 计算转换 图像顺序转换HWC->NCHW)
cv::Mat curr_frame = cv::imread("D:/objects.jpg");
std::vectorvc_RoiRect;
frameToBlob(curr_frame, curr_infer_request, input_name);//设置第一个输入
//设置第二个输入
auto input2 = curr_infer_request->GetBlob(info_name);
auto imInfoDim = inputs.find(info_name)->second->getTensorDesc().getDims()[1];
InferenceEngine::MemoryBlob::Ptr minput2 = InferenceEngine::as(input2);
auto minput2Holder = minput2->wmap();
float* p = minput2Holder.as::value_type*>();p[0] = static_cast(inputs[input_name]->getTensorDesc().getDims()[2]);
p[1] = static_cast(inputs[input_name]->getTensorDesc().getDims()[3]);
p[2] = 1.0f;
std::cout << p[0] << " " << p[1] << std::endl;
infer_process(curr_frame, curr_infer_request);
cv::imshow("src", curr_frame);
char c = cv::waitKey(0);
return 0;
}
// SSD MobileNetV2 模型输入推理设置函数封装 因为要修改infer_request 所有还是需要传指针,智能指针 void frameToBlob(cv::Mat& src, std::shared_ptrInferenceEngine::InferRequest& infer_request, std::string& input_name) { //1、通过传入的推理引擎;获取输入的Blob 格式转换类对象 auto input = infer_request->GetBlob(input_name);//获取input的Blob(进行输入的格式设置的类对象) matU8ToBlob(src, input); return; }
// SSD MobileNetV2 模型输出推理函数封装 void infer_process(cv::Mat& src, std::shared_ptrInferenceEngine::InferRequest& infer_request) { //1、执行推理 infer_request->Infer(); //异步推理就不需要这一步了
//2、获取我们的output
auto scores = infer_request->GetBlob("scores");
auto boxes = infer_request->GetBlob("boxes");
auto clazzes = infer_request->GetBlob("classes");
auto raw_masks = infer_request->GetBlob("raw_masks");
const float* scores_out = static_cast::value_type*>(scores->buffer());//检测的输出结果const float* boxes_out = static_cast::value_type*>(boxes->buffer());// 这个矩形输出的坐标大小是基于480*480的const float* clazzes_data = static_cast::value_type*>(clazzes->buffer());const auto raw_masks_data = static_cast::value_type*>(raw_masks->buffer());//输出的是 raw_masks 结构//3、最后需要获取输出的维度信息 解析数据
const SizeVector scores_outputDims = scores->getTensorDesc().getDims();
const SizeVector boxes_outputDims = boxes->getTensorDesc().getDims();
const SizeVector mask_outputDims = raw_masks->getTensorDesc().getDims();
const int max_scoresSize = scores_outputDims[0];//100
const int max_boxesSize = boxes_outputDims[1];//4
int mask_h = mask_outputDims[2];//raw_masks 宽高 真实与官方文档不一致 现在是14*14
int mask_w = mask_outputDims[3];
size_t box_stride = mask_h * mask_w * mask_outputDims[1];//表示每一个实例的之间的步距 81*14*14,这100个实例之间每个实例都隔这么多字节
int im_w = src.cols;
int im_h = src.rows;
float w_rate = static_cast(im_w) / 480.0;
float h_rate = static_cast(im_h) / 480.0;
cv::RNG rng(12345);
for (int i = 0; i < max_scoresSize; i++)
{
float confidence = scores_out[i];
float xmin = boxes_out[i * max_boxesSize] * w_rate; //这个矩形输出的坐标大小是基于480*480的
float ymin = boxes_out[i * max_boxesSize + 1] * h_rate;
float xmax = boxes_out[i * max_boxesSize + 2] * w_rate;
float ymax = boxes_out[i * max_boxesSize + 3] * h_rate;
if (confidence > 0.5)
{
cv::Scalar color(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));//得到一个随机颜色
cv::Rect box;
float x1 = std::min(std::max(0.0f, xmin), static_cast(im_w));
float y1 = std::min(std::max(0.0f, ymin), static_cast(im_h));
float x2 = std::min(std::max(0.0f, xmax), static_cast(im_w));
float y2 = std::min(std::max(0.0f, ymax), static_cast(im_h));
box.x = static_cast(x1);
box.y = static_cast(y1);
box.width = static_cast(x2 - x1);
box.height = static_cast(y2 - y1);
int label = static_cast(clazzes_data[i]);//输出这个实例是那里类别
// 解析mask 第i个实例(box_stride*i) + 81个类别的第几个类别 每个类别的步距是宽*高(mask_h * mask_w * label)
float* mask_arr = raw_masks_data + box_stride * i + mask_h * mask_w * label;//寻找到这个实例的这个类别对应的地址(大小是14*14)
cv::Mat mask_mat(mask_h, mask_w, CV_32FC1, mask_arr);//将数据创建到mat中大小为14*14的
cv::Mat roi_img = src(box);
cv::Mat resized_mask_mat(box.height, box.width, CV_32FC1);
cv::resize(mask_mat, resized_mask_mat, cv::Size(box.width, box.height));//进行尺寸转换
cv::Mat uchar_resized_mask(box.height, box.width, CV_8UC3, color);
roi_img.copyTo(uchar_resized_mask, resized_mask_mat <= 0.5);//将roi_img像素点对应resized_mask_mat为1的复制到uchar_resized_mask上去
cv::addWeighted(uchar_resized_mask, 0.7, roi_img, 0.3, 0.0f, roi_img);//进行mat叠加 uchar_resized_mask占比0.7,roi_img占比0.3 输出到roi_img
cv::putText(src, coco_labels[label].c_str(), box.tl() + (box.br() - box.tl()) / 2, cv::FONT_HERSHEY_PLAIN, 1.0, cv::Scalar(0, 0, 255), 1, 8);
}
}
return;
}
### 9、场景文字检测
### 9.1、模型介绍


>
> 图42 43
>
>
>
### 9.2、程序执行步骤
加载模式
设置输入
解析输出
### 9.3、代码演示

>
> 图44
>
>
>
代码实践
#include “inference_engine.hpp” #include “opencv2/opencv.hpp” #include
using namespace InferenceEngine; //将mat过来的数据U8类型的 转为Blob,因为Blob是任意类型的因此也声明为模板、 template void matU8ToBlob(const cv::Mat& orig_image, InferenceEngine::Blob::Ptr& blob, int batchIndex = 0) { InferenceEngine::SizeVector blobSize = blob->getTensorDesc().getDims(); const size_t width = blobSize[3]; const size_t height = blobSize[2]; const size_t channels = blobSize[1]; InferenceEngine::MemoryBlob::Ptr mblob = InferenceEngine::asInferenceEngine::MemoryBlob(blob); if (!mblob) { THROW_IE_EXCEPTION << "We expect blob to be inherited from MemoryBlob in matU8ToBlob, " << “but by fact we were not able to cast inputBlob to MemoryBlob”; } // locked memory holder should be alive all time while access to its buffer happens auto mblobHolder = mblob->wmap();
T* blob_data = mblobHolder.as();
cv::Mat resized_image(orig_image);
if (static_cast(width) != orig_image.size().width ||
static_cast(height) != orig_image.size().height) {
cv::resize(orig_image, resized_image, cv::Size(width, height));
}
int batchOffset = batchIndex * width * height * channels;
for (size_t c = 0; c < channels; c++) {
for (size_t h = 0; h < height; h++) {
for (size_t w = 0; w < width; w++) {
blob_data[batchOffset + c * width * height + h * width + w] =
resized_image.at(h, w)[c];
}
}
}
} // SSD MobileNetV2 模型输入推理设置函数封装 因为要修改infer_request 所有还是需要传指针,智能指针 void infer_process(cv::Mat& src, std::shared_ptrInferenceEngine::InferRequest& infer_request, std::string& output_name); // SSD MobileNetV2 模型输出推理函数封装 void frameToBlob(cv::Mat& src, std::shared_ptrInferenceEngine::InferRequest& infer_request, std::string& input_name); std::vectorcv::Vec3b color_tab; int main(int argc, char** argv) { //1、初始化Core ie InferenceEngine::Core ie;//IE的核心类 其实就是IE
//2、ie.ReadNetwork 读取CNN网络 需要模型里面的两个文件 resnet18.bin resnet18.xml
std::string xmlFilename = "D:/code/OpenVINO/text-detection-0003/FP32/text-detection-0003.xml";
std::string binFilename = "D:/code/OpenVINO/text-detection-0003/FP32/text-detection-0003.bin";
InferenceEngine::CNNNetwork network = ie.ReadNetwork(xmlFilename, binFilename);//读取到加载CNN网络就会自动解析网络结构然后就可以获取输入输出了
//3、获取输入与输出格式并设置精度
InferenceEngine::InputsDataMap inputs = network.getInputsInfo();//InputsDataMap本质是一个vector的数组,如果你有多个输入的话则对应每个
InferenceEngine::OutputsDataMap outputs = network.getOutputsInfo();
std::string input_name = "";
std::string output_name1 = "";
std::string output_name2 = "";
for (auto item : inputs)
{
input_name = item.first;
auto input_data = item.second;//是一个数据结构 暂采用C++11的auto自动推断 因为只有一个输入则暂时这样定义在里面设置它的精度
input_data->setPrecision(Precision::U8);//输入图片数据格式为unsigned char 就是8位的精度
//这个也是根据模型设置的输入数据模式
input_data->setLayout(Layout::NCHW);
//也是根据模型设置输入的ColorFormat
input_data->getPreProcess().setColorFormat(ColorFormat::BGR);//该模型规定输入图片为BGR
std::cout << "input name = " << input_name << std::endl;
}
int out_index = 0;
for (auto item : outputs)
{
if (out_index == 1)
{
output_name2 = item.first;
auto output_data = item.second;//是一个数据结构 暂采用C++11的auto自动推断 因为只有一个输入则暂时这样定义在里面设置它的精度
output_data->setPrecision(Precision::FP32);//输出还是浮点数输出的
std::cout << "output name = " << output_name1 << std::endl;
}
else
{
output_name1 = item.first;
auto output_data = item.second;//是一个数据结构 暂采用C++11的auto自动推断 因为只有一个输入则暂时这样定义在里面设置它的精度
output_data->setPrecision(Precision::FP32);//输出还是浮点数输出的
std::cout << "output name = " << output_name1 << std::endl;
}
out_index++;
}
//4、获取可执行网络并链接硬件
auto executable_network = ie.LoadNetwork(network, "CPU");//会加载网络到CPU这个硬件,也可以设置成GPU
//5、创建推理请求 创建之后就可以尝试进行推理了,但是实际在推理之前还有很多事情要做,如格式设置
auto curr_infer_request = executable_network.CreateInferRequestPtr();
auto next_infer_request = executable_network.CreateInferRequestPtr();
//6、输入图像数据预处理(包括BGR->RGB,大小 浮点数 计算转换 图像顺序转换HWC->NCHW)
#if 1 cv::Mat curr_frame = cv::imread(“D:/openvino_ocr.jpg”); std::vectorcv::Rect vc_RoiRect; frameToBlob(curr_frame, curr_infer_request, input_name); curr_infer_request->Infer(); infer_process(curr_frame, curr_infer_request, output_name2);//暂时只需要第二个输出就已经可以精确定位了 //cv::imshow(“src”, curr_frame); char c = cv::waitKey(0);
#endif
#if 0 cv::VideoCapture capture(“D:/lane.avi”); cv::Mat curr_frame; cv::Mat next_frame; capture.read(curr_frame); //设置推理输入 frameToBlob(curr_frame, curr_infer_request, input_name); bool first_frame = true; bool last_frame = false;
color_tab.push_back(cv::Vec3b(0, 0, 0));//对应BG
color_tab.push_back(cv::Vec3b(255, 0, 0));//对应road
color_tab.push_back(cv::Vec3b(0, 0, 255));//对应curb
color_tab.push_back(cv::Vec3b(0, 255, 255));//对应mark
while (true)
{
bool ret = capture.read(next_frame);
if (ret == false)//是最后一帧了
{
last_frame = true;//不在输入设置了
}
if (!last_frame)//不是最后一帧就设置下一帧
{
frameToBlob(next_frame, next_infer_request, input_name);
}
if (first_frame)
{
curr_infer_request->StartAsync();//开始进行推理
next_infer_request->StartAsync();
first_frame = false;
}
else
{
if (!last_frame)//每次开始都是下一帧准备异步 下面有交换
{
next_infer_request->StartAsync();
}
}
//7、循环执行推理 每次推理都是当前帧 等待推理成功就进行解析
if (InferenceEngine::OK == curr_infer_request->Wait(InferenceEngine::IInferRequest::WaitMode::RESULT_READY))
{
infer_process(curr_frame, curr_infer_request, output_name);
}
cv::imshow("道路分割异步显示", curr_frame);
char c = cv::waitKey(1);
if (c == 27)//按下esc
break;
if (last_frame)
{
break;
}
// 异步交互
next_frame.copyTo(curr_frame);
curr_infer_request.swap(next_infer_request);//指针域里面的函数
}
#endif
return 0;
}
// SSD MobileNetV2 模型输入推理设置函数封装 因为要修改infer_request 所有还是需要传指针,智能指针 void frameToBlob(cv::Mat& src, std::shared_ptrInferenceEngine::InferRequest& infer_request, std::string& input_name) { //1、通过传入的推理引擎;获取输入的Blob 格式转换类对象 auto input = infer_request->GetBlob(input_name);//获取input的Blob(进行输入的格式设置的类对象) matU8ToBlob(src, input); return; }
// SSD MobileNetV2 模型输出推理函数封装 void infer_process(cv::Mat& src, std::shared_ptrInferenceEngine::InferRequest& infer_request, std::string& output_name) { //1、执行推理 //infer_request->Infer(); 异步推理就不需要这一步了
//2、获取我们的output
auto output = infer_request->GetBlob(output_name);
//输出的值是0-1之间的浮点数表示这个类别的自信性 我们选择自信度比较大的那个类别即可
const float* detection_out = static_cast::value_type*>(output->buffer());//检测的输出结果//3、最后需要获取输出的维度信息 解析数据
//detection_out 是2*w*h个值的集合 我们要分析出h*w每个对应像素的2个类别 是text与非text
const SizeVector outputDims = output->getTensorDesc().getDims();
const int out_c = outputDims[1];//每个像素点的2个类型的值
const int out_h = outputDims[2];
const int out_w = outputDims[3];
cv::Mat mask = cv::Mat::zeros(cv::Size(out_w, out_h), CV_32F);//存放结果 0-1的
int step = out_h * out_w;
for (int row = 0; row < out_h; row++)
{
for (int col = 0; col < out_w; col++)
{
//文字检测模型 只有两个类别
float p1 = detection_out[row * out_w + col];//该像素第一个类别可能性值的
float p2 = detection_out[step + row * out_w + col];//该像素第二个类别可能性值的地址 是文本
if (p1 < p2)
{
mask.at(row, col) = p2;
}
}
}
cv::resize(mask, mask, cv::Size(src.cols, src.rows));//尺寸转换便于叠加
//变成一张二值图像
mask = mask * 255;//值乘以255 范围从0-1变为0-255
mask.convertTo(mask, CV_8U);//数据类型转换
cv::threshold(mask, mask, 200, 255, cv::THRESH_BINARY);
//绘制轮廓
std::vector> contours;既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上C C++开发知识点,真正体系化!
由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新
如果你需要这些资料,可以戳这里获取
转换类对象 auto input = infer_request->GetBlob(input_name);//获取input的Blob(进行输入的格式设置的类对象) matU8ToBlob(src, input); return; }
// SSD MobileNetV2 模型输出推理函数封装 void infer_process(cv::Mat& src, std::shared_ptrInferenceEngine::InferRequest& infer_request, std::string& output_name) { //1、执行推理 //infer_request->Infer(); 异步推理就不需要这一步了
//2、获取我们的output
auto output = infer_request->GetBlob(output_name);
//输出的值是0-1之间的浮点数表示这个类别的自信性 我们选择自信度比较大的那个类别即可
const float* detection_out = static_cast::value_type*>(output->buffer());//检测的输出结果//3、最后需要获取输出的维度信息 解析数据
//detection_out 是2*w*h个值的集合 我们要分析出h*w每个对应像素的2个类别 是text与非text
const SizeVector outputDims = output->getTensorDesc().getDims();
const int out_c = outputDims[1];//每个像素点的2个类型的值
const int out_h = outputDims[2];
const int out_w = outputDims[3];
cv::Mat mask = cv::Mat::zeros(cv::Size(out_w, out_h), CV_32F);//存放结果 0-1的
int step = out_h * out_w;
for (int row = 0; row < out_h; row++)
{
for (int col = 0; col < out_w; col++)
{
//文字检测模型 只有两个类别
float p1 = detection_out[row * out_w + col];//该像素第一个类别可能性值的
float p2 = detection_out[step + row * out_w + col];//该像素第二个类别可能性值的地址 是文本
if (p1 < p2)
{
mask.at(row, col) = p2;
}
}
}
cv::resize(mask, mask, cv::Size(src.cols, src.rows));//尺寸转换便于叠加
//变成一张二值图像
mask = mask * 255;//值乘以255 范围从0-1变为0-255
mask.convertTo(mask, CV_8U);//数据类型转换
cv::threshold(mask, mask, 200, 255, cv::THRESH_BINARY);
//绘制轮廓
std::vector> contours;[外链图片转存中…(img-JqYnKadD-1715661149559)] [外链图片转存中…(img-rIL0Jpf1-1715661149559)]
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上C C++开发知识点,真正体系化!
由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新
如果你需要这些资料,可以戳这里获取
c语言 2024年最新OpenVINO计算机视觉模型加速-从零到几大案例实践
参考文章