SSD模型的C++API调用例程

SSD目标检测实战
本文介绍如何使用SSD模型进行图片和视频的目标检测,通过修改SSD自带的C++例程,实现对输入图片或视频中物体的识别与定位。

本文就针对SSD自带的c++例程进行修改。可以对图片或者视频进行测试,具体代码如下所示:
源程序ssd_detect_log.cpp

// 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 <caffe/caffe.hpp>
//#ifdef USE_OPENCV
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv/cv.h>
#include <opencv/cxcore.h>
#include <opencv2/core/types_c.h>
//#endif  // USE_OPENCV
#include <algorithm>
#include <iomanip>
#include <iosfwd>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include <iostream>
#include <fstream>
#include <log4cxx/logger.h>
#include <log4cxx/logstring.h>
#include <log4cxx/propertyconfigurator.h>
#include <time.h>


//#ifdef USE_OPENCV
using namespace caffe;  // NOLINT(build/namespaces)
using namespace log4cxx ;
class Detector {
 public:
  Detector(const string& model_file,
           const string& weights_file,
           const string& mean_file,
           const string& mean_value);

  std::vector<vector<float> > Detect(const cv::Mat& img);

 private:
  void SetMean(const string& mean_file, const string& mean_value);

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

  void Preprocess(const cv::Mat& img,
                  std::vector<cv::Mat>* input_channels);

 private:
  shared_ptr<Net<float> > net_;
  cv::Size input_geometry_;
  int num_channels_;
  cv::Mat mean_;
};

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_->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_ = cv::Size(input_layer->width(), input_layer->height());

  /* Load the binaryproto mean file. */
  SetMean(mean_file, mean_value);
}

std::vector<vector<float> > Detector::Detect(const cv::Mat& img) {
  Blob<float>* input_layer = net_->input_blobs()[0];
  input_layer->Reshape(1, num_channels_,
                       input_geometry_.height, input_geometry_.width);
  /* Forward dimension change to all layers. */
  net_->Reshape();

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

  Preprocess(img, &input_channels);

  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;
  for (int k = 0; k < num_det; ++k) {
    if (result[0] == -1) {
      // Skip invalid detection.
      result += 7;
      continue;
    }
    vector<float> detection(result, result + 7);
    detections.push_back(detection);
    result += 7;
  }
  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);
  }
  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;
    for (int i = 0; i < num_channels_; ++i) {
      /* Extract an individual channel. */
      cv::Mat channel(input_geometry_.height, input_geometry_.width, CV_32FC1,
          cv::Scalar(values[i]));
      channels.push_back(channel);
    }
    cv::merge(channels, 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. */
void Detector::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;
  }
}

void Detector::Preprocess(const cv::Mat& img,
                            std::vector<cv::Mat>* input_channels) {
  /* Convert the input image to the input image format of the network. */
  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;
  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_, 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. */
  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, "video",
    "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.5,
    "Only store detections with score higher than the threshold.");

/*
name:void show_detect_result(IplImage *_img, std::vector<vector<float> > & _detect_result,float confidence_threshold )
function:to draw the detected result on the original picture 
input_parameter:
                _mat:the point for original picture 
                _detect_result:the cite for detection result
output_parameter:
                 None
author:wenqiang zhou
*/
void show_detect_result(IplImage *_img , std::vector<vector<float> > & _detect_result,float confidence_threshold )
{
      if(_img==NULL)
      return ;

      CvFont font;  
      cvInitFont(&font, CV_FONT_HERSHEY_COMPLEX, 0.5, 0.5, 0, 1, 2);  
	

      for (int i = 0; i < _detect_result.size(); ++i) {
        const vector<float>& d = _detect_result[i];
        // Detection format: [image_id, label, score, xmin, ymin, xmax, ymax].
        CHECK_EQ(d.size(), 7);
  	
	const int  label = d[1] ;
        const float score = d[2];
	if (score >= confidence_threshold) {
		cv::Point Pmin(static_cast<int>(d[3] * _img->width),static_cast<int>(d[4] * _img->height));
		cv::Point Pmax(static_cast<int>(d[5] * _img->width),static_cast<int>(d[6] * _img->height));
		cvRectangle(_img,Pmin,Pmax,cv::Scalar(0,0,255),1);
		char label_score[20];
		sprintf(label_score,"%d-%f",label,score);
   		cvPutText(_img,label_score, cv::Point(static_cast<int>(d[3] * _img->width),static_cast<int>(d[4] * _img->width)), &font, CV_RGB(255,0,0));  
	}
      }
}



int main(int argc, char** argv) {
//configure the glog 
  PropertyConfigurator::configure("conf.log");

//create two log for project
  LoggerPtr logger_output = Logger::getLogger("out_put");
  LOG4CXX_TRACE(logger_output,"TRACE");
  LOG4CXX_WARN(logger_output,"WARNING");
  LOG4CXX_DEBUG(logger_output,"DEBUG");
  LOG4CXX_ASSERT(logger_output,false , "ASSERT");
  LOG4CXX_FATAL(logger_output,"FATAL");


  ::google::InitGoogleLogging(argv[0]);
  // Print output to stderr (while still logging)
  FLAGS_alsologtostderr = 1;

#ifndef GFLAGS_GFLAGS_H_
  namespace gflags = google;
#endif

  gflags::SetUsageMessage("Do detection using SSD mode.\n"
        "Usage:\n"
        "    ssd_detect [FLAGS] model_file weights_file list_file\n");
  gflags::ParseCommandLineFlags(&argc, &argv, true);
/*
  if (argc < 4) {
    gflags::ShowUsageWithFlagsRestrict(argv[0], "examples/ssd/ssd_detect");
    return 1;
  }
*/
  const string& model_file ="/usr/local/neumoai/caffe_ssd/jobs/VGGNet_for_car/voc_car/SSD_512x512/deploy.prototxt"; //argv[1];
  const string& weights_file ="/usr/local/neumoai/caffe_ssd/models/VGGNet_for_car/voc_car/SSD_512x512/VGG_VOC0712_SSD_512x512_iter_32000.caffemodel" ;//argv[2];
  const string& mean_file = FLAGS_mean_file;
  const string& mean_value = FLAGS_mean_value;
  const string& file_type = FLAGS_file_type;
  const string& out_file = FLAGS_out_file;
  const float confidence_threshold = FLAGS_confidence_threshold;

  // Initialize the network.
  Detector detector(model_file, weights_file, mean_file, mean_value);

  // Set the output mode.
  std::streambuf* buf = std::cout.rdbuf();
  std::ofstream outfile;
  if (!out_file.empty()) {
    outfile.open(out_file.c_str());
    if (outfile.good()) {
      buf = outfile.rdbuf();
    }
  }
  std::ostream out(buf);
  const string &type_indicate = argv[2] ;

  // Process image one by one.
 // std::string pic_dir = "/home/wq/WorkShop/car_detector/000057.jpeg" ; 
 // std::ifstream  infile(argv[1]);
  std::string file="i am here";
 // infile >> file ;
 // printf("-----%s",file.c_str());
 // while (infile >> file) {
 //   out << file.c_str();
    if (!type_indicate.compare("image")) {
      cv::Mat img = cv::imread(argv[1]);
      CHECK(!img.empty()) << "Unable to decode image ";// << file;
      std::vector<vector<float> > detections = detector.Detect(img);

      /* Print the detection results. */
      for (int i = 0; i < detections.size(); ++i) {
        const vector<float>& d = detections[i];
        // Detection format: [image_id, label, score, xmin, ymin, xmax, ymax].
        CHECK_EQ(d.size(), 7);
        const float score = d[2];
        if (score >= confidence_threshold) {
          out << file << " ";
          out << static_cast<int>(d[1]) << " ";
          out << score << " ";
          out << static_cast<int>(d[3] * img.cols) << " ";
          out << static_cast<int>(d[4] * img.rows) << " ";
          out << static_cast<int>(d[5] * img.cols) << " ";
          out << static_cast<int>(d[6] * img.rows) << std::endl;
        }
      }
      IplImage _tmp = IplImage(img); 
/**************************************************/
//add by wq,show the rectangles of detection result
	show_detect_result(&_tmp , detections,confidence_threshold );
	cvNamedWindow("the_detect_result",0);
	cvShowImage("the_detect_result",&_tmp);
	cvWaitKey(0);
	
	cvDestroyWindow("the_detect_result"); 

/***************************************************/
    } else if (!type_indicate.compare("video")) {
    //add by wqz to show the results of detection 
    CvCapture* cvCap = cvCaptureFromFile(argv[1]);// argv[1] is video name
    clock_t time_begin ,time_end ;

    int interval = 50 ;
    IplImage * img_resize = cvCreateImage(cvSize(512,512),IPL_DEPTH_8U,3);
    const char *winName = "detection_result";
    cvNamedWindow(winName,0);
    while(1) {
      	interval++;
        IplImage* img = cvQueryFrame(cvCap);
        if (img == NULL) {
            printf("No more frames, press any key to exit.\n");
            break;
        }

	//if(interval>50)
	{	interval=0;

		if(img->width >img->height)
		cvSetImageROI(img,cvRect(int((img->width-img->height)/2),0,img->height,img->height));
		else 
		cvSetImageROI(img,cvRect(0,int((img->height-img->width)/2),img->width,img->width));


		cvResize(img,img_resize,cv::INTER_LINEAR);
		 
		cv::Mat M(img_resize, false);  
		CHECK(!M.empty()) << "Error when read frame";
    time_begin = clock();
		std::vector<vector<float> > detections = detector.Detect(M);
    time_end = clock();
    printf("the time comsuming:%f \n",difftime(time_end,time_begin)/CLOCKS_PER_SEC);
			
		show_detect_result(img_resize , detections,confidence_threshold );
		cvShowImage(winName, img_resize);

		
        	int key = cvWaitKey(1000/1000);// 30 frame/second for displaying in window
		
	}
    }

	cvReleaseImage(&img_resize);
	cvDestroyWindow(winName); 

	cvReleaseCapture(&cvCap);

    } else {
      LOG(FATAL) << "Unknown file_type: " << file_type;
    }
 // }
  return 0;
}
/*#else
int main(int argc, char** argv) {
  LOG(FATAL) << "This example requires OpenCV; compile with USE_OPENCV.";
}
#endif  // USE_OPENCV*/


可以根据输入参数决定测试的是图片还是视频,大部分代码为ssd自带例程中的,仅供参考。
CMakeLists.txt如下所示:

cmake_minimum_required(VERSION 2.8.7)
#cmake_policy(SET CMP0046 NEW)


#named the project 
project(ssd_300X300_detect_demo  CXX)

#set the caffe include path
set(Caffe_INCLUDE_DIR /usr/local/neumoai/caffe_ssd/distribute/include)
set(OpenCV_INCLUDE_DIR /usr/local/neumoai/opencv2.4.11/include)
set(Cuda_INCLUDE_DIR  /usr/local/neumoai/cuda8.0/include)
set(Log4cxx  /usr/local/log4cxx/include)
set(Root_include  /usr/include)
set(Home_include /usr/local/include)

include_directories(${Caffe_INCLUDE_DIR} ${OpenCV_INCLUDE_DIR} ${Log4cxx} ${Cuda_INCLUDE_DIR} ${Root_include} ${Home_include})
find_package(OpenCV REQUIRED)
message(${OpenCV_INCLUDE_DIR})
message(${OpenCV_LIBS})
link_directories("/usr/lib")
link_directories("/usr/local/lib")
link_directories("/usr/local/neumoai/cuda8.0/targets/x86_64-linux/lib")


add_executable(ssd_300X300_detect_demo  ssd_detect_log.cpp)
#target_link_libraries(ssd_300X300_detect_demo /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.19)
target_link_libraries(ssd_300X300_detect_demo ${OpenCV_LIBS})
target_link_libraries(ssd_300X300_detect_demo /usr/local/log4cxx/lib/liblog4cxx.so)
target_link_libraries(ssd_300X300_detect_demo /usr/local/neumoai/caffe_ssd/distribute/lib/libcaffe.so)
target_link_libraries(ssd_300X300_detect_demo libglog.so)
target_link_libraries(ssd_300X300_detect_demo libgflags.so)
target_link_libraries(ssd_300X300_detect_demo libcudart.so)
target_link_libraries(ssd_300X300_detect_demo libcublas.so)
target_link_libraries(ssd_300X300_detect_demo libcurand.so)
target_link_libraries(ssd_300X300_detect_demo librt.so)
target_link_libraries(ssd_300X300_detect_demo libboost_system.so)

#target_link_libraries(ssd_300X300_detect_demo /usr/local/neumoai/cuda8.0/lib64)

log4cxx的配置文件conf.log内容如下所示:

log4j.rootLogger=debug, R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=./ssd_detect.log
log4j.appender.R.MaxFileSize=100KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=10
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%5p %c [%t] (%F:%L) - %m%n
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值