【目标识别】【结果存入数据库】将Caffe框架和SSD最后检测结果存入Oracle数据库中

 

 

1、代码在ssd_detect中实现

// 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>
#endif  // USE_OPENCV
#include <algorithm>
#include <iomanip>
#include <iosfwd>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include <fstream>
#include <iostream>

#include <windows.h>
#include <sql.h>
#include <sqlext.h>
#include <odbcss.h>

//#define SQLBINDCOL
SQLHENV  henv = SQL_NULL_HENV;//定义环境句柄
SQLHDBC  hdbc1 = SQL_NULL_HDBC;//定义数据库连接句柄     
SQLHSTMT  hstmt1 = SQL_NULL_HSTMT;//定义语句句柄

#ifdef USE_OPENCV
using namespace caffe;  // NOLINT(build/namespaces)
//非核心代码已经省略
int main(int argc, char** argv) {
  ::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 = argv[1];
  const string& weights_file = 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);

  // Process image one by one.
  std::ifstream infile(argv[3]);
  std::string file;


  //连接数据库
  RETCODE retcode;//错误返回码

  // Allocate the ODBC Environment and save handle.
  retcode = SQLAllocHandle(SQL_HANDLE_ENV, NULL, &henv);
  if (retcode < 0)//错误处理
  {
	  out << "allocate ODBC Environment handle errors." << std::endl;
	  return -1;
  }
  // Notify ODBC that this is an ODBC 3.0 application.
  retcode = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION,
	  (SQLPOINTER)SQL_OV_ODBC3, SQL_IS_INTEGER);
  if (retcode < 0) //错误处理
  {
	  out << "the  ODBC is not version3.0 " << std::endl;
	  return -1;
  }

  // Allocate an ODBC connection and connect.
  retcode = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc1);
  if (retcode < 0) //错误处理
  {
	  out << "allocate ODBC connection handle errors." << std::endl;
	  return -1;
  }
  //Data Source Name must be of type User DNS or System DNS
  char* szDSN = "orcl";
  char* szUID = "hyjkxt";//log name
  char* szAuthStr = "hy_jkxt_2016";//passward
  //connect to the Data Source
  retcode = SQLConnect(hdbc1, (SQLCHAR*)szDSN, (SWORD)strlen(szDSN),(SQLCHAR*)szUID, (SWORD)strlen(szUID), (SQLCHAR*)szAuthStr, (SWORD)strlen(szAuthStr));
  if (retcode < 0) //错误处理
  {
	  out << "connect to  ODBC datasource errors." << std::endl;
	  return -1;
  }
  // Allocate a statement handle.
  retcode = SQLAllocHandle(SQL_HANDLE_STMT, hdbc1, &hstmt1);
  if (retcode < 0) //错误处理
  {
	  out << "allocate ODBC statement handle errors." << std::endl;
	  return -1;
  }









  //cv::namedWindow("result");
//  std::vector<cv::Rect> pos;
  while (infile >> file) {
    if (file_type == "image") {
		//std::cout << file << std::endl;
      cv::Mat img = cv::imread(file, -1);
      CHECK(!img.empty()) << "Unable to decode image " << file;
	  double t1 = cv::getTickCount();
      std::vector<vector<float> > detections = detector.Detect(img);
	  //t1 = cv::getTickCount() - t1;
	  //std::cout << "time:" << 1000 * t1 / cv::getTickFrequency() << std::endl;
	 
	  /* Print the detection results. */
	  //ofstream f1("/home/ubuntu/results.txt",ios::app);
	  std::ofstream f2("E:/detect/results.txt", ios::out);
	  int cat, person = 0, car = 0, boat = 0, p = 0, c = 0, b = 0, flag = 0;;
	  string s = "";
	  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) {
			  cat = static_cast<int>(d[1]);   //\BC\C6\CB\E3\C8˳\B5\B4\AC\CA\FD\C1\BF
			  if (cat == 1)
				  person++;
			  else if (cat == 2)
				  car++;
			  else
				  boat++;
		  }
	  }
	  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];
		  string pcb;
		  stringstream ss;
		  if (score >= confidence_threshold) {
			  flag = 1;
			  cat = static_cast<int>(d[1]);  //\BD\ABĿ\B1\EA\D6\D6\C0\E0\B4\FA\BAź\CD\CA\FD\C1\BFд\C8\EB\D7ַ\FB\B4\AEs
			  if (cat == 1)
			  {
				  if (p == 0)
				  {
					  p = 1;
					  ss.str("");
					  ss << d[1];
					  pcb = ss.str();
					  s += " ";
					  s += pcb;
					  //s+=" ";
					  ss.str("");
					  ss << person;
					  pcb = ss.str();
					  s += " ";
					  s += pcb;
					  //s+=" ";
				  }
			  }
			  else if (cat == 2)
			  {
				  if (c == 0)
				  {
					  c = 1;
					  ss.str("");
					  ss << d[1];
					  pcb = ss.str();
					  s += " ";
					  s += pcb;
					  //s+=" ";
					  ss.str("");
					  ss << car;
					  pcb = ss.str();
					  s += " ";
					  s += pcb;
					  //s+=" ";
				  }
			  }
			  else
			  {
				  if (b == 0)
				  {
					  b = 1;
					  ss.str("");
					  ss << d[1];
					  pcb = ss.str();
					  s += " ";
					  s += pcb;
					  //s+=" ";
					  ss.str("");
					  ss << boat;
					  pcb = ss.str();
					  s += " ";
					  s += pcb;
					  //s+=" ";
				  }
			  }
			  ss.str("");      //\B0\FCΧ\BA\D0\D7\F8\B1\EA
			  ss << (d[3] * img.cols);
			  pcb = ss.str();
			  s += " ";
			  s += pcb;
			  //s+=" ";
			  ss.str("");
			  ss << (d[4] * img.rows);
			  pcb = ss.str();
			  s += " ";
			  s += pcb;
			  //s+=" ";
			  ss.str("");
			  ss << (d[5] * img.cols);
			  pcb = ss.str();
			  s += " ";
			  s += pcb;
			  //s+=" ";
			  ss.str("");
			  ss << (d[6] * img.rows);
			  pcb = ss.str();
			  s += " ";
			  s += pcb;
			  //s+=" ";

		  }

	  }
	  if (!f2) break;
	  int q1, q2, q3, q5;
	  //file·\BE\B6+ԭͼƬ\C3\FB\B3\C6:/home/xxzx/.../KD481-\BF\BF\B4\AC\C5\C5_20170622165111_6532_14B50310_14981214718.jpg
	  //fil·\BE\B6+ԭͼƬ\C3\FB\B3\C6ȥ\B3\FD.jpg\B5\C4\CEļ\FE\C3\FB:/home/xxzx/.../KD481-\BF\BF\B4\AC\C5\C5_20170622165111_6532_14B50310_14981214718
	  //iddԭͼƬ\C3\FB\B3\C6ȥ\B3\FD.jpg\B5\C4\CEļ\FE\C3\FB:KD481-\BF\BF\B4\AC\C5\C5_20170622165111_6532_14B50310_14981214718
	  //idԭͼƬ\C3\FB\B3Ʋ\BF\B7\D6:KD481-\BF\BF\B4\AC\C5\C5
	  //iddata1\B4\D3ʱ\BC俪ʼ\B5\BD\D7\EE\BA\F3:20170622165111_6532_14B50310_14981214718
	  //time\C4\EA\D4\C2\C8\D5ʱ\B7\D6\C3\EB:20170622165111
	  //year,month,day:2017,06,22
	  //sfmʱ\B7\D6\C3\EB:165111
	  //shi,fen,miaoʱ\A3\AC\B7֣\AC\C3\EB:16,51,11
	  //idtime\C3\FB\B3\C6+ʱ\BC\E4:KD481-\BF\BF\B4\AC\C5\C5_2017-06-22
	  string fil, id, data, time, iddata, year, month, day, md, iddata1, idd, mds, dsfm, sfm, idtime, ymd, shi, fen, miao, sf;
	  q1 = file.rfind("/");
	  q2 = file.find(".jpg");
	  fil = file;
	  fil.erase(q2);
	  //cout<<fil<<std::endl;
	  //cout<<q1<<std::endl;
	  //s=s.assign(s,1,string::npos);
	  idd.assign(fil, q1 + 1, string::npos);
	  q3 = idd.find("_");
	  id.assign(idd, 0, q3);//mingcheng
	  iddata1.assign(idd, q3 + 1, string::npos);
	  q5 = iddata1.find("_");
	  time.assign(iddata1, 0, q5);//shijian
	  year.assign(time, 0, 4);
	  mds.assign(time, 4, string::npos);
	  month.assign(mds, 0, 2);
	  dsfm.assign(mds, 2, string::npos);
	  day.assign(dsfm, 0, 2);
	  sfm.assign(dsfm, 2, string::npos);
	 // string wpath = "D:/beifen/warning/";
	  //string upath = "D:/beifen/warning/";
	  string wpath = "D:/beifen/warning/";//写入数据库的路径
	  string upath = "D:/beifen/warning/";//存储路径
	  idtime = id + "_";
	  idtime = idtime + time;
	  shi.assign(sfm, 0, 2);
	  sf.assign(sfm, 2, string::npos);
	  fen.assign(sf, 0, 2);
	  miao.assign(sfm, 4, 6);
	  //cout<<iddata<<" "<<id<<" "<<data<<" "<<s<< std::endl;
	  //wpath  windows·\BE\B6:D:/beifen/warning/2017/06/22/
	  //upath  ubuntu·\BE\B6:/home/xxzx/Share/warning/2017/06/22/
	  //ymd\C4\EA\D4\C2\C8\D5:2016-06-22
	  //s\BC\EC\B2\E2\D0\C5Ϣ:1 1 x1 y1 x2 y2  \D6\D6\C0\E0\B4\FA\C2\EB  Ŀ\B1\EA\CA\FD\C1\BF   Ŀ\B1\EA\D7\F8\B1\EA
	  string path = year; path = path + '/'; path = path + month; path = path + '/'; path = path + day; path = path + '/'; path = path + idtime; path = path + ".jpg";
	  wpath = wpath + path;
	  upath = upath + path;
	  ymd = year + "-"; ymd = ymd + month; ymd = ymd + "-"; ymd = ymd + day; ymd = ymd + " "; ymd = ymd + shi; ymd = ymd + ":"; ymd = ymd + fen; ymd = ymd + ":"; ymd = ymd + miao;

	  if (flag == 1) {
		  s = s.assign(s, 1, string::npos);
		  /*\CA\FD\BEݿ\E2\B2\D9\D7\F7\B4\FA\C2\EB



		  */
		  //idtime,id,wpath,s
		  //f1<<idtime<<" "<<id<<" "<<ymd<<" "<<time<<" "<<year<<" "<<month<<" "<<day<<" "<<sfm<<" "<<wpath<<" "<<upath<<" "<<s<<std::endl;
		  f2 << idtime << std::endl;
		  f2 << id << std::endl;
		  f2 << ymd << std::endl;
		  f2 << wpath << std::endl;
		  f2 << s << std::endl;
		  //数据写入数据库
		  string str = "INSERT INTO HY_SPJK_CNN_BJXXB(BJBH,SXTBH,CLBJ,SJ,JTLJ,JCXX) VALUES('" + idtime + "','" + id + "','" + '0' + "'," + "to_date('" + ymd + "','yyyy/mm/dd_hh24:mi:ss')" + ",'" + wpath + "','" + s + "')";
		 // string str = "INSERT INTO HY_SPJK_CNN_BJXXB(BJBH,SXTBH,CLBJ,SJ,JTLJ,JCXX,FWQIP) VALUES('" + idtime + "','" + id + "','" + '0' + "'," + "to_date('" + ymd + "','yyyy/mm/dd_hh24:mi:ss')" + ",'" + wpath + "','" + s + "','10.67.185.117')";

		  //out << str << std::endl;
		  char *camIdChar = new char[str.size() + 1];
		  const char * mystr = str.c_str();
		  strcpy(camIdChar, mystr);
		  
		  //insert into HY_SPJK_CNN_BJXXB values('idtime','id','0','ymd','wpath','s');
		  
		  TCHAR *szSelect1 = camIdChar;
		  retcode = SQLExecDirect(hstmt1, (SQLCHAR*)szSelect1, SQL_NTS);
		  //out << szSelect1 << std::endl;
		  //string str="INSERT INTO HY_SPJK_CNN_BJXXB(BJBH,SXTBH,CLBJ,SJ,JTLJ,JCXX) VALUES('" + idtime + "','" + id + "','" + '0' + "'," + "to_date('" + ymd + "','yyyy/mm/dd_hh24:mi:ss')" + ",'" + wpath + "','" + s + "')"
		  //retcode = SQLExecDirect(hstmt1, (SQLCHAR*)"insert into HY_SPJK_CNN_BJXXBBF(BJBH,SXTBH,CLBJ,JTLJ,JCXX) values('160_20170718121212','160','0','wpath','s')", SQL_NTS);
		  if (retcode<0)
		  {
			  out << "insert errors." << std::endl;
			  return -1;
		  }
		  //system("/home/ubuntu/caffe/examples/ssd/test");
		  //out<<file<<std::endl;
		  std::ifstream in;
		  std::ofstream out;
		  char inpath[1000], outpath[1000];
		  strcpy(inpath, file.c_str());
		  strcpy(outpath, upath.c_str());
		  //string infile;
		  //stringstream ss;
		  //ss.str("");
		  //ss<<file;
		  //infile=ss.str();
		  //in.open("/home/xxzx/1.jpg",ios::binary);//open source file
		  //in.open("/home/xxzx/caffe/data/xxzx_test/海工大队码头_20170620203248_6332_16F34780_14979619684.jpg",ios::binary);
		  in.open(inpath, ios::binary);	//\B4\F2\BF\AAĿ\B1\EA·\BE\B6\CEļ\FE
		  if (in.fail())//open source failed
		  {
			  out << "Error 1: Fail to open the source file." << std::endl;
			  in.close();
			  out.close();
			  return 0;
		  }
		  out.open(outpath, ios::binary);  //\BD\AB\B4?\C4\CEļ\FEת\B4浽ָ\B6\A8Ŀ¼
		  //out.open("/home/xxzx/Share/warning/2017/06/20/海工大队码头_20170620203300.jpg",ios::binary);//build target file 
		  //out.open(upath,ios::binary);
		  if (out.fail())//build file failed
		  {
			  out << "Error 2: Fail to create the new file." << std::endl;
			  out.close();
			  in.close();
			  return 0;
		  }
		  out << in.rdbuf();
		  out.close();
		  in.close();
	  }
	  //f1.close();  
	  f2.close();
//
//      /* Print the detection results. */
	  pos.clear();
//      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;
//		  int posx = static_cast<int>(d[3] * img.cols);
//		  int posy = static_cast<int>(d[4] * img.rows);
//		  int posw = static_cast<int>(d[5] * img.cols) - posx;
//		  int posh = static_cast<int>(d[6] * img.rows) - posy;
//		  cv::Rect pos(posx,posy,posw,posh);
//		  cv::rectangle(img, pos, cv::Scalar(255, 0, 0));
//		  cv::imshow("result", img);
//		  cv::waitKey(0);
//        }
//      }
    } else if (file_type == "video") {
      cv::VideoCapture cap(file);
      if (!cap.isOpened()) {
        LOG(FATAL) << "Failed to open video: " << file;
      }
      cv::Mat img;
      int frame_count = 0;
      while (true) {
        bool success = cap.read(img);
        if (!success) {
          LOG(INFO) << "Process " << frame_count << " frames from " << file;
          break;
        }
        CHECK(!img.empty()) << "Error when read frame";
        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 << std::setfill('0') << std::setw(6) << frame_count << " ";
            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;
          }
        }
        ++frame_count;
      }
      if (cap.isOpened()) {
        cap.release();
      }
    } else {
      LOG(FATAL) << "Unknown file_type: " << file_type;
    }
  }
  /* Clean up.*/
  SQLFreeHandle(SQL_HANDLE_STMT, hstmt1);
  SQLDisconnect(hdbc1);
  SQLFreeHandle(SQL_HANDLE_DBC, hdbc1);
  SQLFreeHandle(SQL_HANDLE_ENV, henv);
  return(0);
  return 0;
}

2、然后编译caffe,形成classification.exe可执行文件,还有关于连接数据库部分稍后补充,有点急事

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值