最简单的人脸检测(免费调用百度AI开放平台接口)

欢迎访问我的GitHub

这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos

本篇概览

注册百度账号

登录百度智能云

实名认证

创建应用

拿到API Key和Secret Key

得到access_token

curl -i -k 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=【百度云应用的API Key】&client_secret=【百度云应用的Secret Key】'

编码


 
	org.projectlombok
    lombok
    1.18.18



	com.squareup.okhttp3
	okhttp
	3.10.0



	com.fasterxml.jackson.core
	jackson-databind
	2.11.0
package com.bolingcavalry.grabpush.bean.request;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;

/**
 * @author willzhao
 * @version 1.0
 * @description 请求对象
 * @date 2022/1/1 16:21
 */
@Data
public class FaceDetectRequest {
    // 图片信息(总数据大小应小于10M),图片上传方式根据image_type来判断
    String image;

    // 图片类型
    // BASE64:图片的base64值,base64编码后的图片数据,编码后的图片大小不超过2M;
    // URL:图片的 URL地址( 可能由于网络等原因导致下载图片时间过长);
    // FACE_TOKEN: 人脸图片的唯一标识,调用人脸检测接口时,会为每个人脸图片赋予一个唯一的FACE_TOKEN,同一张图片多次检测得到的FACE_TOKEN是同一个。
    @JsonProperty("image_type")
    String imageType;

    // 包括age,expression,face_shape,gender,glasses,landmark,landmark150,quality,eye_status,emotion,face_type,mask,spoofing信息
    //逗号分隔. 默认只返回face_token、人脸框、概率和旋转角度
    @JsonProperty("face_field")
    String faceField;

    // 最多处理人脸的数目,默认值为1,根据人脸检测排序类型检测图片中排序第一的人脸(默认为人脸面积最大的人脸),最大值120
    @JsonProperty("max_face_num")
    int maxFaceNum;

    // 人脸的类型
    // LIVE表示生活照:通常为手机、相机拍摄的人像图片、或从网络获取的人像图片等
    // IDCARD表示身份证芯片照:二代身份证内置芯片中的人像照片
    // WATERMARK表示带水印证件照:一般为带水印的小图,如公安网小图
    // CERT表示证件照片:如拍摄的身份证、工卡、护照、学生证等证件图片
    // 默认LIVE
    @JsonProperty("face_type")
    String faceType;

    // 活体控制 检测结果中不符合要求的人脸会被过滤
    // NONE: 不进行控制
    // LOW:较低的活体要求(高通过率 低攻击拒绝率)
    // NORMAL: 一般的活体要求(平衡的攻击拒绝率, 通过率)
    // HIGH: 较高的活体要求(高攻击拒绝率 低通过率)
    // 默认NONE
    @JsonProperty("liveness_control")
    String livenessControl;
    
    // 人脸检测排序类型
    // 0:代表检测出的人脸按照人脸面积从大到小排列
    // 1:代表检测出的人脸按照距离图片中心从近到远排列
    // 默认为0
    @JsonProperty("face_sort_type")
    int faceSortType;
}
package com.bolingcavalry.grabpush.bean.response;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.ToString;

import java.io.Serializable;
import java.util.List;

/**
 * @author willzhao
 * @version 1.0
 * @description TODO
 * @date 2022/1/1 13:30
 */
@Data
@ToString
public class FaceDetectResponse implements Serializable {
    // 返回码
    @JsonProperty("error_code")
    String errorCode;
    // 描述信息
    @JsonProperty("error_msg")
    String errorMsg;
    // 返回的具体内容
    Result result;

    /**
     * @author willzhao
     * @version 1.0
     * @description 返回的具体内容
     * @date 2022/1/1 16:01
     */
    @Data
    public static class Result {
        // 人脸数量
        @JsonProperty("face_num")
        private int faceNum;
        // 每个人脸的信息
        @JsonProperty("face_list")
        List faceList;

        /**
         * @author willzhao
         * @version 1.0
         * @description 检测出来的人脸对象
         * @date 2022/1/1 16:03
         */
        @Data
        public static class Face {
            // 位置
            Location location;
            // 是人脸的置信度
            @JsonProperty("face_probability")
            double face_probability;
            // 口罩
            Mask mask;

            /**
             * @author willzhao
             * @version 1.0
             * @description 人脸在图片中的位置
             * @date 2022/1/1 16:04
             */
            @Data
            public static class Location {
                double left;
                double top;
                double width;
                double height;
                double rotation;
            }

            /**
             * @author willzhao
             * @version 1.0
             * @description 口罩对象
             * @date 2022/1/1 16:11
             */
            @Data
            public static class Mask {
                int type;
                double probability;
            }
        }
    }
}
package com.bolingcavalry.grabpush.extend;

import com.bolingcavalry.grabpush.bean.request.FaceDetectRequest;
import com.bolingcavalry.grabpush.bean.response.FaceDetectResponse;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import sun.misc.BASE64Encoder;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author willzhao
 * @version 1.0
 * @description 百度云服务的调用
 * @date 2022/1/1 11:06
 */
public class BaiduCloudService {

    // 转换
    BASE64Encoder encoder = new BASE64Encoder();

    OkHttpClient client = new OkHttpClient();

    static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    static final String URL_TEMPLATE = "https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=%s";

    String token;

    ObjectMapper mapper = new ObjectMapper();

    public BaiduCloudService(String token) {
        this.token = token;
        
        // 重要:反序列化的时候,字符的字段如果比类的字段多,下面这个设置可以确保反序列化成功
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    }

    /**
     * 将指定位置的图片转为base64字符串
     * @param imagePath
     * @return
     */
    private String img2Base64(String imagePath) {
        InputStream inputStream = null;
        byte[] data = null;

        try {
            inputStream = new FileInputStream(imagePath);
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }

        return null==data ? null :encoder.encode(data);
    }

    /**
     * 检测指定的图片
     * @param imageBase64
     * @return
     */
    public FaceDetectResponse detect(String imageBase64) {
        // 请求对象
        FaceDetectRequest faceDetectRequest = new FaceDetectRequest();
        faceDetectRequest.setImageType("BASE64");
        faceDetectRequest.setFaceField("mask");
        faceDetectRequest.setMaxFaceNum(6);
        faceDetectRequest.setFaceType("LIVE");
        faceDetectRequest.setLivenessControl("NONE");
        faceDetectRequest.setFaceSortType(0);
        faceDetectRequest.setImage(imageBase64);

        FaceDetectResponse faceDetectResponse = null;

        try {
            // 用Jackson将请求对象序列化成字符串
            String jsonContent = mapper.writeValueAsString(faceDetectRequest);

            //
            RequestBody requestBody = RequestBody.create(JSON, jsonContent);
            Request request = new Request
                    .Builder()
                    .url(String.format(URL_TEMPLATE, token))
                    .post(requestBody)
                    .build();
            Response response = client.newCall(request).execute();
            String rawRlt = response.body().string();
            faceDetectResponse = mapper.readValue(rawRlt, FaceDetectResponse.class);
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }

        return faceDetectResponse;
    }

    public static void main(String[] args) {
        // 图片在本地的位置
        String imagePath = "E:temp2022011pic1.jpeg";

        // 百度云的token,是通过此接口得到的:https://aip.baidubce.com/oauth/2.0/token
        String token = "24.95xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.xxxxxxx.xxxxxxxxxx.xxxxxx-xxxxxxxx";

        // 实例化服务对象
        BaiduCloudService service = new BaiduCloudService(token);

        // 将图片转为base64字符串
        String imageBase64 = service.img2Base64(imagePath);

        // 向百度服务发请求,检测人脸
        FaceDetectResponse faceDetectResponse = service.detect(imageBase64);

        // 输出检测结果
        System.out.println(faceDetectResponse);
    }
}

使用限制

欢迎关注头条号:程序员欣宸

展开阅读全文

页面更新:2024-04-25

标签:接口   活体   控制台   口罩   字段   对象   位置   页面   图片   平台   信息

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2008-2024 All Rights Reserved. Powered By bs178.com 闽ICP备11008920号-3
闽公网安备35020302034844号

Top