美文网首页
caffe textboxes++测试(c++版本)-boxDe

caffe textboxes++测试(c++版本)-boxDe

作者: 疯人愿的疯言疯语 | 来源:发表于2018-12-18 14:54 被阅读0次

    这里是c++测试版本的boxDetect.cpp,来源应该是SSD

    // This is a demo code for using a SSD model to do detection.
    // The code is modified from examples/cpp_classification/classification.cpp.
    // Usage:
    //    ssd_detect [FLAGS] model_file weights_file list_file
    //
    // where model_file is the .prototxt file defining the network architecture, and
    // weights_file is the .caffemodel file containing the network parameters, and
    // list_file contains a list of image files with the format as follows:
    //    folder/img1.JPEG
    //    folder/img2.JPEG
    // list_file can also contain a list of video files with the format as follows:
    //    folder/video1.mp4
    //    folder/video2.mp4
    //
    #include <stdio.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 <iomanip>
    #include <iosfwd>
    #include <memory>
    #include <string>
    #include <utility>
    #include <vector>
    #include "caffe/boxDetect.h"
    
    #ifdef USE_OPENCV
    using namespace caffe;  // NOLINT(build/namespaces)
    using namespace std;
    Detector::Detector(const string& model_file,
      const string& weights_file,
      const string& mean_file,
      const string& mean_value) {
    #ifdef CPU_ONLY
      Caffe::set_mode(Caffe::CPU);
    #else
      Caffe::set_mode(Caffe::GPU);
    #endif
    
      /* Load the network. */
      net_.reset(new Net<float>(model_file, TEST));//重新构建网络,调用Net的构造方法
      net_->CopyTrainedLayersFrom(weights_file);//载入模型参数
    
      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)
      << "Input layer should have 1 or 3 channels.";
      //输入图像的尺寸
      input_geometry_.push_back(cv::Size(768, 768));
    
      /* Load the binaryproto mean file. */
      SetMean(mean_file, mean_value);
    }
    
    std::vector<vector<float> > Detector::Detect(const cv::Mat& img) {
    
      vector<vector<float> > detections;
    
      for(int i=0;i< input_geometry_.size();i++)
      {
        int img_height = input_geometry_[i].height;
        int img_width =  input_geometry_[i].width;
        Blob<float>* input_layer = net_->input_blobs()[0];
        input_layer->Reshape(1, num_channels_,
          img_height, img_width);
        /* Forward dimension change to all layers. */
        net_->Reshape();
    
        std::vector<cv::Mat> input_channels;
        WrapInputLayer(&input_channels, i);
    
        Preprocess(img, &input_channels, i);
    
        net_->Forward();
    
        /* Copy the output layer to a std::vector */
        Blob<float>* result_blob = net_->output_blobs()[0];
        const float* result = result_blob->cpu_data();
        //const int num_det = result_blob->height();
        // vector<vector<float> > detections;
        
        int j=0;
        //get datas for textboxes++
        while(true)
        {
          if(result[j]==0&&result[j+1]==0&&result[j+2]==0)
          {
            break;
          }
          vector<float> detection;
          detection.push_back(result[j+2]);
          detection.push_back(result[j+7]);
          detection.push_back(result[j+8]);
          detection.push_back(result[j+9]);
          detection.push_back(result[j+10]);
          detection.push_back(result[j+11]);
          detection.push_back(result[j+12]);
          detection.push_back(result[j+13]);
          detection.push_back(result[j+14]);
          detections.push_back(detection);
          j=j+15;
        }
      }
      return detections;
    }
    
    /* Load the mean file in binaryproto format. */
    void Detector::SetMean(const string& mean_file, const string& mean_value) {
      // cv::Scalar channel_mean;
      // if (!mean_file.empty()) {
      //   CHECK(mean_value.empty()) <<
      //     "Cannot specify mean_file and mean_value at the same time";
      //   BlobProto blob_proto;
      //   ReadProtoFromBinaryFileOrDie(mean_file.c_str(), &blob_proto);
    
      //   /* Convert from BlobProto to Blob<float> */
      //   Blob<float> mean_blob;
      //   mean_blob.FromProto(blob_proto);
      //   CHECK_EQ(mean_blob.channels(), num_channels_)
      //     << "Number of channels of mean file doesn't match input layer.";
    
      //   /* The format of the mean file is planar 32-bit float BGR or grayscale. */
      //   std::vector<cv::Mat> channels;
      //   float* data = mean_blob.mutable_cpu_data();
      //   for (int i = 0; i < num_channels_; ++i) {
      //     /* Extract an individual channel. */
      //     cv::Mat channel(mean_blob.height(), mean_blob.width(), CV_32FC1, data);
      //     channels.push_back(channel);
      //     data += mean_blob.height() * mean_blob.width();
      //   }
    
      //   /* Merge the separate channels into a single image. */
      //   cv::Mat mean;
      //   cv::merge(channels, mean);
    
      //   /* Compute the global mean pixel value and create a mean image
      //    * filled with this value. */
      //   channel_mean = cv::mean(mean);
      //   mean_ = cv::Mat(input_geometry_, mean.type(), channel_mean);
      // }
      for (int m = 0; m < input_geometry_.size(); ++m)
      {
        if (!mean_value.empty()) {
          CHECK(mean_file.empty()) <<
          "Cannot specify mean_file and mean_value at the same time";
          stringstream ss(mean_value);
          vector<float> values;
          string item;
          while (getline(ss, item, ',')) {
            float value = std::atof(item.c_str());
            values.push_back(value);
          }
          CHECK(values.size() == 1 || values.size() == num_channels_) <<
          "Specify either 1 mean_value or as many as channels: " << num_channels_;
    
          std::vector<cv::Mat> channels;
          cv::Mat mean;
          for (int i = 0; i < num_channels_; ++i) {
              /* Extract an individual channel. */
            cv::Mat channel(input_geometry_[m].height, input_geometry_[m].width, CV_32FC1,
              cv::Scalar(values[i]));
            channels.push_back(channel);
          }
          cv::merge(channels, mean);
          mean_.push_back(mean);
        }
      }
    
    }
    
    /* Wrap the input layer of the network in separate cv::Mat objects
     * (one per channel). This way we save one memcpy operation and we
     * don't need to rely on cudaMemcpy2D. The last preprocessing
     * operation will write the separate channels directly to the input
     * layer. */
    
    /* 这个其实是为了获得net_网络的输入层数据的指针,然后后面我们直接把输入图片数据拷贝到这个指针里面*/
    void Detector::WrapInputLayer(std::vector<cv::Mat>* input_channels, int n) {
      Blob<float>* input_layer = net_->input_blobs()[0];
    
      int width = input_geometry_[n].width;
      int height = input_geometry_[n].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 Detector::Preprocess(const cv::Mat& img,
      std::vector<cv::Mat>* input_channels, int n) {
      /* Convert the input image to the input image format of the network. */
      cv::Mat sample;
      //如果输入图片是一张彩色图片,但是CNN的输入是一张灰度图像,那么我们需要把彩色图片转换成灰度图片
      
      //如果输入图片是灰度图片,或者是4通道图片,而CNN的输入要求是彩色图片,因此我们也需要把它转化成三通道彩色图片
      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;
    
      /*2、缩放处理,因为我们输入的一张图片如果是任意大小的图片,那么我们就应该把它缩放到227×227*/
      cv::Mat sample_resized;
      if (sample.size() != input_geometry_[n])
        cv::resize(sample, sample_resized, input_geometry_[n]);
      else
        sample_resized = sample;
      
      /*3、数据类型处理,因为我们的图片是uchar类型,我们需要把数据转换成float类型*/
      cv::Mat 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;
      cv::subtract(sample_float, mean_[n], sample_normalized);
    
      /* This operation will write the separate BGR planes directly to the
       * input layer of the network because it is wrapped by the cv::Mat
       * objects in input_channels. */
      /* 3通道数据分开存储 */
      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.";
    }
    
    DEFINE_string(mean_file, "",
      "The mean file used to subtract from the input image.");
    DEFINE_string(mean_value, "104,117,123",
      "If specified, can be one value or can be same as image channels"
      " - would subtract from the corresponding channel). Separated by ','."
      "Either mean_file or mean_value should be provided, not both.");
    DEFINE_string(file_type, "image",
      "The file type in the list_file. Currently support image and video.");
    DEFINE_string(out_file, "",
      "If provided, store the detection results in the out_file.");
    DEFINE_double(confidence_threshold, 0.01,
      "Only store detections with score higher than the threshold.");
    
    #endif  // USE_OPENCV
    
    

    相关文章

      网友评论

          本文标题:caffe textboxes++测试(c++版本)-boxDe

          本文链接:https://www.haomeiwen.com/subject/pehlkqtx.html