使用face++的API介面-人臉識別
阿新 • • 發佈:2019-01-03
本文地址:http://blog.csdn.net/tiandixuanwuliang/article/details/78018687
本文將介紹如何使用face++的API介面實現人臉識別。
一、獲取face++的API支援
1.1face++官網:https://www.faceplusplus.com.cn/
1.2在face++官網上註冊賬號,填寫開發者資料,如下圖:
二、建立API Key和繫結Bundle ID
2.1在如下圖位置,點選API Key
2.2點選建立API key,按照要求填寫(選擇試用):
2.3繫結應用程式:
至此,我們的準備工作就做好了。我們將會使用API
Key和API
Secret。
三、建立Android工程
3.1建立Android專案。本文使用Fragment+Activity模式,Activity程式碼是簡單的fragment,如下
- package com.wllfengshu.boyandgirl;
- import android.annotation.SuppressLint;
- import android.app.Activity;
- import android.app.FragmentManager;
- import android.app.FragmentTransaction;
- import android.os.Bundle;
- import android.view.View;
- public class MainActivity extends Activity {
- private FragmentManager fm;
- private FragmentTransaction transaction;
- @SuppressLint("NewApi")
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- fm = getFragmentManager();
- transaction = fm.beginTransaction();
- transaction.replace(R.id.ll_fregment, new FaceFragment());
- transaction.commit();
- }
- public void change(View v) {
- transaction = fm.beginTransaction();
- switch (v.getId()) {
- case R.id.ib_main_face:
- transaction.replace(R.id.ll_fregment, new FaceFragment());
- break;
- case R.id.ib_main_gesture:
- transaction.replace(R.id.ll_fregment, new GestureFragment());
- break;
- case R.id.ib_main_other:
- transaction.replace(R.id.ll_fregment, new OtherFragment());
- break;
- }
- transaction.commit();
- }
- }
3.2fragment程式碼如下:(其中封裝的函式會在下文中介紹)
- package com.wllfengshu.boyandgirl;
- import java.io.IOException;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import org.json.JSONException;
- import org.json.JSONObject;
- import android.annotation.SuppressLint;
- import android.app.Fragment;
- import android.content.Intent;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.graphics.Paint;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Message;
- import android.view.LayoutInflater;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.view.ViewGroup;
- import android.widget.Button;
- import android.widget.ImageView;
- import android.widget.TextView;
- import android.widget.Toast;
- import com.wllfengshu.util.Constant;
- import com.wllfengshu.util.DrawUtil;
- import com.wllfengshu.util.GifView;
- import com.wllfengshu.util.HttpUtils;
- import com.wllfengshu.util.ImageUtil;
- @SuppressLint({ "NewApi", "HandlerLeak" })
- public class FaceFragment extends Fragment implements OnClickListener {
- private ImageView iv_face;// 錕矯夥拷選錕斤拷錕酵計�
- private Button ib_face_enter;// 確錕斤拷錕斤拷鈕
- private Button ib_face_choice;// 選錕斤拷圖片錕斤拷鈕錕斤拷錕斤拷圖錕解)
- private TextView tv_face_gender;
- private TextView tv_face_age;
- private TextView tv_face_beauty;
- private Bitmap scalingPhoto;// 點陣圖
- private String gender;// 性別
- private int age;// 年齡
- private int beauty;// 顏值
- private Paint paint;// 畫筆工具
- private View view;
- private GifView gif;
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- view = inflater.inflate(R.layout.fragment_face, container, false);
- iv_face = (ImageView) view.findViewById(R.id.iv_face);
- ib_face_enter = (Button) view.findViewById(R.id.ib_face_enter);
- ib_face_choice = (Button) view.findViewById(R.id.ib_face_choice);
- tv_face_gender = (TextView) view.findViewById(R.id.tv_face_gender);
- tv_face_age = (TextView) view.findViewById(R.id.tv_face_age);
- tv_face_beauty = (TextView) view.findViewById(R.id.tv_face_beauty);
- gif = (GifView) view.findViewById(R.id.gif);
- ib_face_enter.setOnClickListener(this);
- ib_face_choice.setOnClickListener(this);
- paint = new Paint();// 建立畫筆
- scalingPhoto = BitmapFactory.decodeResource(this.getResources(),
- R.drawable.defualt);
- return view;
- }
- @SuppressLint("HandlerLeak")
- private Handler handler = new Handler() {
- @Override
- public void handleMessage(Message msg) {
- String str = (String) msg.obj;
- System.out.println("*******face:" + str);
- if (str.equals("403") || str.equals("400") || str.equals("413")
- || str.equals("500")) {
- Toast.makeText(getActivity(), "Please Try Again",
- Toast.LENGTH_SHORT).show();
- } else {
- try {
- JSONObject resultJSON = new JSONObject(str);
- System.out.println(resultJSON.getString("faces") + "=====");
- if (resultJSON.getString("faces").equals("[]")) {
- Toast.makeText(getActivity(),
- "There is no face picture", Toast.LENGTH_SHORT)
- .show();
- } else {
- @SuppressWarnings("rawtypes")
- List res = DrawUtil.FacePrepareBitmap(resultJSON,
- scalingPhoto, paint, iv_face);
- gender = (String) res.get(0);
- age = (Integer) res.get(1);
- beauty = (Integer) res.get(2);
- System.out.println("------------" + gender + " " + age
- + " " + " " + beauty);
- tv_face_gender.setText("性別:"
- + ImageUtil.getFaceGender(gender));
- tv_face_age.setText("年齡:" + age);
- tv_face_beauty.setText("顏值:" + beauty);
- }
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- gif.setVisibility(View.GONE);// 停止gif
- };
- };
- @Override
- public void onActivityResult(int requestCode, int resultCode, Intent data) {
- if (requestCode == 1) {
- // 錕矯夥拷選錕斤拷錕酵計拷錕斤拷錕斤拷錕斤拷荽錕斤拷錕絛ata錕斤拷
- if (data != null) {
- // 錕矯碉拷圖片錕斤拷路錕斤拷
- String photoPath = ImageUtil.getPhotoPath(getActivity(), data);
- // 錕斤拷錕斤拷
- scalingPhoto = ImageUtil.getScalingPhoto(photoPath);
- // 錕斤拷示圖片
- iv_face.setImageBitmap(scalingPhoto);
- }
- }
- super.onActivityResult(requestCode, resultCode, data);
- }
- @Override
- public void onClick(View v) {
- switch (v.getId()) {
- case R.id.ib_face_choice:
- // 錕斤拷圖錕斤拷
- Intent intent = new Intent();
- intent.setAction(Intent.ACTION_PICK);
- intent.setType("image/*");
- startActivityForResult(intent, 1);// 通錕斤拷氐錕斤拷蚩錕斤拷錕�
- break;
- case R.id.ib_face_enter:
- // 顯示載入動畫
- gif.setVisibility(View.VISIBLE);
- gif.setMovieResource(R.raw.red); // 設定背景gif圖片資源
- String base64ImageEncode = ImageUtil
- .getBase64ImageEncode(scalingPhoto);
- System.out.println(base64ImageEncode);
- // 錕斤拷裝錕斤拷錕斤拷錕斤拷錕斤拷錕斤拷錕�
- final Map<String, Object> map = new HashMap<String, Object>();
- map.put("api_key", Constant.API_KEY);
- map.put("api_secret", Constant.API_SECRET);
- map.put("return_attributes", "gender,age,beauty");
- map.put("image_base64", base64ImageEncode);
- // 錕斤拷錕斤拷錕斤拷錕斤拷錕斤拷錕斤拷
- new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- String result = HttpUtils
- .post(Constant.URL_DETECT, map);
- Message message = new Message();
- message.obj = result;
- handler.sendMessage(message);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }).start();
- break;
- }
- }
- }
上面程式碼說明:fragment頁面中包含兩個按鈕,一個按鈕點選“開啟手機相簿”,一個按鈕點選“確認”。使用者點選確認後,開始把使用者選擇的人臉圖片通過POST請求方式傳送到face++伺服器,等待獲取人臉特徵的資料。其中封裝的POST請求程式碼如下:
- public static String post(String url, Map<String, Object> args) throws IOException {
- URL host = new URL(url);
- HttpURLConnection connection = HttpURLConnection.class.cast(host.openConnection());
- connection.setRequestMethod("POST");
- connection.setDoOutput(true);
- connection.setDoInput(true);
- connection.setUseCaches(false);
- connection.setRequestProperty("Connection", "Keep-Alive");
- connection.setRequestProperty("Charsert", "UTF-8");
- DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
- if (args != null) {
- for (Entry<String, Object> entry : args.entrySet()) {
- String key = entry.getKey();
- Object value = entry.getValue();
- if (value instanceof File) {
- value = new FileInputStream(File.class.cast(value));
- }
- if (value instanceof InputStream) {
- dos.write((key + "=").getBytes());
- InputStream is = InputStream.class.cast(value);
- byte[] data = new byte[is.available()];
- is.read(data);
- dos.write(URLEncoder.encode(Base64.encodeToString(data, data.length), "UTF-8").getBytes());
- is.close();
- } else {
- dos.write((key + "=" + URLEncoder.encode(String.valueOf(value), "UTF-8")).getBytes());
- }
- dos.write("&".getBytes());
- }
- }
- dos.flush();
- dos.close();
- int resultCode = connection.getResponseCode();
- StringBuilder response = new StringBuilder();
- if (resultCode == HttpURLConnection.HTTP_OK) {
- BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
- String line;
- while ((line = br.readLine()) != null) {
- response.append(line);
- }
- br.close();
- } else {
- response.append(resultCode);
- }
- return response.toString();
- }
本文采用把圖片轉換為base64格式進行傳輸,其程式碼如下:
- public static String getBase64ImageEncode(Bitmap myImage) {
- Bitmap bmSmall = Bitmap.createBitmap(myImage, 0, 0, myImage.getWidth(), myImage.getHeight());
- ByteArrayOutputStream stream = new ByteArrayOutputStream();
- bmSmall.compress(Bitmap.CompressFormat.JPEG, 100, stream);
- byte[] arrays = stream.toByteArray();
- // base64 encode
- byte[] encode = Base64.encode(arrays, Base64.DEFAULT);
- String base64Encode = new String(encode);
- return base64Encode;
- }
介面佈局檔案程式碼(activity_main.xml檔案):
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:background="@drawable/bg" >
- <LinearLayout
- android:id="@+id/ll_fregment"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
- </LinearLayout>
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_alignParentBottom="true"
- android:orientation="horizontal" >
- <RadioGroup
- android:layout_width="match_parent"
- android:layout_height="50dp"
- android:orientation="horizontal" >
- <RadioButton
- android:id="@+id/ib_main_face"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:layout_weight="1"
- android:background="@drawable/rb_select"
- android:button="@null"
- android:checked="true"
- android:gravity="center"
- android:onClick="change"
- android:text="人臉識別" />
- <RadioButton
- android:id="@+id/ib_main_gesture"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:layout_weight="1"
- android:background="@drawable/rb_select"
- android:button="@null"
- android:gravity="center"
- android:onClick="change"
- android:text="手勢識別" />
- <RadioButton
- android:id="@+id/ib_main_other"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:layout_weight="1"
- android:background="@drawable/rb_select"
- android:button="@null"
- android:gravity="center"
- android:onClick="change"
- android:text="其他功能" />
- </RadioGroup>
- </LinearLayout>
- </RelativeLayout>
人臉識別介面程式碼:- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent" >
- <TextView
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:gravity="center"
- android:text="人臉識別"
- android:textSize="20sp" />
- <ImageView
- android:id="@+id/iv_face"
- android:layout_width="200dp"
- android:layout_height="300dp"
- android:layout_alignParentTop="true"
- android:layout_centerHorizontal="true"
- android:contentDescription="人臉圖片"
- android:paddingTop="40dp"
- android:src="@drawable/defualt" />
- <LinearLayout
- android:id="@+id/ll_button"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_below="@id/iv_face"
- android:layout_marginLeft="10dp"
- android:layout_marginRight="10dp"
- android:gravity="center_horizontal"
- android:orientation="horizontal" >
- <Button
- android:id="@+id/ib_face_enter"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:background="@drawable/enter"
- android:text="確定" />
- <Button
- android:id="@+id/ib_face_choice"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:background="@drawable/choose"
- android:text="選擇圖片" />
- </LinearLayout>
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_alignParentBottom="true"
- android:layout_below="@id/ll_button"
- android:orientation="horizontal"
- android:paddingTop="20dp" >
- <TextView
- android:id="@+id/tv_face_gender"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_weight="1"
- android:gravity="center"
- android:src="@drawable/ic_launcher"
- android:text="性別"
- android:textSize="20sp" />
- <TextView
- android:id="@+id/tv_face_age"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_weight="1"
- android:gravity="center"
- android:src="@drawable/ic_launcher"
- android:text="年齡"
- android:textSize="20sp" />
- <TextView
- android:id="@+id/tv_face_beauty"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_weight="1"
- android:gravity="center"
- android:src="@drawable/ic_launcher"
- android:text="顏值"
- android:textSize="20sp" />
- </LinearLayout>
- <com.wllfengshu.util.GifView
- android:id="@+id/gif"
- android:layout_width="200dp"
- android:layout_height="200dp"
- android:layout_centerHorizontal="true"
- android:layout_gravity="center_horizontal"
- android:layout_marginTop="60dp"
- android:enabled="false" />
- </RelativeLayout>
人臉識別介面:
本文還有一些其他的封裝函式,由於篇幅問題不一一貼上,請大家自行下載本文程式碼案例:
下載地址:http://download.csdn.net/download/tiandixuanwuliang/9984027