如何开发Java动态人脸识别动态图

借助百度云中的百度人脸识别用java开发一个人脸识别 - CSDN博客
借助百度云中的百度人脸识别用java开发一个人脸识别
demo可以看我的微信小程序。里面是用的腾讯优图和百度人脸检测2个接口
链接的代码是完整的。谢谢
链接: /s/1jICDtYY 密码: bbu3 示例项目下载地址
1.官网文档必须看
2.在管理中心创建应用及查看相关参数 AppID APIKey SecretKey都需要保存起来
3.搬砖测试
项目需要的lib包,基本下载官网的SDK就都会包含。
package com.
public class APIConstants {
public static final String APPID = &管理中心获得&;
public static final String API_KEY = &管理中心获得&;
public static final String SERCET_KEY = &管理中心获得&;
public static final String TOKEN = &为了测试,将生成的key先存一下&;
4.获取AccessToken
官网文档说明/docs#Beginner-Auth
向授权服务地址/oauth/2.0/token发送请求(推荐使用POST),并在URL中带上以下参数:
grant_type: 必须参数,固定为“client_credentials”;client_id: 必须参数,应用的API Key;client_secret: 必须参数,应用的Secret Key;
直接在浏览器GET请求也可以获取:
/oauth/2.0/token?grant_type=client_credentials&client_id=APIKEY&client_secret=SECRETKEY
public class AITest {
public static void main(String[] args) throws Exception {;
String access_token_url = &/oauth/2.0/token?grant_type=client_credentials& +
&&client_id=&+APIContants.API_KEY
+&&client_secret=&+ APIContants.SERCET_KEY;
HttpResponse response = HttpUtils.doPostBD(access_token_url,new HashMap&String, String&(),new HashMap&String, String&());
System.out.println(EntityUtils.toString(response.getEntity()));
{&access_token&:&24.39b6fc97e87058ed6edb92ad482.&,&session_key&:&9mzdCP1XKXZ5yipkl7ubftudl2reGQybIG25NqWi9vqeSFFjxigLFl+WpfDW0PyUt7EP\/Uyn74r31lj3d4kVr4xkbkSk&,&scope&:&public vis-faceverify_faceverify vis-faceattribute_faceattribute wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian wangrantest_test wangrantest_test1 bnstest_test1 bnstest_test2 ApsMisTest_Test\u vis-classify_flower&,&refresh_token&:&25.3c8370eaeb8af4fdbefcef9.11-11111&,&session_secret&:&ffcff19de958e435e6a4&,&expires_in&:2592000}
5.HttpUtils工具类代码
package com.xiaoshuai.baidu.
import java.io.BufferedR
import java.io.DataOutputS
import java.io.InputStreamR
import java.net.HttpURLC
import java.net.URL;
import java.util.L
import java.util.M
* http 工具类
public class HttpUtil {
public static String post(String requestUrl, String accessToken, String params) throws Exception {
String generalUrl = requestUrl + &?access_token=& + accessT
URL url = new URL(generalUrl);
// 打开和URL之间的连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(&POST&);
// 设置通用的请求属性
connection.setRequestProperty(&Content-Type&, &application/x-www-form-urlencoded&);
connection.setRequestProperty(&Connection&, &Keep-Alive&);
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setDoInput(true);
// 得到请求的输出流对象
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(params);
out.flush();
out.close();
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map&String, List&String&& headers = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : headers.keySet()) {
System.out.println(key + &---&& + headers.get(key));
// 定义 BufferedReader输入流来读取URL的响应
BufferedReader in =
if (requestUrl.contains(&nlp&))
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), &GBK&));
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), &UTF-8&));
String result = &&;
String getL
while ((getLine = in.readLine()) != null) {
result += getL
in.close();
System.out.println(&result:& + result);
6.检测人脸美丑及年龄
/docs#FACE官网文档
base64编码后的图片数据,图片大小不超过2M。
max_face_num
最多处理人脸数目,默认值1
face_fields
包括age,beauty,expression,faceshape,gender,glasses,landmark,race,qualities信息,逗号分隔,默认只返回人脸框、概率和旋转角度。
access_token
通过API Key和Secret Key获取的access_token,参考“”
Header如下:
Content-Type
application/x-www-form-urlencoded
Body中数据如下:
图像base64编码
max_face_num
非必填,默认1
face_fields
API调用方式
package com.xiaoshuai.
import java.io.IOE
import java.net.URLE
import java.util.HashM
import org.json.JSONO
import com.baidu.aip.face.AipF
import com.baidu.aip.http.AipR
public class
public static void main(String[] args) throws Exception {
/****************/
String Filepath = &G:/test2.jpg&;
String image = Base64Util.encode(FileUtil.readFileByBytes(Filepath));
String url = &/rest/2.0/face/v1/detect&;
String params =
URLEncoder.encode(&image&, &UTF-8&) + &=& + URLEncoder.encode(image, &UTF-8&)+&&face_fields=age,beauty,expression,gender,glasses,race,qualities&;
HttpUtil httpUtil = new HttpUtil();
String result = httpUtil.post(url, &你自己获取的accessToken&, params);
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
7.返回JSON字符串内容
age 年龄& (目前官网还是没有说明年龄的误差范围)
beauty 美丑分数 0-100 越大值越美(之前官网写的是0-1在我发现错误时,提交官网,官网及时做了修改)
如花识别年龄38& 美丑评分21& 表示不太合理
&result&: [{
&expression&: 0,
&face_probability&: 1,
&glasses&: 0,
&location&: {
&height&: 155,
&width&: 136,
&left&: 103,
&beauty&: 21.,
&race&: &yellow&,
&expression_probablity&: 0.38,
&rotation_angle&: 9,
&yaw&: 2.7,
&roll&: 10.,
&qualities&: {
&completeness&: 0,
&occlusion&: {
&left_eye&: 0,
&chin&: 0,
&mouth&: 0,
&right_cheek&: 0,
&left_cheek&: 0,
&nose&: 0,
&right_eye&: 0
&blur&: 0,
&cartoon&: 0.2252,
&human&: 0.42
&illumination&: 0
&gender_probability&: 0.14,
&age&: 37.,
&gender&: &male&,
&glasses_probability&: 0.05,
&race_probability&: 0.73,
&pitch&: -17.
&result_num&: 1,
public class Sample {
public static void main(String[] args) {
&& &&&& //初始化一个FaceClient
&& &&& &AipFace face = new AipFace(&appid&,&apikey&,&secretkey&);
&& &&& &//可选:设置网络连接参数
&& &&& &face.setConnectionTimeoutInMillis(60000);
&& &&& &face.setSocketTimeoutInMillis(60000);
&& &&& &//调用API
&& &&& &HashMap map = new HashMap();
&& &&& &//
&& &&& &map.put(&face_fields&, &age,beauty,expression,gender,glasses,race,qualities&);
&& &&& &String path = &G:/test2.jpg&;
&& &&& &AipRequest aipRequest = new AipRequest();
&& &&& &aipRequest.setBody(map);
&& &&& &JSONObject result = face.detect(FileUtil.readFileByBytes(path),map);
&& &&& &System.out.println(result.toString(2));
以上就是百度人脸识别API的调用测试流程及demo
阿里云人脸识别API内容很少。返回只有简单的数据。不如百度的全面。
还有一点。
阿里云的是1分钱购买。 100000一共就这么多请求次数。
百度不要钱,按天算请求次数。但是不保证并发。
综上百度API可以考虑入手学习一下。绝非广告。
开源中国与CSDN是同一个博主不存在转载哦
/forum 想了解。可以去百度的论坛咨询
本文已收录于以下专栏:
相关文章推荐
开源的,开箱即用的人脸识别认证java sdk。
import org.opencv.core.C
import org.opencv.core.M
import org.opencv.core.MatOfR
import or...
使用百度AI的人脸识别库,做出的调用示例,其中filePath是图片的路径,可以自行传入一张图片,进行识别。
下载baidu-aip这个库,可以直接使用pip下载:pip install baidu...
如何通过一张图片,找到另一张图片?
     对于搜索引擎而言,寻找图片之间的内在联系,与常见的关键词搜索并没有本质区别——都是通过关键特征的比对,按照一定的逻辑规则完成匹配。然而不同之处也是显而易...
他的最新文章
讲师:何宇健
讲师:董岩
您举报文章:
举报原因:
原文地址:
原因补充:
(最多只允许输入30个字)博客分类:
本例程是识别图片中的人脸,并画出识别出的人脸的位置。在网上找了很久,用java实现人脸识别技术很难找到。多是依靠JNI 调用OpenCV本地方法实现的。那么这里先来说说这种方法:
先认识一下JNI 和OpenCV
JNI是Java Native 的缩写,中文为JAVA本地调用。从1.1开始,Java Native Interface (JNI)标准成为java平台的一部分,它允许Java代码和其他语言写的代码进行交互。
OpenCV是Intel公司支持的开源计算机视觉库。它轻量级而且高效——由一系列 C 函数和少量 C++ 类构成,实现了图像处理和计算机视觉方面的很多通用算法。
将源代码中的dll文件(cv097.dll,cxcore097.dll,highgui097.dll,JNI2OpenCV.dll)放入C:\WINDOWS\system32目录下。
现在开始上源码:
public class JNIOpenCV{
public JNIOpenCV() {}
System.out.println("开始加载JNI2OpenCV.dll");
System.loadLibrary("JNI2OpenCV");
System.out.println("加载完成");
// 加载动态链接库
public native int[] detectFace(int minFaceWidth, int minFaceHeight, String cascade, String filename);
// 声明本地方法
public class FaceDetection {
private JNIOpenCV myJNIOpenCV;
public FaceDetection(String intputFileName,String outputFileName) {
myJNIOpenCV = new JNIOpenCV();
String filename = intputFileN
String outputFilename = outputFileN
String cascade = "F:\\detectface\\xml\\haarcascade_frontalface_alt2.xml";
int[] detectedFaces = myJNIOpenCV.detectFace(40, 40, cascade, filename);
int numFaces = detectedFaces.length / 4;
if(numFaces & 0){
System.out.println("有脸!有 "+ numFaces + " 张脸");
System.out.println("没有脸!");
for (int i = 0; i & numF i++) {
System.out.println("Face " + i + ": " + detectedFaces[4 * i + 0] + " " + detectedFaces[4 * i + 1] + " " + detectedFaces[4 * i + 2] + " " + detectedFaces[4 * i + 3]);
int[][] RectInt=new int[numFaces][4];
for (int i = 0; i & numF i++)
RectInt[i][0]=detectedFaces[4 * i + 0];
RectInt[i][1]=detectedFaces[4 * i + 1];
RectInt[i][2]=detectedFaces[4 * i + 2];
RectInt[i][3]=detectedFaces[4 * i + 3];
if(new DrawInImg(filename,outputFilename,RectInt).DrawRect())
System.out.println("File create success ! ");
System.out.println("File create error ! ");
public static void main(String args[]) {
FaceDetection myFaceDetection = new FaceDetection("F:\\detectface\\image\\tt.jpg","F:\\detectface\\image\\tt2.jpg");
import java.awt.C
import java.awt.G
import java.awt.image.BufferedI
import java.io.F
import java.io.FileInputS
import java.io.FileOutputS
import java.io.IOE
import javax.imageio.ImageIO;
public class DrawInImg {
private boolean isDone =
private String inputFileName = "";
private String outputFileName = "";
private int[][] RectI
public DrawInImg(String inputFileName, String outputFileName,
int[][] RectInt) {
this.inputFileName = inputFileN
this.outputFileName = outputFileN
this.RectInt = RectI
public boolean DrawRect() {
FileInputStream fis = new FileInputStream(inputFileName);
FileOutputStream fos = new FileOutputStream(outputFileName);
BufferedImage img = ImageIO.read(fis);
Graphics g = img.getGraphics();
g.setColor(Color.GREEN);
for (int i = 0; i & RectInt. i++) {
for (int j = 0; j & RectInt[i]. j++) {
g.drawRect(RectInt[i][0], RectInt[i][1], RectInt[i][2],
RectInt[i][3]);
// System.out.print(RectInt[i][j]+" ");
System.out.print("\r\n");
img.flush();
g.dispose();
ImageIO.write(img, "JPG", fos);
while (true) {
if (new File(outputFileName).exists()) {
this.isDone =
} catch (IOException ioe) {
return this.isD
注意:以上代码不能放在包下面,否则会运行不成功的。(原因是dll编译的时候没有带上包,如需包还需重新编译dll)。
下载次数: 500
相关知识库:
浏览: 11283 次
来自: 上海
找了很多很多很多的资料,就LZ这篇写得明白,让我这个菜鸟恍然大 ...
总感觉这种方式不好,把userId写死,我如果想想实现类似we ...
Reset 写道还是websocket吧人家客户还是用的IE6 ...
还是websocket吧
Reset 写道ajax-pushlet-client.js是 ...
(window.slotbydup=window.slotbydup || []).push({
id: '4773203',
container: s,
size: '200,200',
display: 'inlay-fix'匿名用户不能发表回复!|
每天回帖即可获得10分可用分!小技巧:
你还可以输入10000个字符
(Ctrl+Enter)
请遵守CSDN,不得违反国家法律法规。
转载文章请注明出自“CSDN(www.csdn.net)”。如是商业用途请联系原作者。}

我要回帖

更多关于 android 动态人脸识别 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信