关于百度ai的人脸检测功能的调用

阅读: 评论:0

关于百度ai的人脸检测功能的调用

关于百度ai的人脸检测功能的调用

首先第一步创建一个应用

然后就会得到他的appid,和apikey还有secretkey

第二步确认你的账号是v几的,就要看v几的文档,注意这是个坑,v3以前的少一个image_type的参数

好的,确认所有东西之后,在去看文档,步骤是先用appid,和apikey还有secretkey来获取到access_token,这个东西可以重复用一个月,拿到了之后就可以调接口了。先附上我的代码

 

工具类,此工具类我是在大佬那里下载的如有侵权请联系删除(是叫工具类嘛,我也不清楚萌新请大佬嘴下留情)

ample.demo.Common;import org.apache.http.*;
import org.apache.http.client.CookieStore;
import org.apache.fig.AuthSchemes;
import org.apache.fig.CookieSpecs;
import org.apache.fig.RequestConfig;
import org.apache.ity.UrlEncodedFormEntity;
import org.apache.hods.CloseableHttpResponse;
import org.apache.hods.HttpGet;
import org.apache.hods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.fig.Registry;
import org.fig.RegistryBuilder;
import org.socket.ConnectionSocketFactory;
import org.socket.PlainConnectionSocketFactory;
import org.ssl.NoopHostnameVerifier;
import org.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.*;
import org.apache.PoolingHttpClientConnectionManager;
import org.ssage.BasicNameValuePair;
import org.apache.http.util.EntityUtils;import javax.ssl.SSLContext;
import javax.ssl.TrustManager;
import javax.ssl.X509TrustManager;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import CertificateException;
import 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 = ate();//请求配置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 = Instance("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 = ute(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 : Set()) {httpPost.Key(), e.getValue());}if (bodys != null) {List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();for (String key : bodys.keySet()) {nameValuePairList.add(new BasicNameValuePair(key, (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 = ute(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 = ute(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 = ate().setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()).setRedirectStrategy(new DefaultRedirectStrategy()).setDefaultCookieStore(cookieStore).setDefaultRequestConfig(requestConfig).build();HttpGet httpGet = new HttpGet(url);CloseableHttpResponse response = null;try {response = ute(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 = ate().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 = ute(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 = Entity();if (entity != null) {result = String(entity, "UTF-8");}} catch (Exception e) {} finally {try {httpResponse.close();} catch (IOException e) {e.printStackTrace();}}return result;}public static void main(String[] args) {//使用其测试百度云API---获取token//url:  APPID = "11656996"; //管理中心获得//百度人脸识别应用apikeyString API_KEY = "Mz2i2t93E1sEBv2k2WKaPhn9"; //管理中心获得//百度人脸识别应用sercetkeyString SERCET_KEY = "8I3WNoNK71hWkCfQBwmcZvMay7YdiPvs "; //管理中心获得//百度人脸识别token 有效期一个月String TOKEN = null;String access_token_url = ".0/token?grant_type=client_credentials"+ "&client_id=" + API_KEY + "&client_secret=" + SERCET_KEY;CloseableHttpResponse response = HttpClientUtils.doHttpsGet(access_token_url, null);System.out.String(response));//得到token = 24.1d786b9cdbdd8ac7cf55d56c7f38372b.2592000.1509244497.282335-10201425}
}

附上第二个

ample.demo.Common;import java.io.*;public class FileUtil {/*** 读取文件内容,作为字符串返回*/public static String readFileAsString(String filePath) throws IOException {File file = new File(filePath);if (!ists()) {throw new FileNotFoundException(filePath);}if (file.length() > 1024 * 1024 * 1024) {throw new IOException("File is too large");}StringBuilder sb = new StringBuilder((int) (file.length()));// 创建字节输入流FileInputStream fis = new FileInputStream(filePath);// 创建一个长度为10240的Bufferbyte[] bbuf = new byte[10240];// 用于保存实际读取的字节数int hasRead = 0;while ( (hasRead = ad(bbuf)) > 0 ) {sb.append(new String(bbuf, 0, hasRead));}fis.close();String();}/*** 根据文件路径读取byte[] 数组*/public static byte[] readFileByBytes(String filePath) throws IOException {File file = new File(filePath);if (!ists()) {throw new FileNotFoundException(filePath);} else {ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());BufferedInputStream in = null;try {in = new BufferedInputStream(new FileInputStream(file));short bufSize = 1024;byte[] buffer = new byte[bufSize];int len1;while (-1 != (len1 = in.read(buffer, 0, bufSize))) {bos.write(buffer, 0, len1);}byte[] var7 = ByteArray();return var7;} finally {try {if (in != null) {in.close();}} catch (IOException var14) {var14.printStackTrace();}bos.close();}}}}

然后最重要的图片转成那个啥64格式的,

ample.demo.Common;import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.HttpURLConnection;
import java.URL;import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;/*** Created by zhangwenchao on 2017/9/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 = InputStream();data = new byte[inStream.available()];ad(data);inStream.close();} catch (IOException e) {e.printStackTrace();}// 对字节数组Base64编码BASE64Encoder encoder = new BASE64Encoder();// 返回Base64编码过的字节数组字符串de(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();// 返回Base64编码过的字节数组字符串de(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();try {// Base64解码byte[] b = decoder.decodeBuffer(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;}}
}

接下来附上我获取access_token的代码

@Controller
@RequestMapping("/AI" )
public class FaceAPITest {//获取token@PostMapping("/token")@ResponseBodypublic static void getToKenTest(){//使用其测试百度云API---获取token//url:  APPID ="x"; //管理中心获得//百度人脸识别应用apikeyString API_KEY = "xx"; //管理中心获得//百度人脸识别应用sercetkeyString SERCET_KEY = "xxx"; //管理中心获得//百度人脸识别token 有效期一个月String TOKEN = null;String access_token_url = ".0/token?grant_type=client_credentials"+"&client_id="+API_KEY +"&client_secret="+SERCET_KEY;CloseableHttpResponse response =  HttpClientUtils.doHttpsGet(access_token_url,null);System.out.String(response));String  ACC_TOKEN&#String(response);//得到token &#xxxxxxxxxxxxxxxxxxxxxxxxxxx.2592000.1536458879.282335-11656996}
}

拿到了之后,直接用这东西调取接口

@Controller
@RequestMapping("/AI" )
public class FaceAPITest {//使用token调用API@PostMapping("/recognition")@ResponseBodypublic static String faceDetecttest() throws IOException {String token = &#xxxxxxxxxxxxxxxxxxxxxxx.2592000.1536458879.282335-11656996";String Filepath = "E:"+ File.separator + "deb60dd02a.jpg";/* String Filepath = OriginalFilename();*/String image = Base64ImageUtils.GetImageStrFromPath(Filepath);String url = ".0/face/v3/detect?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>();String image_type=UUID.randomUUID().toString().replace("-", "");bodys.put("image_type", "BASE64");bodys.put("image", image);bodys.put("face_field","age,beauty,expression");try {CloseableHttpResponse response =HttpClientUtils.doHttpsPost(url,headers,bodys);String jieguo =  String(response);return jieguo;} catch (Exception e) {e.printStackTrace();}return null;}}

好了,返回给前端的是一个,josn字符串,让前端把这个字符串转成js对象,就可以取到了

还有一点要注意这个的参数,是你需要什么,就加什么,具体看百度ai的文档

附上我的maven,其实json那个是没用的,因为我想在后端把json字符串转成对象,然后发现,在前端转比较方便所有就放弃了

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns=".0.0" xmlns:xsi=""xsi:schemaLocation=".0.0 .0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId&le</groupId><artifactId>demo</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>demo</name><description>Demo project for Spring Boot</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.0.4.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>&porting.outputEncoding>UTF-8</porting.outputEncoding><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>com.baidu.aip</groupId><artifactId>java-sdk</artifactId><version>3.2.1</version></dependency><dependency><groupId>com.baidu.aip</groupId><artifactId>java-sdk</artifactId><version>3.2.0</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpcore</artifactId><version>4.4.5</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.6</version></dependency><dependency><groupId>net.sf.json-lib</groupId><artifactId>json-lib</artifactId><version>2.4</version><classifier>jdk15</classifier></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.32</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.33</version></dependency><dependency><groupId>net.sf.json-lib</groupId><artifactId>json-lib</artifactId><version>2.4</version><classifier>jdk15</classifier></dependency><dependency><groupId>org.apachemons</groupId><artifactId>commons-lang3</artifactId><version>3.1</version></dependency><dependency><groupId>commons-beanutils</groupId><artifactId>commons-beanutils</artifactId><version>1.8.3</version></dependency><dependency><groupId>commons-logging</groupId><artifactId>commons-logging</artifactId><version>1.1.1</version></dependency><dependency><groupId>commons-collections</groupId><artifactId>commons-collections</artifactId><version>3.2.1</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

附上我的目录

好了,这样就可以拿到颜值了,附上一张我的运行结果

哎呀我颜值还是可以的嘛,百度的这个东西要求非常严格,我找那些明星的照片也不过80多分,证明我还是很可以的嘻嘻

 

 

本文发布于:2024-01-30 22:43:05,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170662578823355.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:的人   功能   ai
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23