日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

Java后端 + 百度SDK实现人脸识别

發布時間:2025/3/12 java 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java后端 + 百度SDK实现人脸识别 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Java后端 + 百度SDK實現人臉識別

人工智能越來越貼近我們的生活,相信大家也經常接觸到人臉識別,手機付款、app注冊驗證、門禁等等。

如果要用Java后臺使用這些功能,那么需要怎么做呢?請看完下面這篇文章,就能輕松、簡單入門了!

手把手教你實現人臉識別、人臉對比

  • 注冊百度賬號 https://ai.baidu.com/
    打開網站,注冊百度賬號并登錄。然后按圖1的提示進行操作。
    在圖1中,選擇 “人臉檢測” 跳轉到 圖2。
    在圖2中 點擊 “立即使用” 然后跳轉到 圖3。
    在圖3中 點擊“創建應用” 然后跳轉到 圖4.
    在圖4中 完成應用申請 然后就有了圖5(我們最終需要的就是這個 剛創建應用的參數AppID等)
  • 圖1:
    圖2:

    圖3:

    圖4:

    圖5:

  • Java SDK 文檔地址:https://ai.baidu.com/docs#/Face-Java-SDK/top
    這里有詳細的API文檔。
  • pom.xml 配置:
  • <dependency><groupId>com.baidu.aip</groupId><artifactId>java-sdk</artifactId><version>4.10.0</version></dependency>
  • 人臉識別java類
    下面的 APPID/AK/SK 改成你的,找2張人像圖片在線生成Base64然后復制在下面就可以測試了。
  • import com.baidu.aip.face.AipFace; import com.baidu.aip.face.MatchRequest; import org.apache.commons.codec.binary.Base64; import org.json.JSONObject;import java.util.ArrayList; import java.util.HashMap;public class FaceTest {//設置APPID/AK/SKprivate static String APP_ID = "改成你的圖5中的參數";private static String API_KEY = "改成你的圖5中的參數";private static String SECRET_KEY = "改成你的圖5中的參數";public static void main(String[] args) {// 初始化一個AipFaceAipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);// 可選:設置網絡連接參數client.setConnectionTimeoutInMillis(2000);client.setSocketTimeoutInMillis(60000);// 可選:設置代理服務器地址, http和socket二選一,或者均不設置 // client.setHttpProxy("proxy_host", proxy_port); // 設置http代理 // client.setSocketProxy("proxy_host", proxy_port); // 設置socket代理/** START 獲取讀取 圖片Base64編碼 **/// 方法一:String image1 = "找一張有人臉的圖片,在線圖片生成Base64編碼 然后復制到這里";String image2 = "找一張有人臉的圖片,在線圖片生成Base64編碼 然后復制到這里";// 方法二:/*// 讀本地圖片byte[] bytes = FileUtils.fileToBytes("D:\\Documents\\Pictures\\fc.jpg");byte[] bytes2 = FileUtils.fileToBytes("D:\\Documents\\Pictures\\fj.jpg");// 將字節轉base64String image1 = Base64.encodeBase64String(bytes);String image2 = Base64.encodeBase64String(bytes2);*//** END 獲取讀取 圖片Base64編碼 **/// 人臉對比// image1/image2也可以為url或facetoken, 相應的imageType參數需要與之對應。MatchRequest req1 = new MatchRequest(image1, "BASE64");MatchRequest req2 = new MatchRequest(image2, "BASE64");ArrayList<MatchRequest> requests = new ArrayList<MatchRequest>();requests.add(req1);requests.add(req2);JSONObject res = client.match(requests);System.out.println(res.toString(2));// 人臉檢測// 傳入可選參數調用接口HashMap<String, String> options = new HashMap<String, String>();options.put("face_field", "age");options.put("max_face_num", "2");options.put("face_type", "LIVE");options.put("liveness_control", "LOW");JSONObject res2 = client.detect(image1, "BASE64", options);System.out.println(res2.toString(2));} }

    上面方法二中的相關類:

    Base64.encodeBase64String(bytes) 來自 import org.apache.commons.codec.binary.Base64;
    FileUtils.fileToBytes(“D:\Documents\Pictures\fc.jpg”);
    FileUtils類 如下:

    package com.weixin.demo.utils;import org.slf4j.Logger; import org.slf4j.LoggerFactory;import java.io.*;public class FileUtils {protected static Logger logger = LoggerFactory.getLogger(FileUtils.class);public static byte[] fileToBytes(String filePath) {byte[] buffer = null;File file = new File(filePath);FileInputStream fis = null;ByteArrayOutputStream bos = null;try {fis = new FileInputStream(file);bos = new ByteArrayOutputStream();byte[] b = new byte[1024];int n;while ((n = fis.read(b)) != -1) {bos.write(b, 0, n);}buffer = bos.toByteArray();} catch (FileNotFoundException ex) {ex.printStackTrace();logger.error("", ex);} catch (IOException ex) {ex.printStackTrace();logger.error("", ex);} finally {try {if (null != bos) {bos.close();}} catch (IOException ex) {ex.printStackTrace();logger.error("", ex);} finally {try {if (null != fis) {fis.close();}} catch (IOException ex) {ex.printStackTrace();logger.error("", ex);}}}return buffer;}public static void bytesToFile(byte[] buffer, final String filePath) {File file = new File(filePath);OutputStream output = null;BufferedOutputStream bufferedOutput = null;try {output = new FileOutputStream(file);bufferedOutput = new BufferedOutputStream(output);bufferedOutput.write(buffer);} catch (FileNotFoundException ex) {ex.printStackTrace();logger.error("", ex);} catch (IOException ex) {ex.printStackTrace();logger.error("", ex);} finally {if (null != bufferedOutput) {try {bufferedOutput.close();} catch (IOException ex) {ex.printStackTrace();logger.error("", ex);}}if (null != output) {try {output.close();} catch (IOException ex) {ex.printStackTrace();logger.error("", ex);}}}}public static void bytesToFile(byte[] buffer, File file) {OutputStream output = null;BufferedOutputStream bufferedOutput = null;try {output = new FileOutputStream(file);bufferedOutput = new BufferedOutputStream(output);bufferedOutput.write(buffer);} catch (FileNotFoundException ex) {ex.printStackTrace();logger.error("", ex);} catch (IOException ex) {ex.printStackTrace();logger.error("", ex);} finally {if (null != bufferedOutput) {try {bufferedOutput.close();} catch (IOException ex) {ex.printStackTrace();logger.error("", ex);}}if (null != output) {try {output.close();} catch (IOException ex) {ex.printStackTrace();logger.error("", ex);}}}}/*** byte數組轉換成16進制字符串* * @param src* @return*/public static String bytesToHexString(byte[] src) {StringBuilder stringBuilder = new StringBuilder();if (src == null || src.length <= 0) {return null;}for (int i = 0; i < src.length; i++) {int v = src[i] & 0xFF;String hv = Integer.toHexString(v);if (hv.length() < 2) {stringBuilder.append(0);}stringBuilder.append(hv);}return stringBuilder.toString();}/*** 根據文件流讀取圖片文件真實類型*/public static String getTypeByBytes(byte[] fileBytes) {byte[] b = new byte[4];System.arraycopy(fileBytes, 0, b, 0, b.length);String type = bytesToHexString(b).toUpperCase();if (type.contains("FFD8FF")) {return "jpg";} else if (type.contains("89504E47")) {return "png";} else if (type.contains("47494638")) {return "gif";} else if (type.contains("49492A00")) {return "tif";} else if (type.contains("424D")) {return "bmp";}return type;}public static String getTypeByFile(File file) {String fileName = file.getName();return fileName.substring(fileName.lastIndexOf(".") + 1);}public static String getTypeByFilePath(String filePath) {return filePath.substring(filePath.lastIndexOf(".") + 1);}public static byte[] toByteArray(InputStream input) throws IOException {ByteArrayOutputStream output = new ByteArrayOutputStream();byte[] buffer = new byte[4096];int n = 0;while (-1 != (n = input.read(buffer))) {output.write(buffer, 0, n);}return output.toByteArray();}}

    “人臉對比” 測試結果:
    主要看 score 參數,越高越匹配。滿分100分。

    0 [main] INFO com.baidu.aip.client.BaseClient - get access_token success. current state: STATE_AIP_AUTH_OK 2 [main] DEBUG com.baidu.aip.client.BaseClient - current state after check priviledge: STATE_TRUE_AIP_USER {"result": {"score": 90.39932251,"face_list": [{"face_token": "594b9857e1bc1a6f0bb6fa7183ca962d"},{"face_token": "f552428debe38d54081dfbce5d6d6e1e"}]},"log_id": 1345050756015080031,"error_msg": "SUCCESS","cached": 0,"error_code": 0,"timestamp": 1565601508 }

    “人臉檢測” 測試結果:

    {"result": {"face_num": 1,"face_list": [{"liveness": {"livemapscore": 1},"angle": {"roll": -3.24,"pitch": 13.22,"yaw": 7.82},"face_token": "594b9857e1bc1a6f0bb6fa7183ca962d","location": {"top": 570.86,"left": 197.56,"rotation": 1,"width": 339,"height": 325},"face_probability": 1,"age": 23}]},"log_id": 1368654456015085521,"error_msg": "SUCCESS","cached": 0,"error_code": 0,"timestamp": 1565601508 }

    人臉檢測 相關請求參數、返回參數解釋。(詳情請訪問第2點的SDK地址:即 https://ai.baidu.com/docs#/Face-Java-SDK/top)


    人臉對比 相關請求參數、返回參數解釋。(詳情請訪問第2點的SDK地址:即 https://ai.baidu.com/docs#/Face-Java-SDK/top)

    總結

    以上是生活随笔為你收集整理的Java后端 + 百度SDK实现人脸识别的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。