caffe提取某层特征进行人脸识别源码

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yudiemiaomiao/article/details/78606291

在上一篇博文Classifier的c++类的基础上进行扩展,其中头文件Classifier.h如下:

#include <caffe/caffe.hpp>
#ifdef USE_OPENCV
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#endif  // USE_OPENCV
#include <algorithm>
#include <iosfwd>
#include <memory>
#include <string>
#include <utility>
#include <vector>

#ifdef USE_OPENCV
#ifdef USE_OPENCV
using namespace caffe;  // NOLINT(build/namespaces)
using std::string;
using caffe::Net;
using caffe::Blob;


//为std::pair<string, float>创建一个名为“Prediction”的类型别名
typedef std::pair<string, float> Prediction;
class Classifier {
public:
    // Classifier构造函数的声明,输入形参分别为配置文件(train_val.prototxt)、训练好的模型文件(caffemodel)、均值文件和labels_标签文件
    Classifier(const string& model_file, const string& trained_file, const string& mean_file, const string& label_file);

    // Classify函数对输入的图像进行分类,返回std::pair<string, float>类型的预测结果
    // Classify函数的形参列表:img是输入一张图像,N是输出概率值从按降序排列的前N个值。
    std::vector<Prediction> Classify(const cv::Mat& img, int N = 5);
    //提取图像特征,face为输入图像,feature为输出的特征 add
    int  ExtractFeature(cv::Mat &face,unsigned char *feature);
    //计算特征相似度 add
    int  GetFaceFeatureSimility(unsigned char *feature1,unsigned char *feature2,int len,float *simility);
    //获取特征维度 add
    int  GetFeatureSize(int *feature_length);


private:
    //根据Feature层的名字获取其在网络中的Index
    int  GetBlobIndex(char *query_blob_name);

    // SetMean函数将均值文件读入,转化为一张均值图像mean_,形参是均值文件的文件名
    void SetMean(const string& mean_file);

    // Predict函数调用Process函数将图像输入到网络中,使用net_->Forward()函数进行预测;
    // 将输出层的输出保存到vector容器中返回,输入形参是单张图片
    std::vector<float> Predict(const cv::Mat& img);

    void WrapInputLayer(std::vector<cv::Mat>* input_channels);

    // Preprocess函数对图像的通道数、大小、数据形式进行改变,减去均值mean_,再写入到net_的输入层中
    void Preprocess(const cv::Mat& img, std::vector<cv::Mat>* input_channels);

    // Classifier类的私有变量
private:
    shared_ptr<Net<float> > net_;   // 网络为数据为float类型,那么Blob和一切有关的输入的外部数据都为float类型
    cv::Size input_geometry_;   // 输入层图像的大小
    int num_channels_;      // 输入层的通道数
    cv::Mat mean_;          // 均值文件处理得到的均值图像
    std::vector<string> labels_;    // 标签文件,labels_定义成元素是string类型的vector容器
};

c++文件为:

#include "stdafx.h"
#include "Classifier.h"
#define  FEATURE_LAYER_NAME  "fc1" 
using caffe::Caffe;
using caffe::Phase;
using caffe::TEST;
using caffe::BlobProto;
static  Phase phase=TEST;
static  Caffe::Brew mode=Caffe::CPU;
static  char *blob_name=FEATURE_LAYER_NAME;

static  std::string root_dir="/path/";


//在Classifier类外定义Classifier类的构造函数
Classifier::Classifier(const string& model_file,
    const string& trained_file,
    const string& mean_file,
    const string& label_file) 
{
#ifdef CPU_ONLY
    Caffe::set_mode(Caffe::CPU); // CPU模式
#else
    Caffe::set_mode(Caffe::GPU); // GPU模式
#endif

    /* Load the network. */
    net_.reset(new Net<float>(model_file, TEST));   // 加载配置文件,设定模式为TEST测试
    net_->CopyTrainedLayersFrom(trained_file);  // 加载caffemodel,该函数在net.cpp中实现

    // 要求输入输出都是1(指的是Blob个数)
    CHECK_EQ(net_->num_inputs(), 1) << "Network should have exactly one input.";
    CHECK_EQ(net_->num_outputs(), 1) << "Network should have exactly one output.";

    Blob<float>* input_layer = net_->input_blobs()[0];  // 定义输入层变量
    num_channels_ = input_layer->channels();        // 得到输入层的通道数
    CHECK(num_channels_ == 3 || num_channels_ == 1)     // 检查图像通道数,3对应RGB图像,1对应灰度图像
        << "Input layer should have 1 or 3 channels.";
    input_geometry_ = cv::Size(input_layer->width(), input_layer->height());//得到输入层图像大小

    // Classifier函数中调用SetMean函数,读取binaryproto均值文件,得到均值图像mean_
    SetMean(mean_file);

    std::ifstream labels(label_file.c_str());//从本地txt文本加载标签名称(行表示)

    CHECK(labels) << "Unable to open labels file " << label_file;
    string line;
    while (std::getline(labels, line))
        labels_.push_back(string(line));

    // 输出层只有一个Blob,因此用[0]; 另外,输出层的shape为(1, 10) 
    // mnist有10类,这里的output_layer->channels()就是 shape(1) = 10
    Blob<float>* output_layer = net_->output_blobs()[0];        
    CHECK_EQ(labels_.size(), output_layer->channels())      // 判断标签和输出size是否相同
        << "Number of labels is different from the output layer dimension.";
}


// partial_sort 排序用到的自定义比较函数 => 前者比后者大就返回true
static bool PairCompare(const std::pair<float, int>& lhs,
    const std::pair<float, int>& rhs) {
    return lhs.first > rhs.first;
}

// 函数用于返回向量v的前N个最大值的索引,也就是返回概率最大的五个类别的标签  
// 如果你是二分类问题,那么这个N直接选择1  (N要小于等于类别数)
static std::vector<int> Argmax(const std::vector<float>& v, int N) 
{
    std::vector<std::pair<float, int> > pairs;

    for (size_t i = 0; i < v.size(); ++i)
        pairs.push_back(std::make_pair(v[i], static_cast<int>(i)));

    std::partial_sort(pairs.begin(), pairs.begin() + N, pairs.end(), PairCompare);

    std::vector<int> result;
    for (int i = 0; i < N; ++i)
        result.push_back(pairs[i].second);

    return result;
}

// Classifier类的Classify函数的定义,里面调用了Classifier类的私有函数Predict函数和上面实现的Argmax函数
// 预测函数,输入一张图片img,希望预测的前N种概率最大的,我们一般取N等于1  
// 输入预测结果为std::make_pair,每个对包含这个物体的名字,及其相对于的概率 
std::vector<Prediction> Classifier::Classify(const cv::Mat& img, int N) 
{
    // 调用Predict函数对输入图像进行预测,输出是概率值
    std::vector<float> output = Predict(img);   
    N = std::min<int>(labels_.size(), N);   
    // 调用上面的Argmax函数返回概率值最大的N个类别的标签,放在vector容器maxN里
    std::vector<int> maxN = Argmax(output, N);  
    // 定义一个std::pair<string, float>型的变量,用来存放类别的标签及类别对应的概率值
    std::vector<Prediction> predictions;    
    for (int i = 0; i < N; ++i) {
        int idx = maxN[i];
        predictions.push_back(std::make_pair(labels_[idx], output[idx]));
    }
    return predictions;
}


// 加载均值文件函数的定义
void Classifier::SetMean(const string& mean_file) {

    BlobProto blob_proto;   //构造一个BlobProto对象blob_proto
    ReadProtoFromBinaryFileOrDie(mean_file.c_str(), &blob_proto);   // 读取均值文件给构建好的blob_proto

    // 把BlobProto 转换为 Blob<float>类型
    Blob<float> mean_blob;
    mean_blob.FromProto(blob_proto);// 把blob_proto拷贝给mean_blob

    // 验证均值图片的通道个数是否与网络的输入图片的通道个数相同  
    CHECK_EQ(mean_blob.channels(), num_channels_)
        << "Number of channels of mean file doesn't match input layer.";

    // 把三通道的图片分开存储,三张图片BGR按顺序保存到channels中 (对于mnist,只有一个通道;这里给出的是通用的方法)
    std::vector<cv::Mat> channels;
    float* data = mean_blob.mutable_cpu_data();//令data指向mean_blob
    for (int i = 0; i < num_channels_; ++i) 
    {
        cv::Mat channel(mean_blob.height(), mean_blob.width(), CV_32FC1, data);
        channels.push_back(channel);
        data += mean_blob.height() * mean_blob.width();
    }

    // 重新合成一张图片
    cv::Mat mean;
    cv::merge(channels, mean);

    // 计算每个通道的均值,得到一个三维的向量channel_mean,然后把三维的向量扩展成一张新的均值图片  
    // 这种图片的每个通道的像素值是相等的,这张均值图片的大小将和网络的输入要求一样 
    // 注意: 这里的去均值,是指对需要处理的图像减去均值图像的平均亮度 
    cv::Scalar channel_mean = cv::mean(mean);
    mean_ = cv::Mat(input_geometry_, mean.type(), channel_mean);
}

//Classifier类中Predict函数的定义,输入形参为单张图像
std::vector<float> Classifier::Predict(const cv::Mat& img) {

    Blob<float>* input_layer = net_->input_blobs()[0];

    // 这一步可以不需要,因为加载的网络中已经包含中这个结构(只是为了避免出错)
    input_layer->Reshape(1, num_channels_,input_geometry_.height, input_geometry_.width);

    // 输入带预测的图片数据,然后进行预处理,包括归一化、缩放等操作  
    net_->Reshape();

    std::vector<cv::Mat> input_channels; // 输入图像,按通道保存在vector中

    // 将cv::Mat类型图像数据的size、channel等和网路输入层的Blobg关联起来。
    WrapInputLayer(&input_channels);

    // 调用Classifier类中的Preprocess函数对图像的通道数、大小、数据形式进行改变,减去均值mean_,再写入到net_的输入层中
    Preprocess(img, &input_channels); 

    // 前向传导
    net_->Forward();

#if 1
    // 把最后一层输出值,保存到vector中,结果就是返回每个类的概率  
    Blob<float>* output_layer = net_->output_blobs()[0];   // softmax 输出
    const float* begin = output_layer->cpu_data();
    const float* end = begin + output_layer->channels();
    return std::vector<float>(begin, end);
#else
    // 取全连接层的输出,自己实现softmax  g(i)= exp(i)/sum(exp(·))
    // ip2的bolb,shape为 (1,10),即只有前2维,  number=1,channnel=10
    //   用ip2->shape(2)和ip2->shape(3)获取height和width会报错(shape是vector,越界)
    //   用ip2->height()和ip2->width(),虽然越界,但是会返回1。

    boost::shared_ptr<Blob<float>> ip2 = net_->blob_by_name("ip2"); // InnerProduct 输出
    const float* begin = ip2->cpu_data();
    const float* end = begin + /*ip2->channels()*/ip2->shape(1);  // 只有2维  shape 1*10
    std::vector<float> ip2_Out = std::vector<float>(begin, end);//  channels() 即 shape(1), 是 N*C*W*H 的C, 这里尽管没有W和H,

    float sum = 0;
    for (auto ex1 : ip2_Out)
        sum += std::exp(ex1);

    std::for_each(ip2_Out.begin(), ip2_Out.end(), [&](float i)  {
        std::cout << "exp(" << i << ") = "; i = std::exp(i) / sum; std::cout << i << std::endl;
    });
    return ip2_Out;
#endif
}


// 这个其实是为了获得net_网络的输入层数据的指针,然后后面我们直接把输入图片数据拷贝到这个指针里面
void Classifier::WrapInputLayer(std::vector<cv::Mat>* input_channels) 
{
    Blob<float>* input_layer = net_->input_blobs()[0];

    int width = input_layer->width();
    int height = input_layer->height();
    float* input_data = input_layer->mutable_cpu_data();
    for (int i = 0; i < input_layer->channels(); ++i) 
    {
        cv::Mat channel(height, width, CV_32FC1, input_data);
        input_channels->push_back(channel);
        input_data += width * height;
    }
}

// 图片预处理函数,包括图片缩放、归一化、3通道图片分开存储  
// 对于三通道输入CNN,经过该函数返回的是std::vector<cv::Mat>因为是三通道数据,所以用了vector  
void Classifier::Preprocess(const cv::Mat& img, std::vector<cv::Mat>* input_channels)
{
    // 输入图片通道转换
    cv::Mat sample;
    if (img.channels() == 3 && num_channels_ == 1)      cv::cvtColor(img, sample, cv::COLOR_BGR2GRAY);
    else if (img.channels() == 4 && num_channels_ == 1) cv::cvtColor(img, sample, cv::COLOR_BGRA2GRAY);
    else if (img.channels() == 4 && num_channels_ == 3) cv::cvtColor(img, sample, cv::COLOR_BGRA2BGR);
    else if (img.channels() == 1 && num_channels_ == 3) cv::cvtColor(img, sample, cv::COLOR_GRAY2BGR);
    else
        sample = img;

    // 输入图片缩放处理
    cv::Mat sample_resized;
    if (sample.size() != input_geometry_)
        cv::resize(sample, sample_resized, input_geometry_);
    else
        sample_resized = sample;

    cv::Mat sample_float;        // 定义sample_float为未减均值时的图像
    if (num_channels_ == 3) sample_resized.convertTo(sample_float, CV_32FC3);
    else            sample_resized.convertTo(sample_float, CV_32FC1);

    cv::Mat sample_normalized;   //定义sample_normalized为减去均值后的图像

    // 调用opencv里的cv::subtract函数,将sample_float减去均值图像mean_得到减去均值后的图像
    cv::subtract(sample_float, mean_, sample_normalized);  // 可用 sample_normalized = sample_float - mean_

    // 为了通用,按通道存放在vector中
    cv::split(sample_normalized, *input_channels);

    CHECK(reinterpret_cast<float*>(input_channels->at(0).data) == net_->input_blobs()[0]->cpu_data())
        << "Input channels are not wrapping the input layer of the network.";
}

int Classifier::GetBlobIndex(char *query_blob_name)  
{  
    std::string str_query(query_blob_name); 
    int index=-10000;     
    std::vector<std::string> const & blob_names = net->blob_names();  
    for( unsigned int i = 0; i != blob_names.size(); ++i )   
    {   
        if( str_query == blob_names[i] )   
        {   
            index=i; 
        }   
    }  
    if(index==-10000)
    {
        printf("In the function Recognition::get_blob_index(),can not find the blob index of blob name=%s\n",query_blob_name);   
    }
    return index; 
}  

int Classifier::GetFeatureSize(int *feature_size)
{
    if(feature_size==NULL)
    {
         printf("In the func Recognition::GetFeatureSize(),the input param feature_size  is err!\n");
         return 0;
    }
    int index=-10000;
    index=GetBlobIndex(blob_name);
    if(index==-10000)
    {  
        printf("In the function  Recognition::ExtractFeature,get the blob index of blob name fail,extract face feature failed\n");
        return 0;
    }
    else
    {
        boost::shared_ptr<Blob<float> > blob = (net->blobs())[index];
        unsigned int num_data = blob->count();
        *feature_size=num_data*sizeof(float); //float类型转换
    } 
    return 1;
}

int Classifier::ExtractFeature(cv::Mat &face,unsigned char  *feature)
{  
    int img_channel=face.channels();
    if(feature==NULL)
    {
        printf("In the func Recognition::ExtraceFeature(),the input param feature_size or fature is err!\n");
        return 0;
    }    
    std::vector<cv::Mat> input_channels;
    WrapInputLayer(&input_channels);
    Preprocess(face, &input_channels);
    net->Forward();
    int index=-10000;
    index=GetBlobIndex(blob_name);
    if(index==-10000)
    {  
        printf("In the function  Recognition::ExtractFeature,get the blob index of blob name fail,extract face feature failed\n");
        return 0;
    }
    else
    {
        boost::shared_ptr<Blob<float> > blob = (net->blobs())[index];
        unsigned int num_data = blob->count();
        float *blob_data=(float *)(blob->cpu_data());
        memcpy(feature,blob_data,sizeof(float)*num_data);//数据格式转换
    } 
    return 1;
}

int Classifier::GetFaceFeatureSimility(unsigned char  *feature1,unsigned char  *feature2,int len,float *simility)
{
    if(feature1==NULL||feature2==NULL) 
    {    
         printf("In the func Classifier::GetFaceFeatureSimility(),the input param feature1 or feature2 is err!\n");
         return 0;
    }
    float sumarrayA=0,sumarrayB=0;
    float cosine=0;
    float *temp_feature1=(float *)feature1;
    float *temp_feature2=(float *)feature2;
    int temp_len=len/(sizeof(float));
    for(int i=0;i<temp_len;i++){
        sumarrayA+=temp_feature1[i]*temp_feature1[i];
        sumarrayB+=temp_feature2[i]*temp_feature2[i];
        cosine+=temp_feature1[i]*temp_feature2[i];
    }
    sumarrayA=sqrt(sumarrayA);
    sumarrayB=sqrt(sumarrayB);
    if((sumarrayA-0<0.0001)||(sumarrayB-0<0.0001))
    {
        printf("In the func Recognition::GetFaceFeatureSimility(),the value of the input param feature1 or feature2 is 0!\n");
        return 0;
    }
    //std::cout<<cosine<<std::endl;
    //std::cout<<sumarrayA<<std::endl;
    //std::cout<<sumarrayB<<std::endl;
    cosine/=(sumarrayA*sumarrayB);
    *simility=cosine*1000;
    //std::cout<<*simility<<std::endl;
    return 1;
}



Classifier::~Classifier()
{
}

调用

int main(int argc, char** argv) 
{   
    // 使用时检查输入的参数向量是否为要求的6个,如果不是,打印使用说明
    // 这里可以根据个人需要更改,是否需要均值文件等...
    static  std::string model_file = root_dir+"CNN.prototxt";
    static  std::string trained_file = root_dir+"CNN.caffemodel";
    static  std::string mean_file =root_dir+"train_data_mean.binaryproto";
    static  std::string label_file="";

    // 创建对象并初始化网络、模型、均值、标签各类对象
    Classifier classifier(model_file, trained_file, mean_file, label_file);

    char *path1="1.jpg";
    cv::Mat img1;
    cv::Mat img1 = cv::imread(path1, 0);
    int face_feature_len=0;
    int ret=0;
    ret=classifier.GetFeatureSize(&face_feature_len)
    unsigned char  *feat1=new unsigned char[face_feature_len];
    memset(feat1,0,face_feature_len);
    int ret1=0;
    ret1=classifier.ExtractFeature(img1,feat1);

    char *path2="2.jpg";
    cv::Mat img2;
    img2=cv::imread(path2,0);
    unsigned char  *feat1=new unsigned char[face_feature_len];
    memset(feat1,0,face_feature_len);
    int ret2=0;
    ret2=classifier.ExtractFeature(img2,feat2);
    float score=0;
    int ret3= classifier.GetFaceFeatureSimility(feat1,feat2,len,&score);
}

猜你喜欢

转载自blog.csdn.net/yudiemiaomiao/article/details/78606291