Commit b73fa348 by guanghui.cui

支持多人识别

parent 2115f608
#TBB library
include_directories(${TBB_ROOT_DIR}/include)
# Local libraries
include_directories(${LandmarkDetector_SOURCE_DIR}/include)
include_directories(../../lib/local/LandmarkDetector/include)
add_executable(FaceLandmarkVidMulti FaceLandmarkVidMulti.cpp)
target_link_libraries(FaceLandmarkVidMulti LandmarkDetector)
target_link_libraries(FaceLandmarkVidMulti dlib)
target_link_libraries(FaceLandmarkVidMulti ${OpenCV_LIBS} ${Boost_LIBRARIES} ${TBB_LIBRARIES})
install (TARGETS FaceLandmarkVidMulti DESTINATION bin)
#ifndef BASEDEFINE_H
#define BASEDEFINE_H
#include <iostream>
#include <vector>
struct sReqCertificate
{
std::string Image_file;
std::string member_tel;
std::string member_name;
std::string authentication_channel;
std::string union_id;
};
struct sUserInfo
{
std::string confidence;
std::string memberTel;
std::string memberName;
std::string authenticationChannel;
std::string unionId;
};
struct sServerResponse
{
std::string success;
std::string errorMessage;
std::vector<sUserInfo> vecUser;
};
#endif
\ No newline at end of file
///////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2016, Carnegie Mellon University and University of Cambridge,
// all rights reserved.
//
// THIS SOFTWARE IS PROVIDED 揂S IS?FOR ACADEMIC USE ONLY AND ANY EXPRESS
// OR IMPLIED WARRANTIES WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
// BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY.
// OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Notwithstanding the license granted herein, Licensee acknowledges that certain components
// of the Software may be covered by so-called 搊pen source?software licenses (揙pen Source
// Components?, which means any software licenses approved as open source licenses by the
// Open Source Initiative or any substantially similar licenses, including without limitation any
// license that, as a condition of distribution of the software licensed under such license,
// requires that the distributor make the software available in source code format. Licensor shall
// provide a list of Open Source Components for a particular version of the Software upon
// Licensee抯 request. Licensee will comply with the applicable terms of such licenses and to
// the extent required by the licenses covering Open Source Components, the terms of such
// licenses will apply in lieu of the terms of this Agreement. To the extent the terms of the
// licenses applicable to Open Source Components prohibit any of the restrictions in this
// License Agreement with respect to such Open Source Component, such restrictions will not
// apply to such Open Source Component. To the extent the terms of the licenses applicable to
// Open Source Components require Licensor to make an offer to provide source code or
// related information in connection with the Software, such offer is hereby made. Any request
// for source code or related information should be directed to cl-face-tracker-distribution@lists.cam.ac.uk
// Licensee acknowledges receipt of notices for the Open Source Components for the initial
// delivery of the Software.
// * Any publications arising from the use of this software, including but
// not limited to academic journal and conference publications, technical
// reports and manuals, must cite at least one of the following works:
//
// OpenFace: an open source facial behavior analysis toolkit
// Tadas Baltru歛itis, Peter Robinson, and Louis-Philippe Morency
// in IEEE Winter Conference on Applications of Computer Vision, 2016
//
// Rendering of Eyes for Eye-Shape Registration and Gaze Estimation
// Erroll Wood, Tadas Baltru歛itis, Xucong Zhang, Yusuke Sugano, Peter Robinson, and Andreas Bulling
// in IEEE International. Conference on Computer Vision (ICCV), 2015
//
// Cross-dataset learning and person-speci?c normalisation for automatic Action Unit detection
// Tadas Baltru歛itis, Marwa Mahmoud, and Peter Robinson
// in Facial Expression Recognition and Analysis Challenge,
// IEEE International Conference on Automatic Face and Gesture Recognition, 2015
//
// Constrained Local Neural Fields for robust facial landmark detection in the wild.
// Tadas Baltru歛itis, Peter Robinson, and Louis-Philippe Morency.
// in IEEE Int. Conference on Computer Vision Workshops, 300 Faces in-the-Wild Challenge, 2013.
//
///////////////////////////////////////////////////////////////////////////////
// FaceTrackingVidMulti.cpp : Defines the entry point for the multiple face tracking console application.
#include "LandmarkCoreIncludes.h"
#include <fstream>
#include <sstream>
// OpenCV includes
#include <opencv2/videoio/videoio.hpp> // Video write
#include <opencv2/videoio/videoio_c.h> // Video write
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "jsonAnalysis.h"
#include "../curl/curl.h"
#include "utility/utilCommonAPI.h"
#include "utility/iniOperation.h"
#pragma comment(lib, "libcurl.lib")
bool bTakePic = false; //是否开始拍照
double accuracy = 0.00;
string postResponseStr;
string socketBackJson;
struct faceModel
{
cv::Vec4d rect; //头像范围
double dAcc; //精确度
};
#define INFO_STREAM( stream ) \
std::cout << stream << std::endl
#define WARN_STREAM( stream ) \
std::cout << "Warning: " << stream << std::endl
#define ERROR_STREAM( stream ) \
std::cout << "Error: " << stream << std::endl
static void printErrorAndAbort( const std::string & error )
{
std::cout << error << std::endl;
abort();
}
#define FATAL_STREAM( stream ) \
printErrorAndAbort( std::string( "Fatal error: " ) + stream )
using namespace std;
vector<string> get_arguments(int argc, char **argv)
{
vector<string> arguments;
for(int i = 0; i < argc; ++i)
{
arguments.push_back(string(argv[i]));
}
return arguments;
}
void NonOverlapingDetections(const vector<LandmarkDetector::CLNF>& clnf_models, vector<cv::Rect_<double> >& face_detections)
{
// Go over the model and eliminate detections that are not informative (there already is a tracker there)
for(size_t model = 0; model < clnf_models.size(); ++model)
{
// See if the detections intersect
cv::Rect_<double> model_rect = clnf_models[model].GetBoundingBox();
for(int detection = face_detections.size()-1; detection >=0; --detection)
{
double intersection_area = (model_rect & face_detections[detection]).area();
double union_area = model_rect.area() + face_detections[detection].area() - 2 * intersection_area;
// If the model is already tracking what we're detecting ignore the detection, this is determined by amount of overlap
if( intersection_area/union_area > 0.5)
{
face_detections.erase(face_detections.begin() + detection);
}
}
}
}
// reply of the requery
size_t req_reply(void *ptr, size_t size, size_t nmemb, void *stream)
{
string *str = (string*)stream;
string strTmp((char*)ptr, size*nmemb);
(*str) = strTmp;
//(*str).append((char*)ptr, size*nmemb);
//cout << (char*)ptr << endl;
return size * nmemb;
}
// http POST
CURLcode curl_post_req(const string &url, const string imgPath, string &response)
{
// init curl
CURL *curl = curl_easy_init();
// res code
CURLcode res;
if (curl)
{
string fileName;
#ifdef WIN32
fileName = imgPath.substr(imgPath.rfind('\\') + 1, imgPath.size());
#else
fileName = imgPath.substr(imgPath.rfind('/') + 1, imgPath.size());
#endif
struct curl_httppost *formpost = NULL;
struct curl_httppost *lastptr = NULL;
curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "imageFile", CURLFORM_FILE, imgPath.data(), CURLFORM_END);
curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "filename", CURLFORM_COPYCONTENTS, fileName.data(), CURLFORM_END);
curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "submit", CURLFORM_COPYCONTENTS, "send", CURLFORM_END);
// set params
struct curl_slist *head = NULL;
head = curl_slist_append(head, "Content-Type:multipart/form-data");
//head = curl_slist_append(head, "Content-Type:application/json");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, head);
curl_easy_setopt(curl, CURLOPT_POST, 1); // post req
curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); // url
curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
//curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postParams.c_str()); // params
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false); // if want to use https
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false); // set peer and host verify false
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, req_reply);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&response);
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(curl, CURLOPT_HEADER, 1);
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 3);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 3);
// start req
res = curl_easy_perform(curl);
}
// release curl
curl_easy_cleanup(curl);
return res;
}
#include <dlib/sockets.h>
#include <dlib/server.h>
HANDLE g_hSemaphore = NULL;
//string socketBackJson;
class serv : public dlib::server
{
void on_connect(
dlib::connection& con
)
{
char tmpJson[1000];
int n = con.read(tmpJson, 1000);
tmpJson[n] = '\0';
cout << "recived data:" << tmpJson << endl;
int fm_cmd = SocketRequestJson(tmpJson);
if (2002 == fm_cmd) {
bTakePic = true;
DWORD dw = WaitForSingleObject(g_hSemaphore,10000 /*INFINITE*/);
if (dw == WAIT_TIMEOUT) {
socketBackJson = GetSocketResultJson(99, "timeout", "");
}
//-----------
cout << "-----------------------------socket back data:" << socketBackJson.data() << endl;
con.write(socketBackJson.data(), socketBackJson.length());
}
con.shutdown();
}
};
serv our_server;
void dlibServer()
{
try
{
// set up the server object we have made
our_server.set_listening_port(24777);
// Tell the server to begin accepting connections.
our_server.set_max_connections(10000);
our_server.start_async();
//cin.get();
}
catch (exception& e)
{
cout << e.what() << endl;
}
}
int main (int argc, char **argv)
{
//信号量
g_hSemaphore = CreateSemaphore(NULL //信号量的安全特性
, 1 //设置信号量的初始计数。可设置零到最大值之间的一个值
, 1 //设置信号量的最大计数
, NULL //指定信号量对象的名称
);
if (NULL == g_hSemaphore)
{
cout << "create hSemaphore failed! error_code:" << GetLastError() << endl;
return 0;
}
WaitForSingleObject(g_hSemaphore, INFINITE);
dlibServer();
// global init curl
curl_global_init(CURL_GLOBAL_ALL);
std::string strFilePath = GetProcDir();
std::string strPathImg = strFilePath + "tmpimg.jpg";
std::string strPathIni = strFilePath + "config.ini";
std::string strUrl = ZIni::readString("SYS", "serachURL", "", strPathIni.c_str());
accuracy = ZIni::readDouble("SYS", "accuracy", 0.06, strPathIni.c_str());
vector<string> arguments = get_arguments(argc, argv);
// Some initial parameters that can be overriden from command line
vector<string> files, depth_directories, tracked_videos_output, dummy_out;
// By default try webcam 0
int device = 0;
// cx and cy aren't necessarilly in the image center, so need to be able to override it (start with unit vals and init them if none specified)
float fx = 600, fy = 600, cx = 0, cy = 0;
LandmarkDetector::FaceModelParameters det_params(arguments);
det_params.use_face_template = true;
// This is so that the model would not try re-initialising itself
det_params.reinit_video_every = -1;
det_params.curr_face_detector = LandmarkDetector::FaceModelParameters::HOG_SVM_DETECTOR;
vector<LandmarkDetector::FaceModelParameters> det_parameters;
det_parameters.push_back(det_params);
// Get the input output file parameters
bool u;
string output_codec;
LandmarkDetector::get_video_input_output_params(files, depth_directories, dummy_out, tracked_videos_output, u, output_codec, arguments);
// Get camera parameters
LandmarkDetector::get_camera_params(device, fx, fy, cx, cy, arguments);
// The modules that are being used for tracking
vector<LandmarkDetector::CLNF> clnf_models;
vector<bool> active_models;
int num_faces_max = 4;
LandmarkDetector::CLNF clnf_model(det_parameters[0].model_location);
clnf_model.face_detector_HAAR.load(det_parameters[0].face_detector_location);
clnf_model.face_detector_location = det_parameters[0].face_detector_location;
clnf_models.reserve(num_faces_max);
clnf_models.push_back(clnf_model);
active_models.push_back(false);
for (int i = 1; i < num_faces_max; ++i)
{
clnf_models.push_back(clnf_model);
active_models.push_back(false);
det_parameters.push_back(det_params);
}
// If multiple video files are tracked, use this to indicate if we are done
bool done = false;
int f_n = -1;
// If cx (optical axis centre) is undefined will use the image size/2 as an estimate
bool cx_undefined = false;
if(cx == 0 || cy == 0)
{
cx_undefined = true;
}
while(!done) // this is not a for loop as we might also be reading from a webcam
{
string current_file;
// We might specify multiple video files as arguments
if(files.size() > 0)
{
f_n++;
current_file = files[f_n];
}
bool use_depth = !depth_directories.empty();
// Do some grabbing
cv::VideoCapture video_capture;
if( current_file.size() > 0 )
{
INFO_STREAM( "Attempting to read from file: " << current_file );
video_capture = cv::VideoCapture( current_file );
}
else
{
INFO_STREAM( "Attempting to capture from device: " << device );
video_capture = cv::VideoCapture( device );
// Read a first frame often empty in camera
cv::Mat captured_image;
video_capture >> captured_image;
}
if (!video_capture.isOpened())
{
FATAL_STREAM("Failed to open video source");
return 1;
}
else INFO_STREAM( "Device or file opened");
cv::Mat captured_image;
video_capture >> captured_image;
// If optical centers are not defined just use center of image
if(cx_undefined)
{
cx = captured_image.cols / 2.0f;
cy = captured_image.rows / 2.0f;
}
int frame_count = 0;
// saving the videos
cv::VideoWriter writerFace;
if(!tracked_videos_output.empty())
{
try
{
writerFace = cv::VideoWriter(tracked_videos_output[f_n], CV_FOURCC(output_codec[0],output_codec[1],output_codec[2],output_codec[3]), 30, captured_image.size(), true);
}
catch(cv::Exception e)
{
WARN_STREAM( "Could not open VideoWriter, OUTPUT FILE WILL NOT BE WRITTEN. Currently using codec " << output_codec << ", try using an other one (-oc option)");
}
}
// For measuring the timings
int64 t1,t0 = cv::getTickCount();
double fps = 10;
INFO_STREAM( "Starting tracking");
while(!captured_image.empty())
{
// Reading the images
cv::Mat_<float> depth_image;
cv::Mat_<uchar> grayscale_image;
cv::Mat disp_image = captured_image.clone();
if(captured_image.channels() == 3)
{
cv::cvtColor(captured_image, grayscale_image, CV_BGR2GRAY);
}
else
{
grayscale_image = captured_image.clone();
}
// Get depth image
if(use_depth)
{
char* dst = new char[100];
std::stringstream sstream;
sstream << depth_directories[f_n] << "\\depth%05d.png";
sprintf(dst, sstream.str().c_str(), frame_count + 1);
// Reading in 16-bit png image representing depth
cv::Mat_<short> depth_image_16_bit = cv::imread(string(dst), -1);
// Convert to a floating point depth image
if(!depth_image_16_bit.empty())
{
depth_image_16_bit.convertTo(depth_image, CV_32F);
}
else
{
WARN_STREAM( "Can't find depth image" );
}
}
vector<cv::Rect_<double> > face_detections;
bool all_models_active = true;
for(unsigned int model = 0; model < clnf_models.size(); ++model)
{
if(!active_models[model])
{
all_models_active = false;
}
}
// Get the detections (every 8th frame and when there are free models available for tracking)
if(frame_count % 8 == 0 && !all_models_active)
{
if(det_parameters[0].curr_face_detector == LandmarkDetector::FaceModelParameters::HOG_SVM_DETECTOR)
{
vector<double> confidences;
LandmarkDetector::DetectFacesHOG(face_detections, grayscale_image, clnf_models[0].face_detector_HOG, confidences);
}
else
{
LandmarkDetector::DetectFaces(face_detections, grayscale_image, clnf_models[0].face_detector_HAAR);
}
}
// Keep only non overlapping detections (also convert to a concurrent vector
NonOverlapingDetections(clnf_models, face_detections);
vector<tbb::atomic<bool> > face_detections_used(face_detections.size());
// Go through every model and update the tracking
tbb::parallel_for(0, (int)clnf_models.size(), [&](int model){
//for(unsigned int model = 0; model < clnf_models.size(); ++model)
//{
bool detection_success = false;
// If the current model has failed more than 4 times in a row, remove it
if(clnf_models[model].failures_in_a_row > 4)
{
active_models[model] = false;
clnf_models[model].Reset();
}
// If the model is inactive reactivate it with new detections
if(!active_models[model])
{
for(size_t detection_ind = 0; detection_ind < face_detections.size(); ++detection_ind)
{
// if it was not taken by another tracker take it (if it is false swap it to true and enter detection, this makes it parallel safe)
if(face_detections_used[detection_ind].compare_and_swap(true, false) == false)
{
// Reinitialise the model
clnf_models[model].Reset();
// This ensures that a wider window is used for the initial landmark localisation
clnf_models[model].detection_success = false;
detection_success = LandmarkDetector::DetectLandmarksInVideo(grayscale_image, depth_image, face_detections[detection_ind], clnf_models[model], det_parameters[model]);
// This activates the model
active_models[model] = true;
// break out of the loop as the tracker has been reinitialised
break;
}
}
}
else
{
// The actual facial landmark detection / tracking
detection_success = LandmarkDetector::DetectLandmarksInVideo(grayscale_image, depth_image, clnf_models[model], det_parameters[model]);
}
});
//vector<cv::Vec4d> vecRect;
vector<faceModel> vecFaceModel;
// Go through every model and visualise the results
for(size_t model = 0; model < clnf_models.size(); ++model)
{
// Visualising the results
// Drawing the facial landmarks on the face and the bounding box around it if tracking is successful and initialised
double detection_certainty = clnf_models[model].detection_certainty;
double visualisation_boundary = -0.1;
// Only draw if the reliability is reasonable, the value is slightly ad-hoc
if(detection_certainty < visualisation_boundary)
{
//LandmarkDetector::Draw(disp_image, clnf_models[model]);
if(detection_certainty > 1)
detection_certainty = 1;
if(detection_certainty < -1)
detection_certainty = -1;
detection_certainty = (detection_certainty + 1)/(visualisation_boundary +1);
// A rough heuristic for box around the face width
int thickness = (int)std::ceil(2.0* ((double)captured_image.cols) / 640.0);
// Work out the pose of the head from the tracked model
cv::Vec6d pose_estimate = LandmarkDetector::GetCorrectedPoseWorld(clnf_models[model], fx, fy, cx, cy);
// Draw it in reddish if uncertain, blueish if certain
//LandmarkDetector::DrawBox(disp_image, pose_estimate, cv::Scalar((1-detection_certainty)*255.0,0, detection_certainty*255), thickness, fx, fy, cx, cy);
faceModel faceAttr;
cv::Vec4d rect;
LandmarkDetector::DrawRect(disp_image, pose_estimate, cv::Scalar(0, (1 - detection_certainty)*255.0, detection_certainty * 255), thickness, fx, fy, cx, cy, rect);
faceAttr.dAcc = detection_certainty;
faceAttr.rect = rect;
vecFaceModel.push_back(faceAttr);
}
}
//获取到面积最大的矩形
int posMax = 0;
double rcArea = 0.0000;
for (int i = 0; i < vecFaceModel.size(); i++) {
double dArea = vecFaceModel[i].rect[2]* vecFaceModel[i].rect[3];
if (dArea > rcArea) {
rcArea = dArea;
posMax = i;
}
}
//std::string strPathImg="E:\\tempImg.jpg";
if (vecFaceModel.size() > 0&& bTakePic&&vecFaceModel[posMax].dAcc < accuracy) {
cout << strPathImg.data() << endl;
socketBackJson.clear();
cout << "+++++++attr:" << vecFaceModel[posMax].rect[0] << " " << vecFaceModel[posMax].rect[1] << " " << vecFaceModel[posMax].rect[2] << " " << vecFaceModel[posMax].rect[3] << " "<< vecFaceModel[posMax].dAcc<<endl;
int rcX = captured_image.cols*vecFaceModel[posMax].rect[0];
int rcY = captured_image.rows*vecFaceModel[posMax].rect[1];
int rcWidth = captured_image.cols*vecFaceModel[posMax].rect[2];
int rcHeight = captured_image.rows*vecFaceModel[posMax].rect[3];
rcX = rcX - 25 > 0 ? rcX - 25 : rcX;
rcY = rcY - 60 > 0 ? rcY - 60 : rcY;
rcWidth = rcWidth + 50 < captured_image.cols ? rcWidth + 50 : rcWidth;
rcHeight = rcHeight + 80 < captured_image.rows ? rcHeight + 80 : rcHeight;
if (rcX < 0)
rcX = 0;
if (rcY < 0)
rcY = 0;
if (rcX + rcWidth > captured_image.cols) {
rcWidth = captured_image.cols - rcX;
}
if (rcY + rcHeight > captured_image.rows) {
rcHeight = captured_image.rows - rcY;
}
cv::Rect rect(rcX, rcY, rcWidth, rcHeight);
cv::Mat newPhoto = captured_image(rect);
vector<int> compression_params;
compression_params.push_back(CV_IMWRITE_JPEG_QUALITY); //选择jpeg
compression_params.push_back(100); //在这个填入你要的图片质量
cv::imwrite(strPathImg, newPhoto, compression_params);
bTakePic = false;
postResponseStr.clear();
auto res = curl_post_req(strUrl, strPathImg, postResponseStr);
if (res != CURLE_OK)
cerr << "curl_easy_perform() failed: " + string(curl_easy_strerror(res)) << endl;
else {
postResponseStr = UnicodeToAscii(Utf8ToUnicode(postResponseStr));
cout << "utf8 to ascii:" << postResponseStr << endl;
}
sServerResponse response = GetServerResultData(postResponseStr.data());
//-------------socket返回给pos----------------
if (response.vecUser.size() > 0) {
int status = 0;
string msg="";
string phone = "";
float fNum = 0.00;
fNum = atof(response.vecUser[0].confidence.data());
if (fNum > 80.000) {
status = 100;
msg = "success";
phone = response.vecUser[0].memberTel.data();
}
else {
status = 31;
msg = "no";
}
cout << "confidence:" << response.vecUser[0].confidence.data() << endl;
socketBackJson = GetSocketResultJson(status, msg.data(), phone.data());
cout << "soceket back json:" << socketBackJson.data() << endl;
}
cout << "---------------------------release semaphore" << endl;
ReleaseSemaphore(g_hSemaphore, 1, NULL);
}
//-------------------------------------------------------------------------------------------
// Work out the framerate
if(frame_count % 10 == 0)
{
t1 = cv::getTickCount();
fps = 10.0 / (double(t1-t0)/cv::getTickFrequency());
t0 = t1;
}
// Write out the framerate on the image before displaying it
char fpsC[255];
sprintf(fpsC, "%d", (int)fps);
string fpsSt("FPS:");
fpsSt += fpsC;
cv::putText(disp_image, fpsSt, cv::Point(10,20), CV_FONT_HERSHEY_SIMPLEX, 0.5, CV_RGB(255,0,0), 1, CV_AA);
int num_active_models = 0;
for( size_t active_model = 0; active_model < active_models.size(); active_model++)
{
if(active_models[active_model])
{
num_active_models++;
}
}
char active_m_C[255];
sprintf(active_m_C, "%d", num_active_models);
string active_models_st("Active models:");
active_models_st += active_m_C;
cv::putText(disp_image, active_models_st, cv::Point(10,60), CV_FONT_HERSHEY_SIMPLEX, 0.5, CV_RGB(255,0,0), 1, CV_AA);
if(!det_parameters[0].quiet_mode)
{
cv::namedWindow("tracking_result",1);
cv::imshow("tracking_result", disp_image);
if(!depth_image.empty())
{
// Division needed for visualisation purposes
imshow("depth", depth_image/2000.0);
}
}
// output the tracked video
if(!tracked_videos_output.empty())
{
writerFace << disp_image;
}
video_capture >> captured_image;
// detect key presses
char character_press = cv::waitKey(1);
// restart the trackers
if(character_press == 'r')
{
for(size_t i=0; i < clnf_models.size(); ++i)
{
clnf_models[i].Reset();
active_models[i] = false;
}
}
else if (character_press == 's')
{
bTakePic = true;
}
// quit the application
//else if(character_press=='q')
//{
// return(0);
//}
// Update the frame count
frame_count++;
}
frame_count = 0;
// Reset the model, for the next video
for(size_t model=0; model < clnf_models.size(); ++model)
{
clnf_models[model].Reset();
active_models[model] = false;
}
// break out of the loop if done with all the files
if(f_n == files.size() -1)
{
done = true;
}
}
// global release
curl_global_cleanup();
CloseHandle(g_hSemaphore);
return 0;
}
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{C3FAF36F-44BC-4454-87C2-C5106575FE50}</ProjectGuid>
<RootNamespace>FaceLandmarkVidMulti</RootNamespace>
<ProjectName>FaceLandmarkVidMulti</ProjectName>
<WindowsTargetPlatformVersion>8.1</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="..\..\lib\3rdParty\dlib\dlib.props" />
<Import Project="..\..\lib\3rdParty\OpenCV3.1\openCV3.1.props" />
<Import Project="..\..\lib\3rdParty\boost\boost_d.props" />
<Import Project="..\..\lib\3rdParty\tbb\tbb_d.props" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="..\..\lib\3rdParty\dlib\dlib.props" />
<Import Project="..\..\lib\3rdParty\OpenCV3.1\openCV3.1.props" />
<Import Project="..\..\lib\3rdParty\boost\boost_d.props" />
<Import Project="..\..\lib\3rdParty\tbb\tbb_d.props" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="..\..\lib\3rdParty\boost\boost.props" />
<Import Project="..\..\lib\3rdParty\dlib\dlib.props" />
<Import Project="..\..\lib\3rdParty\tbb\tbb.props" />
<Import Project="..\..\lib\3rdParty\OpenCV3.1\openCV3.1.props" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="..\..\lib\3rdParty\boost\boost.props" />
<Import Project="..\..\lib\3rdParty\dlib\dlib.props" />
<Import Project="..\..\lib\3rdParty\tbb\tbb.props" />
<Import Project="..\..\lib\3rdParty\OpenCV3.1\openCV3.1.props" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<TargetName>FaceLandmarkVidMulti</TargetName>
<IntDir>$(ProjectDir)$(Configuration)\</IntDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<TargetName>FaceLandmarkVidMulti</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<TargetName>FaceLandmarkVidMulti</TargetName>
<IntDir>$(ProjectDir)$(Configuration)\</IntDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<TargetName>FaceLandmarkVidMulti</TargetName>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>$(SolutionDir)\lib\local\LandmarkDetector\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>$(SolutionDir)\lib\local\LandmarkDetector\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<EnableEnhancedInstructionSet>AdvancedVectorExtensions</EnableEnhancedInstructionSet>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<AdditionalIncludeDirectories>$(SolutionDir)\lib\local\LandmarkDetector\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<AdditionalIncludeDirectories>$(SolutionDir)\lib\local\LandmarkDetector\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<EnableEnhancedInstructionSet>AdvancedVectorExtensions</EnableEnhancedInstructionSet>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="FaceLandmarkVidMulti.cpp" />
<ClCompile Include="jsonAnalysis.cpp" />
<ClCompile Include="utility\iniOperation.cpp" />
<ClCompile Include="utility\utilCommonAPI.cpp" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\lib\local\LandmarkDetector\LandmarkDetector.vcxproj">
<Project>{bdc1d107-de17-4705-8e7b-cdde8bfb2bf8}</Project>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<ClInclude Include="CommonStruct.h" />
<ClInclude Include="jsonAnalysis.h" />
<ClInclude Include="utility\iniOperation.h" />
<ClInclude Include="utility\utilCommonAPI.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<ClCompile Include="FaceLandmarkVidMulti.cpp" />
<ClCompile Include="utility\iniOperation.cpp">
<Filter>utility</Filter>
</ClCompile>
<ClCompile Include="utility\utilCommonAPI.cpp">
<Filter>utility</Filter>
</ClCompile>
<ClCompile Include="jsonAnalysis.cpp" />
</ItemGroup>
<ItemGroup>
<Filter Include="utility">
<UniqueIdentifier>{3271a844-b793-4e80-bce9-b5bf97041b45}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClInclude Include="utility\iniOperation.h">
<Filter>utility</Filter>
</ClInclude>
<ClInclude Include="utility\utilCommonAPI.h">
<Filter>utility</Filter>
</ClInclude>
<ClInclude Include="CommonStruct.h" />
<ClInclude Include="jsonAnalysis.h" />
</ItemGroup>
</Project>
\ No newline at end of file
// json.cpp : 定义控制台应用程序的入口点。
//
#include "jsonAnalysis.h"
#include <iostream>
std::string GetReqCertificateJson(sReqCertificate &req)
{
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
writer.StartObject();
writer.Key("Image_file");
writer.String(req.Image_file.data());
writer.Key("member_tel");
writer.String(req.member_tel.data());
writer.Key("member_name");
writer.String(req.member_name.data());
writer.Key("authentication_channel");
writer.String(req.authentication_channel.data());
writer.Key("union_id");
writer.String(req.union_id.data());
writer.EndObject();
return buffer.GetString();
}
std::string GetIdentityUserJson(const char* photo)
{
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
writer.StartObject();
writer.Key("Image_file");
writer.String(photo);
writer.EndObject();
return buffer.GetString();
}
sServerResponse GetServerResultData(const char* json)
{
sServerResponse res;
rapidjson::Document document; // 定义一个Document对象
document.Parse(json); // 解析,Parse()无返回值,也不会抛异常
if (document.HasParseError()) // 通过HasParseError()来判断解析是否成功
{
std::cout<<"HasParseError11"<<std::endl;
}
else
{
rapidjson::Value& msg = document["success"];
res.success=msg.GetString();
if ("yes" == res.success) {
if (document.HasMember("results")) {
rapidjson::Value& results = document["results"];
if (results.IsArray()) {
for (unsigned int i = 0; i<results.Size(); i++) {
sUserInfo user;
rapidjson::Value& objValue = results[i];
if (objValue.HasMember("confidence")) {
rapidjson::Value& confidence = objValue["confidence"];
user.confidence = confidence.GetString();
}
if (objValue.HasMember("memberTel")) {
rapidjson::Value& memberTel = objValue["memberTel"];
user.memberTel = memberTel.GetString();
}
if (objValue.HasMember("memberName")) {
rapidjson::Value& memberName = objValue["memberName"];
user.memberName = memberName.GetString();
}
if (objValue.HasMember("authenticationChannel")) {
rapidjson::Value& authenticationChannel = objValue["authenticationChannel"];
user.authenticationChannel = authenticationChannel.GetString();
}
if (objValue.HasMember("unionId")) {
rapidjson::Value& unionId = objValue["unionId"];
user.unionId = unionId.GetString();
}
res.vecUser.push_back(user);
}
}
}
}
else if ("no" == res.success) {
if (document.HasMember("errorMessage")) {
rapidjson::Value& errorMessage = document["errorMessage"];
res.errorMessage = errorMessage.GetString();
}
}
}
return res;
}
int SocketRequestJson(const char* json)
{
int result = 0;
rapidjson::Document document; // 定义一个Document对象
document.Parse(json); // 解析,Parse()无返回值,也不会抛异常
if (document.HasParseError()) // 通过HasParseError()来判断解析是否成功
{
// 可通过GetParseError()取得出错代码,
// 注意GetParseError()返回的是一个rapidjson::ParseErrorCode类型的枚举值
// 使用函数rapidjson::GetParseError_En()得到错误码的字符串说明,这里的En为English简写
// 函数GetErrorOffset()返回出错发生的位置
//LOG_ERROR("GetTakeawayPrintInfo JSON parse error: (%d:%d)", document.GetParseError(), document.GetErrorOffset())
//return false;
}
else
{
rapidjson::Value& fm_cmd = document["fm_cmd"];
result = fm_cmd.GetInt();
}
return result;
}
std::string GetSocketResultJson(const int statuscode, const char* msg, const char* phone)
{
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
writer.StartObject();
writer.Key("statusCode");
writer.Int(statuscode);
writer.Key("msg");
writer.String(msg);
writer.Key("member_id");
writer.String(phone);
writer.EndObject();
return buffer.GetString();
}
\ No newline at end of file
#ifndef JSON_H
#define JSON_H
#include <map>
#include "../rapidjson/rapidjson.h"
#include "../rapidjson/document.h"
#include "../rapidjson/reader.h"
#include "../rapidjson/writer.h"
#include "../rapidjson/stringbuffer.h"
#include "CommonStruct.h"
//#pragma warning(disable:4003)
using namespace rapidjson;
std::string GetReqCertificateJson(sReqCertificate &req);
std::string GetIdentityUserJson(const char* photo);
sServerResponse GetServerResultData(const char* json);
int SocketRequestJson(const char* json);
std::string GetSocketResultJson(const int statuscode, const char* msg, const char* phone);
#endif
///////////////////////////////////////////////////////////////
// Name: ZIni
// Version: 0.1
// Author: zhaobinjie
// Email: zhaobinjie1984@163.com
// Date: 2010-04-29
//
// Description:
// This class provides static functions for writing and
// reading INI files.
///////////////////////////////////////////////////////////////
#include "iniOperation.h"
#include <fstream>
#include <sstream>
#include <cctype>
#include <cstdlib>
bool ZIni::writeString(std::string strSectName,
std::string strKeyName,
std::string strValue,
std::string strFileName)
{
// open INI file
std::ifstream fsIni(strFileName.c_str(),
std::ios_base::in);
// open INI.bak file
std::ofstream fsIniBak((strFileName + ".zbk").c_str(),
std::ios_base::out | std::ios_base::trunc);
// file opened successfully
if (fsIni && fsIniBak)
{
// search section
std::string strLine = "";
std::string strSection = std::string("[") + strSectName + "]";
bool bWritten = false;
while (getline(fsIni, strLine))
{
// remain the others
fsIniBak << strLine << std::endl;
// section found
if (!bWritten && 0 == strSection.compare(trim(strLine)))
{
// search key
while (getline(fsIni, strLine))
{
std::string strTemp = trim(strLine);
// write value to the end of this section
if (strTemp.length() > 0 && '[' == strTemp[0])
{
fsIniBak << strKeyName << " = " << strValue
<< std::endl;
fsIniBak << strLine << std::endl;
bWritten = true;
break;
}
// replace the origin value
if (strTemp.length() > strKeyName.length() &&
0 == strTemp.compare(0,
strKeyName.length(), strKeyName) &&
'=' == strTemp[strKeyName.length()])
{
fsIniBak << strKeyName << " = " << strValue
<< std::endl;
bWritten = true;
break;
}
// remain the others
fsIniBak << strLine << std::endl;
}
// write value
if (!bWritten)
{
fsIniBak << strKeyName << " = " << strValue << std::endl;
bWritten = true;
}
}
}
// write value
if (!bWritten)
{
fsIniBak << strSection << std::endl;
fsIniBak << strKeyName << " = " << strValue << std::endl;
}
// close file stream
fsIni.close();
fsIniBak.close();
}
else
{
return false;
}
// open INI.zbk file
std::ifstream fsIniBakNew((strFileName + ".zbk").c_str(),
std::ios_base::in);
// open INI file
std::ofstream fsIniNew(strFileName.c_str(),
std::ios_base::out | std::ios_base::trunc);
// file opened successfully
if (fsIniBakNew && fsIniNew)
{
std::string strLine = "";
while (getline(fsIniBakNew, strLine))
{
fsIniNew << strLine << std::endl;
}
// close file stream
fsIniBakNew.close();
fsIniNew.close();
}
else
{
return false;
}
return true;
}
bool ZIni::writeInt(std::string strSectName,
std::string strKeyName,
int iValue,
std::string strFileName)
{
// convert int to string
std::stringstream ssValue;
ssValue << iValue;
return writeString(strSectName, strKeyName, ssValue.str(), strFileName);
}
bool ZIni::writeDouble(std::string strSectName,
std::string strKeyName,
double fValue,
std::string strFileName)
{
// convert double to string
std::stringstream ssValue;
ssValue << fValue;
return writeString(strSectName, strKeyName, ssValue.str(), strFileName);
}
std::string ZIni::readString(std::string strSectName,
std::string strKeyName,
std::string strDefault,
std::string strFileName)
{
// open INI file
std::ifstream fsIni(strFileName.c_str(), std::ios_base::in);
// file opened successfully
if (fsIni)
{
// search section
std::string strLine = "";
std::string strSection = std::string("[") + strSectName + "]";
while (getline(fsIni, strLine))
{
// section found
if (0 == strSection.compare(trim(strLine)))
{
// search key
while (getline(fsIni, strLine))
{
std::string strTemp = trim(strLine);
// end of this section
if (strTemp.length() > 0 && '[' == strTemp[0])
{
return strDefault;
}
if (strTemp.length() > strKeyName.length() + 1 &&
0 == strTemp.compare(0,
strKeyName.length(), strKeyName) &&
'=' == strTemp[strKeyName.length()])
{
return (strTemp.substr(strKeyName.length() + 1));
}
}
}
}
}
// read failed
return strDefault;
}
int ZIni::readInt(std::string strSectName,
std::string strKeyName,
int iDefault,
std::string strFileName)
{
// converting between int and string
std::stringstream ssDefault;
ssDefault << iDefault;
return atoi(readString(strSectName, strKeyName,
ssDefault.str(), strFileName).c_str());
}
double ZIni::readDouble(std::string strSectName,
std::string strKeyName,
double fDefault,
std::string strFileName)
{
// converting between double and string
std::stringstream ssDefault;
ssDefault << fDefault;
return atof(readString(strSectName, strKeyName,
ssDefault.str(), strFileName).c_str());
}
//消除字串两段的空格,字串中间的保留
std::string ZIni::trim(std::string &strInput)
{
std::string str(strInput);
if(str.empty())
return str;
str = str.substr(str.find_first_not_of(' '),str.find_last_not_of(' ')+1);
std::string::size_type pos_equations = str.find_first_of('=');
if(pos_equations != std::string::npos)
{
if(pos_equations > 0 && str[pos_equations-1] == ' ')
str.erase(pos_equations-1,1);
pos_equations = str.find_first_of('=');
if(pos_equations < str.size() && str[pos_equations+1] == ' ')
str.erase(pos_equations+1,1);
}
return str;
}
\ No newline at end of file
///////////////////////////////////////////////////////////////
// Name: ZIni
// Version: 0.1
// Author: zhaobinjie
// Email: zhaobinjie1984@163.com
// Date: 2010-04-29
//
// Description:
// This class provides static functions for writing and
// reading INI files.
///////////////////////////////////////////////////////////////
#ifndef ZINI_H
#define ZINI_H
#include <string>
class ZIni
{
public:
ZIni() {}
virtual ~ZIni() {}
public:
// return if succeed or not
static bool writeString(
std::string strSectName, // in. section name
std::string strKeyName, // in. key name
std::string strValue, // in. value to be write
std::string strFileName // in. INI file name
);
// return if succeed or not
static bool writeInt(
std::string strSectName, // in. section name
std::string strKeyName, // in. key name
int iValue, // in. value to be write
std::string strFileName // in. INI file name
);
// return if succeed or not
static bool writeDouble(
std::string strSectName, // in. section name
std::string strKeyName, // in. key name
double fValue, // in. value to be write
std::string strFileName // in. INI file name
);
// return the got string
static std::string readString(
std::string strSectName, // in. section name
std::string strKeyName, // in. key name
std::string strDefault, // in. defaut value if read failed
std::string strFileName // in. INI file name
);
// return the got int
static int readInt(
std::string strSectName, // in. section name
std::string strKeyName, // in. key name
int iDefault, // in. defaut value if read failed
std::string strFileName // in. INI file name
);
// return the got double
static double readDouble(
std::string strSectName, // in. section name
std::string strKeyName, // in. key name
double fDefault, // in. defaut value if read failed
std::string strFileName // in. INI file name
);
private:
static std::string trim(std::string &strInput);
};
#endif //ZINI_H
#include "utilCommonAPI.h"
#include <stdio.h>
#include <stdlib.h>
#include <cstring>
#include <stdarg.h>
#define WIN32
#ifdef WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif
//函数名: GetProcDir()
//功 能: 获取当前程序的路径
std::string GetProcDir()
{
std::string strDir;
#ifdef WIN32
char exeFullPath[MAX_PATH]; // Full path
GetModuleFileNameA(NULL, exeFullPath, MAX_PATH);
strDir = exeFullPath; // Get full path of the file
int pos = strDir.find_last_of('\\', strDir.length());
strDir = strDir.substr(0, pos+1); // Return the directory without the file name
#else
char szBuffer[256];
int npos = 0;
npos = readlink( "/proc/self/exe", szBuffer, 256 );
if ( npos < 0 || npos >= 256 )
{
printf( "readlink failed.\n" );
return strDir;
}
szBuffer[npos] = '\0';
char *ptr = NULL;
char c = '/';
ptr = strrchr(szBuffer,c);
if(ptr != NULL)
*(ptr +1) = 0;
strDir = szBuffer;
#endif
return strDir;
}
#ifdef WIN32
std::string UnicodeToAscii(const std::wstring& wstr) {
// 预算-缓冲区中多字节的长度
int ansiiLen = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, nullptr, 0, nullptr, nullptr);
// 给指向缓冲区的指针变量分配内存
char *pAssii = (char*)malloc(sizeof(char)*ansiiLen);
// 开始向缓冲区转换字节
WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, pAssii, ansiiLen, nullptr, nullptr);
std::string ret_str = pAssii;
free(pAssii);
return ret_str;
}
std::wstring Utf8ToUnicode(const std::string& str) {
// 预算-缓冲区中宽字节的长度
int unicodeLen = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, nullptr, 0);
// 给指向缓冲区的指针变量分配内存
wchar_t *pUnicode = (wchar_t*)malloc(sizeof(wchar_t)*unicodeLen);
// 开始向缓冲区转换字节
MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, pUnicode, unicodeLen);
std::wstring ret_str = pUnicode;
free(pUnicode);
return ret_str;
}
#endif // WIN32
#include <string>
//函数名: GetProcDir()
//功 能: 获取当前程序的路径
std::string GetProcDir();
#ifdef WIN32
#else
void OutputDebugString(const char* lpOutputString);
#endif
#ifdef WIN32
#else //LINUX
#define _DO_NOT_HAVE_S
#endif //WIN32
#ifdef _DO_NOT_HAVE_S //如果没有_s版的函数,则启动如下的替换宏
//#define sprintf_s(buffer,size,format, ...) sprintf(buffer,format,__VA_ARGS__)
#include <stdio.h>
#include <stdarg.h>
int sprintf_s(
char *buffer,
size_t sizeOfBuffer,
const char *format ,...); //这个比较特殊,需要真的去实现
#define memcpy_s(dest,num,src,count) memcpy(dest,src,count)
#define fprintf_s fprintf
#define _strdate_s(buf,num) _strdate(buf)
#define strcat_s(dest,num,src) strcat(dest,src)
#define fopen_s(pf,name,mode) *pf=fopen(name,mode)
#define strncpy_s(dest,num,src,count) strncpy(dest,src,count)
#define localtime_s(tm,time) *tm=*localtime(time)
#define _strdup strdup
#else
#define mkdir(pathname,mode) _mkdir(pathname)
#endif
#ifdef WIN32
std::string UnicodeToAscii(const std::wstring& wstr);
std::wstring Utf8ToUnicode(const std::string& str);
#endif // WIN32
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment