Baidu Smart Cloud Portrait Segmentation Case Teaching: back-end java realizes ID card portrait segmentation and background color change

renderings

 

 

 

① Go to  Baidu Smart Cloud - Intelligent Era Infrastructure  and search for "Portrait Segmentation". After real-name authentication, you can get free trial times

②Get Access_token

String accessToken = "[access_token]"

Here you need to go to another interface to get Access_token. Get the tutorial: https://ai.baidu.com/ai-doc/REFERENCE/Ck3dwjhhu

To save trouble here, I choose to use postman to get Access_token

 

 ③Fill the Access_token into the code below. Change the image file path to the path you need. The tool classes required in the code can be downloaded directly through the URL in the comment

The code below comes from the Baidu portrait segmentation development document, I made a little modification.

/**
 * 人像分割
 */
public class Main {

    /**
     * 重要提示代码中所需工具类
     * 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 body_seg() {

        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/body_seg";
        try {
            // 本地文件路径
            String filePath = "D:/AAfile/2.jpg";
            byte[] imgData = FileUtil.readFileByBytes(filePath);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");
            String param = "image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。
            String accessToken = "[access_token]";//这里需要去另一个接口获取一下access_token
            String result = HttpUtil.post(url, accessToken, param);
            Map mapTypes = JSON.parseObject(result);//将返回的json转化为map
            String a = String.valueOf(mapTypes.get("foreground"));//这里获取到的是处理后的base64
            File file = new File("D:/AAfile/baidu2.jpg");//新建文件作为处理后图片
            StreamUtils.base64ToFile(a,file);//将base64转为文件
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void main(String[] args) {
        Main.body_seg();
    }
}

Guess you like

Origin blog.csdn.net/qq_70143756/article/details/129422835