Java调用百度AI实现人体属性分析

好久没有更新了...闲来无事发一下模仿百度AI的人体属性分析。

百度AI效果图如下:

本人开发效果图如下:

界面大家可以忽略........下面讲讲代码实现

1、Base64ImageUtils.java   实现图片解码功能

package com.lzw.utils;import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;import java.util.Base64.Encoder;
import java.util.Base64;
import java.util.Base64.Decoder;/*** Created by lzw on 2019/8/29.* 本地或者网络图片资源转为Base64字符串*/
public class Base64ImageUtils {/*** @Title: GetImageStrFromUrl* @Description: 将一张网络图片转化成Base64字符串* @param imgURL 网络资源位置* @return Base64字符串*/public static String GetImageStrFromUrl(String imgURL) {byte[] data = null;try {// 创建URLURL url = new URL(imgURL);// 创建链接HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("GET");conn.setConnectTimeout(5 * 1000);InputStream inStream = conn.getInputStream();data = new byte[inStream.available()];inStream.read(data);inStream.close();} catch (IOException e) {e.printStackTrace();}// 对字节数组Base64编码//BASE64Encoder encoder = new BASE64Encoder();Encoder encoder = Base64.getEncoder();// 返回Base64编码过的字节数组字符串// return encoder.encode(data);return encoder.encodeToString(data);}/*** @Title: GetImageStrFromPath* @Description: (将一张本地图片转化成Base64字符串)* @param imgPath* @return*/public static String GetImageStrFromPath(String imgPath) {InputStream in = null;byte[] data = null;// 读取图片字节数组try {in = new FileInputStream(imgPath);data = new byte[in.available()];in.read(data);in.close();} catch (IOException e) {e.printStackTrace();}// 对字节数组Base64编码//BASE64Encoder encoder = new BASE64Encoder();Encoder encoder = Base64.getEncoder();// 返回Base64编码过的字节数组字符串// return encoder.encode(data);return encoder.encodeToString(data);}/*** @Title: GenerateImage* @Description: base64字符串转化成图片* @param imgStr* @param imgFilePath  图片文件名,如“E:/tmp.jpg”* @return*/public static boolean saveImage(String imgStr,String imgFilePath) {if (imgStr == null) // 图像数据为空return false;// BASE64Decoder decoder = new BASE64Decoder();Decoder decoder = Base64.getDecoder();try {// Base64解码//byte[] b = decoder.decodeBuffer(imgStr);byte[] b = decoder.decode(imgStr);for (int i = 0; i < b.length; ++i) {if (b[i] < 0) {// 调整异常数据b[i] += 256;}}// 生成jpeg图片OutputStream out = new FileOutputStream(imgFilePath);out.write(b);out.flush();out.close();return true;} catch (Exception e) {return false;}}
}

2、HttpClientUtils.java   自己编写调用百度API 接口工具类

package com.lzw.utils;import org.apache.http.*;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.*;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;/*** HttpClient4.5.X实现的工具类* 可以实现http和ssl的get/post请求*/
public class HttpClientUtils{//创建HttpClientContext上下文private static HttpClientContext context = HttpClientContext.create();//请求配置private static RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(120000).setSocketTimeout(60000).setConnectionRequestTimeout(60000).setCookieSpec(CookieSpecs.STANDARD_STRICT).setExpectContinueEnabled(true).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST)).setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();//SSL的连接工厂private static SSLConnectionSocketFactory socketFactory = null;//信任管理器--用于ssl连接private static TrustManager manager = new X509TrustManager() {public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}public X509Certificate[] getAcceptedIssuers() {return null;}};//ssl请求private static void enableSSL() {try {SSLContext sslContext = SSLContext.getInstance("TLS");sslContext.init(null, new TrustManager[]{manager}, null);socketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (KeyManagementException e) {e.printStackTrace();}}/*** https get请求* @param url* @param data* @return* @throws IOException*/public static CloseableHttpResponse doHttpsGet(String url, String data){enableSSL();Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", socketFactory).build();PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig).build();HttpGet httpGet = new HttpGet(url);CloseableHttpResponse response = null;try {response = httpClient.execute(httpGet, context);}catch (Exception e){e.printStackTrace();}return response;}/*** https post请求 参数为名值对* @param url* @param headers* @param bodys* @return* @throws IOException*/public static CloseableHttpResponse doHttpsPost(String url, Map<String, String> headers, Map<String, String> bodys) {enableSSL();Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", socketFactory).build();PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig).build();HttpPost httpPost = new HttpPost(url);for (Map.Entry<String, String> e : headers.entrySet()) {httpPost.addHeader(e.getKey(), e.getValue());}if (bodys != null) {List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();for (String key : bodys.keySet()) {nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));}UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, Consts.UTF_8);formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");httpPost.setEntity(formEntity);}CloseableHttpResponse response = null;try {response = httpClient.execute(httpPost, context);}catch (Exception e){}return response;}/*** https post请求 参数为名值对* @param url* @param values* @return* @throws IOException*/public static CloseableHttpResponse doHttpsPost(String url, List<NameValuePair> values) {enableSSL();Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", socketFactory).build();PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig).build();HttpPost httpPost = new HttpPost(url);UrlEncodedFormEntity entity = new UrlEncodedFormEntity(values, Consts.UTF_8);httpPost.setEntity(entity);CloseableHttpResponse response = null;try {response = httpClient.execute(httpPost, context);}catch (Exception e){}return response;}/*** http get* @param url* @param data* @return*/public static CloseableHttpResponse doGet(String url, String data) {CookieStore cookieStore = new BasicCookieStore();CloseableHttpClient httpClient = HttpClientBuilder.create().setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()).setRedirectStrategy(new DefaultRedirectStrategy()).setDefaultCookieStore(cookieStore).setDefaultRequestConfig(requestConfig).build();HttpGet httpGet = new HttpGet(url);CloseableHttpResponse response = null;try {response = httpClient.execute(httpGet, context);}catch (Exception e){}return response;}/*** http post** @param url* @param values* @return*/public static CloseableHttpResponse doPost(String url, List<NameValuePair> values) {CookieStore cookieStore = new BasicCookieStore();CloseableHttpClient httpClient = HttpClientBuilder.create().setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()).setRedirectStrategy(new DefaultRedirectStrategy()).setDefaultCookieStore(cookieStore).setDefaultRequestConfig(requestConfig).build();HttpPost httpPost = new HttpPost(url);UrlEncodedFormEntity entity = new UrlEncodedFormEntity(values, Consts.UTF_8);httpPost.setEntity(entity);CloseableHttpResponse response = null;try {response = httpClient.execute(httpPost, context);}catch (Exception e){}return response;}/*** 直接把Response内的Entity内容转换成String** @param httpResponse* @return*/public static String toString(CloseableHttpResponse httpResponse) {// 获取响应消息实体String result = null;try {HttpEntity entity = httpResponse.getEntity();if (entity != null) {result = EntityUtils.toString(entity,"UTF-8");}}catch (Exception e){}finally {try {httpResponse.close();} catch (IOException e) {e.printStackTrace();}}return result;}

3、BodyAPITest.java

package com.lzw.test;import org.apache.http.client.methods.CloseableHttpResponse;import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;import com.lzw.bean.Attribute;
import com.lzw.bean.AttributeList;
import com.lzw.bean.Location;
import com.lzw.utils.Base64ImageUtils;
import com.lzw.utils.HttpClientUtils;import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;import javax.imageio.ImageIO;public class BodyAPITest {//public static String token;public static String path_out = "src/main/webapp/image/image0.jpg";public static int image_num = 1;public static void main(String[] args) throws IOException {//getToKenTest() ;faceDetecttest("D:/photo/smoke.jpg");}//获取tokenpublic static void getToKenTest(){//使用其测试百度云API---获取token//url: http://console.bce.baidu.com/ai String APPID ="****"; //管理中心获得//百度人体识别应用apikeyString API_KEY = "****************"; //管理中心获得//百度人体识别应用sercetkeyString SERCET_KEY = "*****************"; //管理中心获得//百度人体识别token 有效期一个月String TOKEN = null;String access_token_url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials"+"&client_id="+API_KEY +"&client_secret="+SERCET_KEY;CloseableHttpResponse response =  HttpClientUtils.doHttpsGet(access_token_url,null);// token = HttpClientUtils.toString(response);System.out.println(HttpClientUtils.toString(response));//得到token = 24.872f6e00253c3e524432fb1d2acb2ff0.2592000.1566020183.282335-16656258}//使用token调用APIpublic static void faceDetecttest(String Filepath){System.out.println("start");String token = "24.e55420e9a77ef19e6971f2f880794ca6.2592000.1568985224.282335-16656258";//String Filepath = "D:/photo/smoke.jpg";//System.out.println("111");String image = Base64ImageUtils.GetImageStrFromPath(Filepath);//System.out.println("222");String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/body_attr?access_token="+token;Map<String, String> headers = new HashMap<String, String>();headers.put("Content-Type", "application/x-www-form-urlencoded");Map<String, String> bodys = new HashMap<String, String>();bodys.put("image", image);//bodys.put("face_fields", "gender,age");String msg = null;try {CloseableHttpResponse response =  HttpClientUtils.doHttpsPost(url,headers,bodys);//System.out.println("33333");msg = HttpClientUtils.toString(response);System.out.println(msg);} catch (Exception e) {e.printStackTrace();}}}

在控制台就可以看到从百度AI调回来的信息,要进一步操作的话就需要对这么信息进行json解析 这个就不详细讲了有需要的评论区留言吧  项目需要的jar包有空再一并上传

Java调用百度AI实现人体属性分析相关推荐

  1. java调用百度AI实现图文识别功能

    一.创建百度应用 1.在浏览器输入网址https://login.bce.baidu.com/或者百度搜索'百度ai'点击第一个.点击主页的产品服务,看到文字识别.如下图所示: 2.点击创建应用 创建 ...

  2. Java调用百度AI开放平台API

    百度AI开放平台 百度AI开放平台是全球领先的人工智能服务平台,面向开发者及企业开放120多项全球领先的AI能力和软硬一体组件,并提供 EasyDL定制化训练平台.对话系统开发平台UNIT.自定义模板 ...

  3. 关于百度AI 图像识别 人体识别 调用API的简单实践

    title: 关于百度AI 图像识别 人体识别 调用API的简单实践 author: HardyDragon tags: 图像识别 有关图像识别 来到控制台创建相关应用,有一些API每天有免费的调用次 ...

  4. python爬虫爬取股票评论,调用百度AI进行语义分析, matlab观察股票涨跌和评论的关系

    文章自己写的,代码自己调试的,但是思想是拿来的哈哈,不能叫严格意义上的 原创哦 一.爬股票的评论 环境:win7 aconda2python2.7,pycharm3.5 professional 1. ...

  5. 调用百度AI接口实现图片文字识别

    一.准备阶段 进入百度AI网址点击这里跳转 ,点击导航栏的开放能力 ---- 文字识别 ---- 通用文字识别,进入文字识别OCR界面. 在文字识别ORC界面点击 技术文档 进入帮助文档. 在左侧可以 ...

  6. 调用百度ai接口实现图片文字识别详解

    调用百度ai接口实现图片文字识别详解 首先先介绍一下这篇博文是干嘛的,为了不浪费大家时间.公司最近和短视频公司合作,需要监控app的截图上的文字是否符合规范,也就是确保其没有违规的文字.到网上找了一些 ...

  7. Java使用百度AI实现识别身份证照片信息,根据身份证号码,获取相关个人信息

    Java使用百度AI实现识别身份证照片信息 百度智能云-登录 1.登录百度智能云,选择文字识别,创建相关信息 2.获取APP_ID.API_KEY.SECRET_KEY 核心处理代码 import c ...

  8. Java调用百度API实现图像识别

    Java调用百度API实现图像识别 最近在做一个关于识别的小功能,翻阅了一堆资料,也实践自己去实现这个功能,最后识别的结果不是那么理想.这里介绍一个完全可以商用以及识别率超高的百度ai接口 1.为什么 ...

  9. python调用百度AI对颜值评分

    上一篇文章介绍了应用百度AI的文字识别功能对身份证进行识别.本文介绍应用百度AI的人脸识别功能对年龄.性别.颜值等进行识别,感兴趣的朋友一起来看看效果吧.由于安装baidu-aip模块和获取百度AI接 ...

最新文章

  1. php 2 往数据库添加数据
  2. 《Java8实战》-第六章读书笔记(用流收集数据-01)
  3. java输出数组中出现的次数最多的那个及次数
  4. mvn如何执行java代码
  5. DNS枚举工具DNSenum
  6. 用javascript伪造太阳系模型系统
  7. oracle 12c dg新特性,Oracle 12c DG新特性---一键switchover
  8. 可编程ic卡 通用吗_8255可编程IC
  9. Token Based Authentication using ASP.NET Web API 2, Owin, and Identity
  10. 轻量级动态线程池才是“王道”?
  11. jquery 里 $(this)的用法
  12. centos7配置静态ip地址
  13. 深度学习大厂前端项目开发全流程全流程
  14. hdfs--Structured Streaming--console案例
  15. 吞食天地2重制版巫妖王panny版存档_11年前的冷饭—Nintendo 任天堂 Switch《宵星传奇 重制版》评测...
  16. 小明左手拿着纸牌黑桃10,右手拿着纸牌红桃8, 现在交换手中的牌, 用程序模拟实现的过程, 并输出交换前后手中的纸牌的结果
  17. AdGuard免费的电脑手机广告拦截程序
  18. 3D游戏建模教程:Maya如何隐藏灯光
  19. Python环境搭建之OpenCV
  20. 设计多媒体计算机的选配方案,多媒体教室设计方案的选择与管理

热门文章

  1. python日历下拉框_c#教程之C#日历样式的下拉式计算器实例讲解
  2. 最新总结Spring知识及常见面试题
  3. 中地恒达无线倾角加速度计
  4. android没有无线显示器,手机的无线显示器在哪?安卓手机在哪儿?
  5. 5分钟教你做一个WebView广告过滤器
  6. pythonqq交流群_使用 Python 获取 QQ 群投票数据
  7. 面试必考的:并发和并行有什么区别?
  8. 星际争霸pymarl的环境搭建(pymarl+smac)
  9. 实例甜点 Unreal Engine 4迷你教程(4)之用C++实现添加子Widget到VerticalBox中以及ClearChildren...
  10. 【华为云技术分享】10分钟快速在华为云鲲鹏弹性云服务器上部署一个自己的弹幕网站!