美文网首页散文哲思简友广场
python调用百度AI接口实现人像分割

python调用百度AI接口实现人像分割

作者: Cache_wood | 来源:发表于2021-02-03 23:37 被阅读0次

    @[toc]

    官网地址

    人像分割

    新建AipBodyAnalysis

    from aip import AipBodyAnalysis
    
    """ 你的 APPID AK SK """
    APP_ID = '你的 App ID'
    API_KEY = '你的 Api Key'
    SECRET_KEY = '你的 Secret Key'
    
    client = AipBodyAnalysis(APP_ID, API_KEY, SECRET_KEY)
    

    读取图片

    """ 读取图片 """
    def get_file_content(filePath):
        with open(filePath, 'rb') as fp:
            return fp.read()
    
    image = get_file_content('example.jpg')
    
    """ 调用人像分割 """
    client.bodySeg(image);
    
    """ 如果有可选参数 """
    options = {}
    options["type"] = "labelmap"
    
    """ 带参数调用人像分割 """
    client.bodySeg(image, options)
    

    完整代码

    python调用百度AI的方法不用多说,实现人像分割的代码如下:

    # -*- coding: utf-8 -*-
    """
    Created on Mon Feb  1 21:25:21 2021
    
    @author: lenovo
    """
    from aip import AipBodyAnalysis
    import cv2
    import numpy as np
    import base64
    
    APP_ID = '23619478'
    API_KEY = 'x2M6XTQ4oNIlhS2f2GQBElHa'
    SECRET_KEY = 'xxxxxxxxxxx'
    
    client = AipBodyAnalysis(APP_ID, API_KEY, SECRET_KEY)
    
    """ 读取图片 """
    def get_file_content(filePath):
        with open(filePath, 'rb') as fp:
            return fp.read()
    
    image = get_file_content('banben.jpg')
    
    """ 调用人像分割 """
    res = client.bodySeg(image)
     
    foreground = base64.b64decode(res['foreground'])
    labelmap = base64.b64decode(res['labelmap'])
    scoremap = base64.b64decode(res['scoremap'])
     
    nparr_foreground = np.fromstring(foreground,np.uint8)
    foregroundimg = cv2.imdecode(nparr_foreground,1)
    foregroundimg = cv2.resize(foregroundimg,(512,512),interpolation=cv2.INTER_NEAREST)
    im_new_foreground = np.where(foregroundimg==1, 10, foregroundimg)
    cv2.imwrite('foreground.png', im_new_foreground)
     
    nparr_labelmap = np.fromstring(labelmap,np.uint8)
    labelmapimg = cv2.imdecode(nparr_labelmap,1)
    labelmapimg = cv2.resize(labelmapimg,(512,512),interpolation=cv2.INTER_NEAREST)
    im_new_labelmapimg = np.where(labelmapimg==1, 255, labelmapimg)
    cv2.imwrite('labelmap.png', im_new_labelmapimg)
     
    nparr_scoremap = np.fromstring(scoremap,np.uint8)
    scoremapimg = cv2.imdecode(nparr_scoremap,1)
    scoremapimg = cv2.resize(scoremapimg,(512,512),interpolation=cv2.INTER_NEAREST)
    im_new_scoremapimg = np.where(scoremapimg==1, 255, scoremapimg)
    cv2.imwrite('scoremap.png', im_new_scoremapimg)
    

    最终效果

    原图:



    labelmap - 二值图像,需二次处理方能查看分割效果


    scoremap - 人像前景灰度图



    foreground - 人像前景抠图,透明背景


    相关文章

      网友评论

        本文标题:python调用百度AI接口实现人像分割

        本文链接:https://www.haomeiwen.com/subject/gmnytltx.html