Face recognition may be one of the most common applications in life under the development of artificial intelligence, which also reflects the maturity of face recognition technology to a certain extent. Baidu Cloud provides an API for face recognition, which can be tried for free. Try it out today.
The first step: registration and login
Create a Baidu account. Log in to the Baidu cloud platform and use our Baidu network disk account.
Step 2: Find and create a facial recognition service
Then click Create App.
After the creation is successful, there will be three key information: APPID, APIKey, Secrect Key
Step 3: Add a face
After entering the application, create a group and user
So now there are two faces in the face database.
Step 4: Create a project and configuration environment
Configure JDK, maven will not talk about it.
Create a maven project, and then add Baidu's SDK into it, that is, introduce Baidu's package in the maven pom file
<dependency>
<groupId>com.baidu.aip</groupId>
<artifactId>java-sdk</artifactId>
<version>4.12.0</version>
</dependency>
Step 5: Coding
import com.baidu.aip.face.AipFace;
import com.baidu.aip.util.Base64Util;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
public class FaceTest {
//需要修改为自己的
private static final String APP_ID = "XXXX";
private static final String API_KEY = "XXXX";
private static final String SECRET_KEY = "XXXx";
static AipFace client = null;
static {
client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
// 可选:设置网络连接参数
client.setConnectionTimeoutInMillis(2000);
client.setSocketTimeoutInMillis(60000);
}
public static void main(String[] args) throws IOException {
//BASE64Decoder decoder = new BASE64Decoder();
String file1 = "/Users/yuchk/Desktop/haha.png";
byte[] img2 = FileToByte(new File(file1));
// 需要填写自己的groupIdList
System.out.println(searchFace(img2, "car"));
}
private static String searchFace(byte[] arg0, String groupIdList) {
String imgStr = Base64Util.encode(arg0);
String imageType = "BASE64";
HashMap<String, String> options = new HashMap<String, String>();
options.put("quality_control", "NORMAL");
options.put("liveness_control", "LOW");
options.put("max_user_num", "1");
JSONObject res = client.search(imgStr, imageType, groupIdList, options);
return res.toString(2);
}
private static byte[] FileToByte(File file) throws IOException {
// 将数据转为流
InputStream content = new FileInputStream(file);
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = content.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
// 获得二进制数组
return swapStream.toByteArray();
}
}
operation result