1. 程式人生 > >c++實現Face++ API的呼叫

c++實現Face++ API的呼叫

1.Face++ API

Face++提供人臉相關技術的線上API服務給開發者使用,API 地址:http://www.faceplusplus.com.cn/。在使用Face++的線上API之前,肯定是要進行開發者註冊申請的,申請完以後Face++會給開發者提供一個API Key和Secret Key,在後期的伺服器通訊時會用到兩個Key。

2.呼叫說明

以Face++人臉檢測為例,輸入引數分別是:

       api_key(App的Face++ API Key);

       api_secret(APP的Face++ API Secret);

       img[POST](待檢測圖片的URL 或者 通過POST方法上傳的二進位制資料,原始圖片大小需要小於1M);

返回資料為JSON格式的人臉的性別(gender), 年齡(age), 種族(race), 微笑程度(smiling), 眼鏡(glass)和姿勢(pose)等屬性。呼叫之前需安裝安裝libcurl和jsoncpp下圖為呼叫示例。

3.程式碼實現

#include<opencv2/opencv.hpp>
#include<iostream>
#include<vector>
#include<string>
#include <curl/curl.h>
#include "json.h"


using namespace std;
using namespace cv;

#define POSTURL  "http://apicn.faceplusplus.com/v2/detection/detect?api_key=06e4c8b1b3254eb2769d337457b8efac&api_secret=your=glass,pose,gender,age,race,smiling"

int writer(char *data, size_t size, size_t nmemb, string *writerData)
{
	if (writerData == NULL)
		return 0;
	int len = size*nmemb;
	writerData->append(data, len);
	return len;
}

int main()
{
	Mat img = imread("1.bmp");

	vector<uchar> vec_Img;

	vector<int> vecCompression_params;
	vecCompression_params.push_back(CV_IMWRITE_JPEG_QUALITY);
	vecCompression_params.push_back(90);
	imencode(".jpg", img, vec_Img, vecCompression_params);

	CURL *curl;
	CURLcode res;
	
	string buffer;

	struct curl_slist *http_header = NULL;

	curl = curl_easy_init();

	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writer);
	curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);

	struct curl_httppost *formpost = 0;
	struct curl_httppost *lastptr = 0;
	curl_formadd(&formpost, &lastptr, CURLFORM_PTRNAME, "img", CURLFORM_BUFFER, "imgdata", CURLFORM_BUFFERPTR, vec_Img.data(), CURLFORM_BUFFERLENGTH, vec_Img.size(), CURLFORM_END);
	curl_easy_setopt(curl, CURLOPT_URL, POSTURL);
	curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);   

	res = curl_easy_perform(curl);

	curl_easy_cleanup(curl);


	Json::Value root;
	Json::Reader reader;
	bool parsingSuccessful = reader.parse(buffer, root);

	if (!parsingSuccessful)
	{
		cout << "Failed to parse the data!" << endl;
		exit(0);
	}

	cout << buffer << endl;

	waitKey(0);
	return 0;
}



參考文獻