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

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 {
            // 创建URL
            URL 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");
    }
	
	
    //获取token
    public static void getToKenTest(){
 
        //使用其测试百度云API---获取token
        //url: http://console.bce.baidu.com/ai 

        String APPID ="****"; //管理中心获得
 
        //百度人体识别应用apikey
        String API_KEY = "****************"; //管理中心获得
 
        //百度人体识别应用sercetkey
        String 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调用API
    public 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包有空再一并上传

发布了89 篇原创文章 · 获赞 58 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/sm16111/article/details/101149252