基于百度的图片人脸检测

1.需求

检测图片中的人脸区域

2.认证信息

在这里插入图片描述

3.代码
package com.visy.utils;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author visy.wang
 * @date 2024/12/13 14:03
 */
public class FaceUtil {
    private static final String API_KEY = "API Key";
    private static final String SECRET_KEY = "Secret Key";
    private static final String GET_TOKEN_URL = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s";
    private static final String DETECT_URL = "https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=%s";

    public static void main(String[] args) throws Exception{
        //获取AccessToken
        //有效期为30天,可缓存,过期后再重新获取
        String token = getToken();
        System.out.println("token: "+token);
        
        //读取本地图片,并转换成Base64字符串
        String filePath = "E:\\test\\imgs\\109951168274614846.jpg";
        Path path = Paths.get(filePath);
        byte[] imageData = Files.readAllBytes(path);
        String base64 = Base64.getEncoder().encodeToString(imageData);

		//人脸检测
        JSONObject result = faceDetect(token, base64);
        if(!Integer.valueOf(0).equals(result.getInteger("error_code"))){
            System.out.println("人脸检测失败:"+result.getString("error_msg"));
            return;
        }

		//检测到的人脸列表
        JSONArray array = result.getJSONObject("result").getJSONArray("face_list");
        for (int i = 0; i < array.size(); i++) {
            JSONObject location = array.getJSONObject(i).getJSONObject("location");
            System.out.println(location);

            BufferedImage image = ImageIO.read(path.toFile());
            BufferedImage canvas = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
            //获得画布的画笔
            Graphics graphics = canvas.getGraphics();
            //先将原图片画到画布上
            graphics.drawImage(image, 0, 0, null);
            graphics.setColor(Color.RED);
            //标记人人脸区域
            graphics.fillRect(
                location.getFloat("left").intValue(),
                location.getFloat("top").intValue(),
                location.getFloat("width").intValue(),
                location.getFloat("height").intValue()
            );
            graphics.dispose(); //释放资源
            ImageIO.write(canvas, "jpg", new File(filePath.substring(0, filePath.length()-4)+"_"+System.currentTimeMillis()+".jpg")); // 保存图片
        }
    }

    public static String getToken(){
        String body = HttpUtil.get(String.format(GET_TOKEN_URL, API_KEY, SECRET_KEY), StandardCharsets.UTF_8);
        System.out.println("获取AccessToken响应体: "+body);
        JSONObject result = JSONObject.parseObject(body);
        System.out.println("AccessToken 有效期:"+result.getInteger("expires_in")+"秒");
        return result.getString("access_token");
    }

    public static JSONObject faceDetect(String accessToken, String imageBase64) {
        String url = String.format(DETECT_URL, accessToken);

        Map<String, Object> map = new HashMap<>();
        map.put("image", imageBase64);
        map.put("image_type", "BASE64");
        String param = JSONObject.toJSONString(map);

        String body = HttpUtil.post(url, param);
        System.out.println("人脸检测返回体:"+body);
        return JSON.parseObject(body);
    }
}
4.效果

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值