深度学习之用CelebA_Spoof数据集搭建一个活体检测-训练好的模型用MNN来推理

一、模型转换准备

首先确保已完成PyTorch到ONNX的转换:深度学习之用CelebA_Spoof数据集搭建活体检测系统:模型验证与测试。这里有将PyTorch到ONNX格式的模型转换。

二、ONNX转MNN

使用MNN转换工具进行格式转换:具体的编译过程可以参考MNN的官方代码。MNN是一个轻量级的深度神经网络引擎,支持深度学习的推理与训练。适用于服务器/个人电脑/手机/嵌入式各类设备。

./MNNConvert -f ONNX --modelFile live_spoof.onnx --MNNModel live_spoof.mnn

三、C++推理工程搭建

工程结构

mnn_inference/
├── CMakeLists.txt
├── include/
│   ├── InferenceInit.h
│   └── LiveSpoofDetector.h
├── src/
│   ├── InferenceInit.cpp
│   ├── LiveSpoofDetector.cpp
│   └── CMakeLists.txt
└── third_party/MNN/

根目录下的 CMakeLists.txt

cmake_minimum_required(VERSION 3.12)
project(MNNInference)# 设置C++标准
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)# 查找OpenCV
find_package(OpenCV REQUIRED)# 包含第三方库MNN
set(MNN_DIR ${CMAKE_SOURCE_DIR}/third_party/MNN)
include_directories(${MNN_DIR}/include)# 添加子目录
add_subdirectory(src)# 主可执行文件
add_executable(mnn_inference_main src/main.cpp
)# 链接库
target_link_libraries(mnn_inference_mainPRIVATEinference_lib${MNN_DIR}/lib/libMNN.so${OpenCV_LIBS}
)# 安装规则
install(TARGETS mnn_inference_mainRUNTIME DESTINATION bin
)

src目录下的 CMakeLists.txt

# 添加库
add_library(inference_lib STATICInferenceInit.cppLiveSpoofDetector.cpp
)# 包含目录
target_include_directories(inference_libPUBLIC${CMAKE_SOURCE_DIR}/include${MNN_DIR}/include${OpenCV_INCLUDE_DIRS}
)# 编译选项
target_compile_options(inference_libPRIVATE-Wall-O3
)

核心实现代码

将MNN读取导入模型和一些mnn_session进行预处理的公共部分抽取出来,以后可以更换不同的模型,只需要给出特定的预处理。

// InferenceInit.h
#ifndef MNN_CORE_MNN_HANDLER_H
#define MNN_CORE_MNN_HANDLER_H
#include "MNN/Interpreter.hpp"
#include "MNN/MNNDefine.h"
#include "MNN/Tensor.hpp"
#include "MNN/ImageProcess.hpp"#include <iostream>
#include "opencv2/opencv.hpp"
#endif
#include "mylog.h"
#define LITEMNN_DEBUG
namespace mnncore
{class  BasicMNNHandler{protected:std::shared_ptr<MNN::Interpreter> mnn_interpreter;MNN::Session *mnn_session = nullptr;MNN::Tensor *input_tensor = nullptr; // assume single input.MNN::ScheduleConfig schedule_config;std::shared_ptr<MNN::CV::ImageProcess> pretreat; // init at subclassconst char *log_id = nullptr;const char *mnn_path = nullptr;const char *mnn_model_data = nullptr;//int mnn_model_size = 0;protected:const int num_threads; // initialize at runtime.int input_batch;int input_channel;int input_height;int input_width;int dimension_type;int num_outputs = 1;protected:explicit BasicMNNHandler(const std::string &_mnn_path, int _num_threads = 1);int initialize_handler();std::string turnHeadDataToString(std::string headData);virtual ~BasicMNNHandler();// un-copyableprotected:BasicMNNHandler(const BasicMNNHandler &) = delete; //BasicMNNHandler(BasicMNNHandler &&) = delete; //BasicMNNHandler &operator=(const BasicMNNHandler &) = delete; //BasicMNNHandler &operator=(BasicMNNHandler &&) = delete; //protected:virtual void transform(const cv::Mat &mat) = 0; // ? needed ?private:void print_debug_string();};
}
#endif //MNN_CORE_MNN_HANDLER_H
// InferenceInit.cpp
#include "mnn/core/InferenceInit.h"
namespace mnncore
{
BasicMNNHandler::BasicMNNHandler(const std::string &_mnn_path, int _num_threads) :log_id(_mnn_path.data()), mnn_path(_mnn_path.data()),num_threads(_num_threads)
{//initialize_handler();
}int BasicMNNHandler::initialize_handler()
{std::cout<<"load  Model from file: " << mnn_path << "\n";mnn_interpreter = std::shared_ptr<MNN::Interpreter>(MNN::Interpreter::createFromFile(mnn_path));myLog(ERROR_, "mnn_interpreter createFromFile done!");if (nullptr == mnn_interpreter) {std::cout << "load centerface failed." << std::endl;return -1;}// 2. init schedule_configschedule_config.numThread = (int) num_threads;MNN::BackendConfig backend_config;backend_config.precision = MNN::BackendConfig::Precision_Low; // default Precision_Highbackend_config.memory = MNN::BackendConfig::Memory_Low;backend_config.power = MNN::BackendConfig::Power_Low;schedule_config.backendConfig = &backend_config;// 3. create sessionmyLog(ERROR_, "createSession...");mnn_session = mnn_interpreter->createSession(schedule_config);// 4. init input tensormyLog(ERROR_, "getSessionInput...");input_tensor = mnn_interpreter->getSessionInput(mnn_session, nullptr);// 5. init input dimsinput_batch = input_tensor->batch();input_channel = input_tensor->channel();input_height = input_tensor->height();input_width = input_tensor->width();dimension_type = input_tensor->getDimensionType();myLog(ERROR_, "input_batch: %d, input_channel: %d, input_height: %d, input_width: %d, dimension_type: %d", input_batch, input_channel, input_height, input_width, dimension_type);// 6. resize tensor & session needed ???if (dimension_type == MNN::Tensor::CAFFE){// NCHWmnn_interpreter->resizeTensor(input_tensor, {input_batch, input_channel, input_height, input_width});mnn_interpreter->resizeSession(mnn_session);} // NHWCelse if (dimension_type == MNN::Tensor::TENSORFLOW){mnn_interpreter->resizeTensor(input_tensor, {input_batch, input_height, input_width, input_channel});mnn_interpreter->resizeSession(mnn_session);} // NC4HW4else if (dimension_type == MNN::Tensor::CAFFE_C4){
#ifdef LITEMNN_DEBUGstd::cout << "Dimension Type is CAFFE_C4, skip resizeTensor & resizeSession!\n";
#endif}// output countnum_outputs = (int)mnn_interpreter->getSessionOutputAll(mnn_session).size();
#ifdef LITEMNN_DEBUGthis->print_debug_string();
#endifreturn 0;
}BasicMNNHandler::~BasicMNNHandler()
{mnn_interpreter->releaseModel();if (mnn_session)mnn_interpreter->releaseSession(mnn_session);
}
void BasicMNNHandler::print_debug_string()
{std::cout << "LITEMNN_DEBUG LogId: " << log_id << "\n";std::cout << "=============== Input-Dims ==============\n";if (input_tensor) input_tensor->printShape();if (dimension_type == MNN::Tensor::CAFFE)std::cout << "Dimension Type: (CAFFE/PyTorch/ONNX)NCHW" << "\n";else if (dimension_type == MNN::Tensor::TENSORFLOW)std::cout << "Dimension Type: (TENSORFLOW)NHWC" << "\n";else if (dimension_type == MNN::Tensor::CAFFE_C4)std::cout << "Dimension Type: (CAFFE_C4)NC4HW4" << "\n";std::cout << "=============== Output-Dims ==============\n";auto tmp_output_map = mnn_interpreter->getSessionOutputAll(mnn_session);std::cout << "getSessionOutputAll done!\n";for (auto it = tmp_output_map.cbegin(); it != tmp_output_map.cend(); ++it){std::cout << "Output: " << it->first << ": ";it->second->printShape();}std::cout << "========================================\n";
}
} // namespace mnncore

主要的推理处理代码:
头文件声明

//LiveSpoofDetector.h
#include "mnn/core/InferenceInit.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include<iterator>
#include <algorithm>#define RESIZE_LIVE_SPOOF_SIZE 112
using namespace mnncore;
namespace mnncv {class SqueezeNetLiveSpoof : public BasicMNNHandler{public:explicit SqueezeNetLiveSpoof(const std::string &model_path, int numThread = 1);~SqueezeNetLiveSpoof() override = default;// 保留原有函数int Init(const char* model_path);float detect_handler(const unsigned char* pData, int width, int height, int nchannel,  int mod);cv::Mat m_image;private:void initialize_pretreat();void transform(const cv::Mat &mat) override;std::vector<cv::Point2f> coord5points;const float meanVals_[3] = { 103.94f, 116.78f, 123.68f};const float normVals_[3] = {0.017f, 0.017f, 0.017f};};
}

函数定义:

// LiveSpoofDetector.cpp
#include "include/mnn/cv/RGB/LiveSpoofDetector.h"
#include <opencv2/opencv.hpp>using namespace mnncv;SqueezeNetLiveSpoof::SqueezeNetLiveSpoof(const std::string &model_path, int numThread) : BasicMNNHandler(model_path, numThread) {initialize_pretreat();
}int SqueezeNetLiveSpoof::Init(const char* model_path) {std::string model_path_str = model_path;int FileLoadFlag = initialize_handler(model_path_str, 0);if (FileLoadFlag >= 0 ){return 0;}return FileLoadFlag;
}
template<typename T> std::vector<float> softmax(const T *logits, unsigned int _size, unsigned int &max_id)
{//types::__assert_type<T>();if (_size == 0 || logits == nullptr) return{};float max_prob = 0.f, total_exp = 0.f;std::vector<float> softmax_probs(_size);for (unsigned int i = 0; i < _size; ++i){softmax_probs[i] = std::exp((float)logits[i]);total_exp += softmax_probs[i];}for (unsigned int i = 0; i < _size; ++i){softmax_probs[i] = softmax_probs[i] / total_exp;if (softmax_probs[i] > max_prob){max_id = i;max_prob = softmax_probs[i];}}return softmax_probs;
}
float SqueezeNetLiveSpoof::detect_handler(const unsigned char* pData, int width, int height, int nchannel, int mod)
{if (!pData || width <= 0 || height <= 0) return 0.0f;try {// 1. 将输入数据转换为OpenCV Matcv::Mat input_mat(height, width, nchannel == 3 ? CV_8UC3 : CV_8UC1, (void*)pData);if (nchannel == 1) {cv::cvtColor(input_mat, input_mat, cv::COLOR_GRAY2BGR);}// 2. 预处理图像this->transform(input_mat);// 3. 运行推理mnn_interpreter->runSession(mnn_session);// 4. 获取输出auto output_tensor = mnn_interpreter->getSessionOutput(mnn_session, nullptr);MNN::Tensor host_tensor(output_tensor, output_tensor->getDimensionType());output_tensor->copyToHostTensor(&host_tensor);auto embedding_dims = host_tensor.shape(); // (1,128)const unsigned int hidden_dim = embedding_dims.at(1);const float* embedding_values = host_tensor.host<float>();unsigned int pred_live = 0;auto softmax_probs = softmax<float>(embedding_values, hidden_dim, pred_live);//std::cout << "softmax_probs: " << softmax_probs[0]<<"  "<<softmax_probs[1] << std::endl;float live_score = softmax_probs[0]; // 取真脸概率作为活体分数std::cout << "live_score: " << live_score<< "   spoof_score:"<< softmax_probs[1]<< std::endl;return live_score;} catch (const std::exception& e) {std::cerr << "detect_handler exception: " << e.what() << std::endl;return 0.0f;}
}
void SqueezeNetLiveSpoof::initialize_pretreat() {// 初始化预处理参数MNN::CV::Matrix trans;trans.setScale(1.0f, 1.0f);MNN::CV::ImageProcess::Config img_config;img_config.filterType = MNN::CV::BICUBIC;::memcpy(img_config.mean, meanVals_, sizeof(meanVals_));::memcpy(img_config.normal, normVals_, sizeof(normVals_));img_config.sourceFormat = MNN::CV::BGR;img_config.destFormat = MNN::CV::RGB;pretreat = std::shared_ptr<MNN::CV::ImageProcess>(MNN::CV::ImageProcess::create(img_config));pretreat->setMatrix(trans);
}
void SqueezeNetLiveSpoof::transform(const cv::Mat &mat){cv::Mat mat_rs;cv::resize(mat, mat_rs, cv::Size(input_width, input_height));pretreat->convert(mat_rs.data, input_width, input_height, mat_rs.step[0], input_tensor);
}

四、结果展示

在返回的分类结果中,我们用0.8作为阈值对活体分数进行过滤,得到的结果如下:
判断为非活体的图片结果
在这里插入图片描述

五、留下来的问题

一个从数据整理到最后的MNN推理的2D活体检测的工作简单的完结了,这个系列的内容主要目的是讲诉一个模型如何从设计到部署的全过程,过程中的有些描述和个人理解并不一定正确,如果有其他理解或者错处指出,请严重指出。
深度学习之用CelebA_Spoof数据集搭建一个活体检测-数据处理
深度学习之用CelebA_Spoof数据集搭建一个活体检测-模型搭建和训练
深度学习之用CelebA_Spoof数据集搭建一个活体检测-模型验证与测试
深度学习之用CelebA_Spoof数据集搭建一个活体检测-一些模型训练中的改动带来的改善
那么这个系列完结,留下什么问题:
1 2D活体检测有没有更好的方法?
2 训练的过程如何更好更快的调参以及收敛,以及如何寻找更好的特征?
3 在实际使用过程中,怎样提高功能的体验感,至于那些判断错误的,该如何进行处理?
4 如何在不同环境下,保证活体的准确率?
这都是在这个工作中需要重视的,而且这项工作并不会因为有了部署成功就能成功,而是需要不断改善。如果有好的方法和建议,烦请留言告知,我们一起讨论!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/80004.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

JVM学习专题(一)类加载器与双亲委派

目录 1、JVM加载运行全过程梳理 2、JVM Hotspot底层 3、war包、jar包如何加载 4、类加载器 我们来查看一下getLauncher&#xff1a; 1.我们先查看getExtClassLoader() 2、再来看看getAppClassLoader(extcl) 5、双亲委派机制 1.职责明确&#xff0c;路径隔离​&#xff…

部署安装gitlab-ce-17.9.7-ce.0.el8.x86_64.rpm

目录 ​编辑 实验环境 所需软件 实验开始 安装部署gitlab171.配置清华源仓库&#xff08;版本高的系统无需做&#xff09;vim /etc/yum.repos.d/gitlab-ce.repo 2.提前下载包dnf localinstall gitlab-ce-17.9.7-ce.0.el8.x86_64.rpm --rocklinux 3.修改配…

使用LoRA微调Qwen2.5-VL-7B-Instruct完成电气主接线图识别

使用LoRA微调Qwen2.5-VL-7B-Instruct完成电气主接线图识别 动机 任务适配需求 Qwen2.5-VL在视觉理解方面表现优异&#xff0c;但电气主接线图识别需要特定领域的结构化输出能力&#xff08;如设备参数提取、拓扑关系解析&#xff09;。微调可增强模型对专业符号&#xff08;如…

系统集成项目管理工程师学习笔记

第九章 项目管理概论 1、项目基本要素 项目基础 项目是为创造独特的产品、服务或成果而进行的临时性工作。 项目具有临时性、独特性、渐进明细的特点。项目的“临时性”是指项目只有明确的起点和终点。“临时性”并一定意味着项目的持续时间短。 项目可宣告结束的情况&…

Secs/Gem第七讲(基于secs4net项目的ChatGpt介绍)

好的&#xff0c;那我们现在进入&#xff1a; 第七讲&#xff1a;掉电重连后&#xff0c;为什么设备不再上报事件&#xff1f;——持久化与自动恢复的系统设计 关键词&#xff1a;掉电恢复、状态重建、初始化流程、SecsMessage 缓存机制、自动重连、事件再注册 本讲目标 你将理…

室内定位:热门研究方向与未解难题深度解析

I. 引言:对普适性室内定位的持续探索 A. 室内定位在现代应用中的重要性 室内定位系统(IPS)正迅速成为众多应用领域的基石技术,其重要性源于现代社会人们约70%至90%的时间在室内度过的事实 1。这些应用横跨多个行业,包括应急响应 1、智能建筑与智慧城市 6、医疗健康(如病…

Android学习总结之Glide自定义三级缓存(实战篇)

一、为什么需要三级缓存 内存缓存&#xff08;Memory Cache&#xff09; 内存缓存旨在快速显示刚浏览过的图片&#xff0c;例如在滑动列表时来回切换的图片。在 Glide 中&#xff0c;内存缓存使用 LruCache 算法&#xff08;最近最少使用&#xff09;&#xff0c;能自动清理长…

Linux的文件查找与压缩

查找文件 find命令 # 命令&#xff1a;find 路径范围 选项1 选项1的值 \[选项2 选项2 的值…]# 作用&#xff1a;用于查找文档&#xff08;其选项有55 个之多&#xff09;# 选项&#xff1a;# -name&#xff1a;按照文档名称进行搜索&#xff08;支持模糊搜索&#xff0c;\* &…

python处理异常,JSON

异常处理 #异常处理 # 在连接MySQL数据库的过程中&#xff0c;如果不能有效地处理异常&#xff0c;则异常信息过于复杂&#xff0c;对用户不友好&#xff0c;暴露过多的敏感信息 # 所以&#xff0c;在真实的生产环境中&#xff0c; 程序必须有效地处理和控制异常&#xff0c;按…

线程的两种实现方式

线程的两种实现方式——内核支持线程&#xff08;kernal Supported Thread, KST&#xff09;&#xff0c; 用户级线程&#xff08;User Level Thread, ULT&#xff09; 1. 内核支持线程 顾名思义&#xff0c;内核支持线程即为在内核支持下的那些线程&#xff0c;它们的创建&am…

vue3基础学习(上) [简单标签] (vscode)

目录 1. Vue简介 2. 创建Vue应用 2.1 下载JS文件 2.2 引用JS文件 2.3 调用Vue方法​编辑 2.4 运行一下试试: 2.5 代码如下 3.模块化开发模式 3.1 Live Server插件 3.2 运行 4. 常用的标签 4.1 reactive 4.1.1 运行结果 4.1.2 代码: 4.2 ref 4.2.1 运行结果 4.2.2…

自定义分区器-基础

什么是分区 在 Spark 里&#xff0c;弹性分布式数据集&#xff08;RDD&#xff09;是核心的数据抽象&#xff0c;它是不可变的、可分区的、里面的元素并行计算的集合。 在 Spark 中&#xff0c;分区是指将数据集按照一定的规则划分成多个较小的子集&#xff0c;每个子集可以独立…

深入解析HTTP协议演进:从1.0到3.0的全面对比

HTTP协议作为互联网的基础协议&#xff0c;经历了多个版本的迭代演进。本文将详细解析HTTP 1.0、HTTP 1.1、HTTP/2和HTTP/3的核心特性与区别&#xff0c;帮助开发者深入理解网络协议的发展脉络。 一、HTTP 1.0&#xff1a;互联网的奠基者 核心特点&#xff1a; 短连接模式&am…

基于windows环境Oracle主备切换之后OGG同步进程恢复

基于windows环境Oracle主备切换之后OGG同步进程恢复 场景&#xff1a;db1是主库&#xff0c;db2是备库&#xff0c;ogg从db2备库抽取数据同步到目标数据库 db1 - db2(ADG) – ogg – targetdb 场景&#xff1a;db2是主库&#xff0c;db1是备库&#xff0c;ogg从db1备库抽取数…

微服务,服务粒度多少合适

项目服务化好处 复用性&#xff0c;消除代码拷贝专注性&#xff0c;防止复杂性扩散解耦合&#xff0c;消除公共库耦合高质量&#xff0c;SQL稳定性有保障易扩展&#xff0c;消除数据库解耦合高效率&#xff0c;调用方研发效率提升 微服务拆分实现策略 统一服务层一个子业务一…

【工奥阀门科技有限公司】签约智橙PLM

近日&#xff0c;工奥阀门科技有限公司正式签约了智橙泵阀行业版PLM。 忠于质量&#xff0c;臻于服务&#xff0c;精于研发 工奥阀门科技有限公司&#xff08;以下简称工奥阀门&#xff09;坐落于浙江永嘉&#xff0c;是一家集设计、开发、生产、销售、安装、服务为一体的阀门…

2025-5-15Vue3快速上手

1、setup和选项式API之间的关系 (1)vue2中的data,methods可以与vue3的setup共存 &#xff08;2&#xff09;vue2中的data可以用this读取setup中的数据&#xff0c;但是反过来不行&#xff0c;因为setup中的this是undefined &#xff08;3&#xff09;不建议vue2和vue3的语法混用…

基于智能推荐的就业平台的设计与实现(招聘系统)(SpringBoot Thymeleaf)+文档

&#x1f497;博主介绍&#x1f497;&#xff1a;✌在职Java研发工程师、专注于程序设计、源码分享、技术交流、专注于Java技术领域和毕业设计✌ 温馨提示&#xff1a;文末有 CSDN 平台官方提供的老师 Wechat / QQ 名片 :) Java精品实战案例《700套》 2025最新毕业设计选题推荐…

什么是路由器环回接口?

路由器环回接口&#xff08;LoopbackInterface&#xff09;是网络设备中的一种逻辑虚拟接口&#xff0c;不依赖物理硬件&#xff0c;但在网络配置和管理中具有重要作用。以下是其核心要点&#xff1a; 一、基本特性 1.虚拟性与稳定性 环回接口是纯软件实现的逻辑接口&#x…

HOT100 (滑动窗口子串普通数组矩阵)

先填坑 滑动窗口 3. 无重复字符的最长子串 给定一个字符串 s ,请你找出其中不含有重复字符的最长子串的长度。 思路:用一个uset容器存放当前滑动窗口中的元素 #include <bits/stdc++.h> using namespace std; class Solution {public:int lengthOfLongestSubstring(st…