Face++を使用したAPIインタフェース-顔認識
245991 ワード
本住所:http://blog.csdn.net/tiandixuanwuliang/article/details/78018687
ここではface++のAPIインタフェースを用いて顔認識を実現する方法について説明する.
一、face++のAPIサポートを取得する
1.1 face++公式サイト:https://www.faceplusplus.com.cn/
1.2 face++公式サイトにアカウントを登録し、開発者の資料を記入する.以下の図である.
二、API Keyの作成とBundle IDのバインド
2.1下図のような位置で、API Keyをクリックする
2.2 APIキーの作成をクリックし、必要に応じて記入する(試用選択):
2.3アプリケーションのバインド:
これで、私たちの準備はできました.API KeyとAPI Secretを使用します.
三、Androidプロジェクトの作成
3.1 Androidプロジェクトを設立する.本稿ではFragment+Activityモードを用い,Activityコードは以下のように簡単なfragmentである.
ここではface++のAPIインタフェースを用いて顔認識を実現する方法について説明する.
一、face++のAPIサポートを取得する
1.1 face++公式サイト:https://www.faceplusplus.com.cn/
1.2 face++公式サイトにアカウントを登録し、開発者の資料を記入する.以下の図である.
二、API Keyの作成とBundle IDのバインド
2.1下図のような位置で、API Keyをクリックする
2.2 APIキーの作成をクリックし、必要に応じて記入する(試用選択):
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
map =
new HashMap();
-
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
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
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 ):
-
"1.0" encoding=
"utf-8"?>
-
"http://schemas.android.com/apk/res/android"
-
android:layout_width=
"match_parent"
-
android:layout_height=
"match_parent"
-
android:background=
"@drawable/bg" >
-
-
android:id=
"@+id/ll_fregment"
-
android:layout_width=
"match_parent"
-
android:layout_height=
"match_parent"
-
android:orientation=
"vertical" >
-
-
-
android:layout_width=
"match_parent"
-
android:layout_height=
"wrap_content"
-
android:layout_alignParentBottom=
"true"
-
android:orientation=
"horizontal" >
-
-
android:layout_width=
"match_parent"
-
android:layout_height=
"50dp"
-
android:orientation=
"horizontal" >
-
-
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=
" " />
-
-
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=
" " />
-
-
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=
" " />
-
-
-
-
-