百度AI开放平台——简易人脸识别java版

百度AI开放平台——简易人脸识别java版

  • 准备工作
  • 流程:
  • 项目结构和代码:
  • 最终效果:
  • 注:

准备工作

1、百度AI开发平台账号和人脸识别相关功能
2、一张人脸照片

流程:

1、页面调用摄像头拍照获取当前使用者照片,传入后台保存
2、利用事先保存的图片和前台传入的图片进行对比,返回一个匹配值

项目结构和代码:

百度AI开放平台——简易人脸识别java版_第1张图片

  1. FaceMatch.java(百度AI账号配置和进行人脸匹配的类)
package home.face.controller;



import home.face.utils.Base64Util;
import home.face.utils.FileUtil;
import home.face.utils.HttpUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

/**
* 人脸对比
*/
public class FaceMatch {
     

    /**
     * 百度云AK
     */
    private static final String API_KEY = "API_KEY";
    /**
     * 百度云SK
     */
    private static final String SECRET_KEY = "SECRET_KEY";
    /**
     * 获取access_token的接口地址
     */
    private static final String AUTH_HOST = "https://aip.baidubce.com/oauth/2.0/token?";
    /**
     * 进行人脸探测的接口地址
     */
    private static final String DETECT_HOST = "https://aip.baidubce.com/rest/2.0/face/v3/detect";



    /**
    * 重要提示代码中所需工具类
    * FileUtil,Base64Util,HttpUtil,GsonUtils请从
    * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
    * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
    * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
    * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
    * 下载
    */
    public static String faceMatch() {
     
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/match";
        String score = "0";
        try {
     
        	JSONArray jsonArray = new JSONArray();

        	JSONObject json  = new JSONObject();
        	json.put("image_type", "BASE64");
        	byte[] imgData = FileUtil.readFileByBytes("/Users/miyakohiroshi/Desktop/picture.jpg");
            String imgStr = Base64Util.encode(imgData);
            json.put("image", imgStr);


            JSONObject json1  = new JSONObject();
        	json1.put("image_type", "BASE64");
        	byte[] imgData1 = FileUtil.readFileByBytes("/Users/miyakohiroshi/Desktop/pingchang.jpg");
            String imgStr1 = Base64Util.encode(imgData1);
            json1.put("image", imgStr1);

            jsonArray.add(json1);
            jsonArray.add(json);

            // 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。
            String accessToken = getAuth();

            String result = HttpUtil.post(url, accessToken, "application/json", jsonArray.toString());
//            System.out.println(result);
            JSONObject resultString = JSONObject.fromObject(result);

            if(resultString.has("result") && JSONObject.fromObject(result).getInt("error_code") == 0){
     
            	score = JSONObject.fromObject(resultString.getString("result")).getString("score");
            	System.out.println("===="+score);
            }
            return score;
        } catch (Exception e) {
     
            e.printStackTrace();
        }
        return score;
    }

    /**
     * 获取权限token
     * @return
     */
    public static String getAuth(){
     
        // 获取token地址
        String getAccessTokenUrl = AUTH_HOST
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + API_KEY
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + SECRET_KEY;
        JSONObject jsonObject = null;
        BufferedReader in = null;
        try {
     
            URL realUrl = new URL(getAccessTokenUrl);
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            /*for (String key : map.keySet()) {
                System.err.println(key + "--->" + map.get(key));
            }*/
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
     
                result += line;
            }
            /**
             * 返回结果示例
             */
            jsonObject = JSONObject.fromObject(result);
            String access_token = jsonObject.getString("access_token");
            return access_token;
        } catch (Exception e) {
     
            e.printStackTrace();
        } finally {
     
            if(in!=null){
     
                try {
     
                    in.close();
                } catch (IOException e) {
     
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static void main(String[] args) {
     
        FaceMatch.faceMatch();
    }
}
  1. TestController.java(进行图片保存和返回结果的类)
package home.face.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
@RequestMapping("Test")
public class TestController {
     


        //base64字符串转化成图片
        @RequestMapping("/test")
        public  String GenerateImage(String imgStr, HttpServletRequest req, HttpServletResponse res)
        {
     
            String modelInfo = "人脸识别的阈值是80;你的识别结果是";
            String origin = req.getHeader("Origin");
            if( null != origin) {
     
                res.addHeader("Access-Control-Allow-Origin", origin);
            }

            //对字节数组字符串进行Base64解码并生成图片
            if (imgStr == null) //图像数据为空
                return modelInfo+"0";
            BASE64Decoder decoder = new BASE64Decoder();
            imgStr = imgStr.split(",")[1];
            try
            {
     
                //Base64解码
                byte[] b = decoder.decodeBuffer(imgStr);
                for(int i=0;i<b.length;++i)
                {
     
                    if(b[i]<0)
                    {
     //调整异常数据
                        b[i]+=256;
                    }
                }
                //生成jpeg图片
                String imgFilePath = "/Users/miyakohiroshi/Desktop/picture.jpg";//新生成的图片
                OutputStream out = new FileOutputStream(imgFilePath);
                out.write(b);
                out.flush();
                out.close();
                String socre = FaceMatch.faceMatch();

                return modelInfo+socre;
            }
            catch (Exception e)
            {
     
                return modelInfo+"0";
            }
        }

}

  1. cutpicture.html(进行图片获取和结果返回)



    GET VIDEO
    






>



  1. application.properties(配置文件)
server.port=8080
spring.thymeleaf.mode=HTML
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
  1. pom.xml


    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.2.1.RELEASE
         
    
    Home
    face
    0.0.1-SNAPSHOT
    face
    Demo project for Spring Boot

    
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
            
                
                    org.junit.vintage
                    junit-vintage-engine
                
            
        
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
        
            net.sf.json-lib
            json-lib
            2.4
            jdk15
        
        
            com.google.code.gson
            gson
            2.8.6
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

最终效果:

注:

1、页面获取的人脸图片存放地址/Users/miyakohiroshi/Desktop/picture.jpg
2、事先准备的人脸地址/Users/miyakohiroshi/Desktop/pingchang.jpg
3、百度人脸匹配推荐的阈值是80

你可能感兴趣的:(人脸识别,springboot,百度AI人脸识别,html调用摄像头照相,java人脸识别)