人像分割
更新时间:2024-03-26
接口描述
识别人体的轮廓范围,与背景进行分离,适用于拍照背景替换、照片合成、身体特效等场景。输入正常人像图片,返回分割后的二值结果图、灰度图、透明背景的人像图(png格式);并输出画面中的人数、人体坐标信息,可基于此对图片进行过滤、筛选,如筛选出大于x人的图片进行特殊处理。
分割效果示意图:
1)原图
2)二值图
3)灰度图
4)前景人像图(透明背景)
注:返回的二值图像需要进行二次处理才可查看分割效果,示例代码如下;灰度图和前景人像图不用处理,直接解码保存图片即可。
Python:
{
    import cv2
    import numpy as np
    import base64
    labelmap = base64.b64decode(res['labelmap'])    # res为通过接口获取的返回json
    nparr = np.fromstring(labelmap, np.uint8)
    labelimg = cv2.imdecode(nparr, 1)
    # width, height为图片原始宽、高
    labelimg = cv2.resize(labelimg, (width, height), interpolation=cv2.INTER_NEAREST)
    im_new = np.where(labelimg==1, 255, labelimg)
    cv2.imwrite('path/to/your/outputfile', im_new)
}Java:
public static BufferedImage resize(BufferedImage img, int newW, int newH) {
    Image tmp = img.getScaledInstance(newW, newH, Image.SCALE_SMOOTH);
    BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = dimg.createGraphics();
    g2d.drawImage(tmp, 0, 0, null);
    g2d.dispose();
    return dimg;
}
public static void convert(String labelmapBase64, int realWidth, int realHeight) {
    try {
	
        byte[] bytes = Base64.getDecoder().decode(labelmapBase64);
        InputStream is = new ByteArrayInputStream(bytes);
        BufferedImage image = ImageIO.read(is);
        BufferedImage newImage = resize(image, realWidth, realHeight);
        BufferedImage grayImage = new BufferedImage(realWidth, realHeight, BufferedImage.TYPE_BYTE_GRAY);
        for(int i= 0 ; i < realWidth ; i++){
            for(int j = 0 ; j < realHeight; j++){
                int rgb = newImage.getRGB(i, j);
                grayImage.setRGB(i, j, rgb * 255);  //将像素存入缓冲区
            }
        }
        File newFile = new File("gray.jpg");
        ImageIO.write(grayImage, "jpg", newFile);
    } catch (IOException e) {
        e.printStackTrace();
    }
}在线调试
您可以在示例代码中心中调试该接口,可进行签名验证、查看在线调用的请求内容和返回结果、示例代码的自动生成。
请求说明
请求示例
HTTP 方法:POST
请求URL: https://aip.baidubce.com/rest/2.0/image-classify/v1/body_seg
URL参数:
| 参数 | 值 | 
|---|---|
| access_token | 通过API Key和Secret Key获取的access_token,参考“Access Token获取” | 
Header如下:
| 参数 | 值 | 
|---|---|
| Content-Type | application/x-www-form-urlencoded | 
Body中放置请求参数,参数详情如下:
请求参数
| 参数 | 是否必选 | 类型 | 可选值范围 | 说明 | 
|---|---|---|---|---|
| image | 是 | string | - | 图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M。图片的base64编码是不包含图片头的,如( data:image/jpg;base64,),支持图片格式:jpg、bmp、png,最短边至少50px,最长边最大4096px | 
| type | 否 | string | labelmap,scoremap,foreground | 可以通过设置type参数,自主设置返回哪些结果图,避免造成带宽的浪费 1)可选值说明: labelmap - 二值图像,需二次处理方能查看分割效果 scoremap - 人像前景灰度图 foreground - 人像前景抠图,透明背景 2)type 参数值可以是可选值的组合,用逗号分隔;如果无此参数默认输出全部3类结果图 | 
请求代码示例
提示一:使用示例代码前,请记得替换其中的示例Token、图片地址或Base64信息。
提示二:部分语言依赖的类或库,请在代码注释中查看下载地址。
人像分割
curl -i -k 'https://aip.baidubce.com/rest/2.0/image-classify/v1/body_seg?access_token=【调用鉴权接口获取的token】' --data 'image=【图片Base64编码,需UrlEncode】' -H 'Content-Type:application/x-www-form-urlencoded'<?php
/**
 * 发起http post请求(REST API), 并获取REST请求的结果
 * @param string $url
 * @param string $param
 * @return - http response body if succeeds, else false.
 */
function request_post($url = '', $param = '')
{
    if (empty($url) || empty($param)) {
        return false;
    }
    $postUrl = $url;
    $curlPost = $param;
    // 初始化curl
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $postUrl);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    // 要求结果为字符串且输出到屏幕上
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    // post提交方式
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
    // 运行curl
    $data = curl_exec($curl);
    curl_close($curl);
    return $data;
}
$token = '[调用鉴权接口获取的token]';
$url = 'https://aip.baidubce.com/rest/2.0/image-classify/v1/body_seg?access_token=' . $token;
$img = file_get_contents('[本地文件路径]');
$img = base64_encode($img);
$bodys = array(
    'image' => $img
);
$res = request_post($url, $bodys);
var_dump($res);package com.baidu.ai.aip;
import com.baidu.ai.aip.utils.Base64Util;
import com.baidu.ai.aip.utils.FileUtil;
import com.baidu.ai.aip.utils.HttpUtil;
import java.net.URLEncoder;
/**
* 人像分割
*/
public class BodySeg {
    /**
    * 重要提示代码中所需工具类
    * 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() {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/body_seg";
        try {
            // 本地文件路径
            String filePath = "[本地文件路径]";
            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 = "[调用鉴权接口获取的token]";
            String result = HttpUtil.post(url, accessToken, param);
            System.out.println(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public static void main(String[] args) {
        BodySeg.body_seg();
    }
}# encoding:utf-8
import requests
import base64
'''
人像分割
'''
request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/body_seg"
# 二进制方式打开图片文件
f = open('[本地文件]', 'rb')
img = base64.b64encode(f.read())
params = {"image":img}
access_token = '[调用鉴权接口获取的token]'
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/x-www-form-urlencoded'}
response = requests.post(request_url, data=params, headers=headers)
if response:
    print (response.json())#include <iostream>
#include <curl/curl.h>
// libcurl库下载链接:https://curl.haxx.se/download.html
// jsoncpp库下载链接:https://github.com/open-source-parsers/jsoncpp/
const static std::string request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/body_seg";
static std::string body_seg_result;
/**
 * curl发送http请求调用的回调函数,回调函数中对返回的json格式的body进行了解析,解析结果储存在全局的静态变量当中
 * @param 参数定义见libcurl文档
 * @return 返回值定义见libcurl文档
 */
static size_t callback(void *ptr, size_t size, size_t nmemb, void *stream) {
    // 获取到的body存放在ptr中,先将其转换为string格式
    body_seg_result = std::string((char *) ptr, size * nmemb);
    return size * nmemb;
}
/**
 * 人像分割
 * @return 调用成功返回0,发生错误返回其他错误码
 */
int body_seg(std::string &json_result, const std::string &access_token) {
    std::string url = request_url + "?access_token=" + access_token;
    CURL *curl = NULL;
    CURLcode result_code;
    int is_success;
    curl = curl_easy_init();
    if (curl) {
        curl_easy_setopt(curl, CURLOPT_URL, url.data());
        curl_easy_setopt(curl, CURLOPT_POST, 1);
        curl_httppost *post = NULL;
        curl_httppost *last = NULL;
        curl_formadd(&post, &last, CURLFORM_COPYNAME, "image", CURLFORM_COPYCONTENTS, "【base64_img】", CURLFORM_END);
        curl_easy_setopt(curl, CURLOPT_HTTPPOST, post);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback);
        result_code = curl_easy_perform(curl);
        if (result_code != CURLE_OK) {
            fprintf(stderr, "curl_easy_perform() failed: %s\n",
                    curl_easy_strerror(result_code));
            is_success = 1;
            return is_success;
        }
        json_result = body_seg_result;
        curl_easy_cleanup(curl);
        is_success = 0;
    } else {
        fprintf(stderr, "curl_easy_init() failed.");
        is_success = 1;
    }
    return is_success;
}using System;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
namespace com.baidu.ai
{
    public class BodySeg
    {
        // 人像分割
        public static string body_seg()
        {
            string token = "[调用鉴权接口获取的token]";
            string host = "https://aip.baidubce.com/rest/2.0/image-classify/v1/body_seg?access_token=" + token;
            Encoding encoding = Encoding.Default;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
            request.Method = "post";
            request.KeepAlive = true;
            // 图片的base64编码
            string base64 = getFileBase64("[本地图片文件]");
            String str = "image=" + HttpUtility.UrlEncode(base64);
            byte[] buffer = encoding.GetBytes(str);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
            string result = reader.ReadToEnd();
            Console.WriteLine("人像分割:");
            Console.WriteLine(result);
            return result;
        }
        public static String getFileBase64(String fileName) {
            FileStream filestream = new FileStream(fileName, FileMode.Open);
            byte[] arr = new byte[filestream.Length];
            filestream.Read(arr, 0, (int)filestream.Length);
            string baser64 = Convert.ToBase64String(arr);
            filestream.Close();
            return baser64;
        }
    }
}返回说明
返回参数
| 字段 | 是否必选 | 类型 | 说明 | 
|---|---|---|---|
| labelmap | 否 | string | 分割结果图片,base64编码之后的二值图像,需二次处理方能查看分割效果 | 
| scoremap | 否 | string | 分割后人像前景的scoremap,归一到0-255,不用进行二次处理,直接解码保存图片即可。Base64编码后的灰度图文件,图片中每个像素点的灰度值 = 置信度 * 255,置信度为原图对应像素点位于人体轮廓内的置信度,取值范围[0, 1] | 
| foreground | 否 | string | 分割后的人像前景抠图,透明背景,Base64编码后的png格式图片,不用进行二次处理,直接解码保存图片即可。将置信度大于0.5的像素抠出来,并通过image matting技术消除锯齿 | 
| person_num | 是 | int32 | 检测到的人体框数目 | 
| person_info | 否 | object[] | 人体框信息 | 
| +height | 否 | float | 人体区域的高度,注意当值为0时 数据类型为int | 
| +left | 否 | float | 人体区域离左边界的距离,注意当值为0时 数据类型为int | 
| +top | 否 | float | 人体区域离上边界的距离,注意当值为0时 数据类型为int | 
| +width | 否 | float | 人体区域的宽度,注意当值为0时 数据类型为int | 
| +score | 否 | float | 人体框的概率分数,取值0-1,,注意当值为0时 数据类型为int | 
返回示例
{
    "log_id": 2451426617428943180,
    "labelmap": "iVBORw0KGg",
    "scoremap": "iVBORw0KGg"
    "foreground": "iVBORw0KGg",
    "person_num": 2,
    "person_info": [
        {
            "height": 420.9641110897064,
            "width": 365.67474365234375,
            "top": 3.704406976699829,
            "score": 0.9801973104476929,
            "left": 229.32940673828125
        },
        {
            "height": 371.6713676452637,
            "width": 167.91799926757812,
            "top": 49.91801834106445,
            "score": 0.4228516221046448,
            "left": 470.4878234863281
        }
    ],    
}