Call Tencent API to achieve portrait segmentation

1. Introduction of the author

Yue Zeang, male, graduate student of 2022, School of Electronic Information, Xi'an Polytechnic University,
research direction: machine vision and artificial intelligence
email: [email protected]

Chen Mengdan, female, School of Electronic Information, Xi'an Polytechnic University, 2022 graduate student, Zhang Hongwei's artificial intelligence research group
Research direction: machine vision and artificial intelligence
Email: [email protected]

2. Tencent Cloud API Portrait Segmentation

2.1 Interface description of portrait segmentation

  • Portrait segmentation: that is, binary classification portrait segmentation, which recognizes the complete outline of the human body in the incoming picture and performs keying.
  • Custom Portrait Segmentation: Optimize multi-category segmentation on the basis of foreground and background segmentation, and support the segmentation of hair and facial features. It can be used not only as the underlying technology for changing hairstyles and pendants, but also for playing games such as picking heads and faces.

Interface request domain name: bda.tencentcloudapi.com.

2.2 Introduction to request parameters

Binary portrait segmentation input parameters:
insert image description here
custom portrait segmentation input parameters:
insert image description here
binary portrait segmentation output parameters:
insert image description here
custom portrait segmentation output parameters:
insert image description here

3. Code

3.1 Get SecretId and SecretKey

Register and log in to the Tencent Cloud account, click on the console , search for the access key , and find the previously used SecretId and SecretKey .

insert image description here
insert image description here

3.2 Code debugging for portrait segmentation

Search for portrait segmentation , click to enter.
insert image description here
After clicking to open immediately , there will be 1000 free resources.
insert image description here
Click Resource Package Management to see the usage of free resources.
insert image description here
Go back to the homepage, click Documents , search for Portrait Segmentation in the search box , and then click Human Body Analysis .
insert image description here
Click the API documentation and the corresponding link, and then click Debug.
insert image description here
insert image description here
insert image description here

3.3 Complete code

import json
import base64
import matplotlib.pyplot as plt

from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.bda.v20200324 import bda_client, models

try:
    cred = credential.Credential("***********mKekMks31pOhlANL3Ug", "vhFXbQ2QXQ4SZU9Zjd******YzEG3b")
    # 实例化一个http选项,可选的,没有特殊需求可以跳过
    httpProfile = HttpProfile()
    httpProfile.endpoint = "bda.tencentcloudapi.com"

    # 实例化一个client选项,可选的,没有特殊需求可以跳过
    clientProfile = ClientProfile()
    clientProfile.httpProfile = httpProfile
    # 实例化要请求产品的client对象,clientProfile是可选的
    client = bda_client.BdaClient(cred, "ap-beijing", clientProfile)

    # 实例化一个请求对象,每个接口都会对应一个request对象
    img_path="人像分割前的图像加载路径"
    with open(img_path,"rb") as file:
        img=base64.b64encode(file.read())
      
    req = models.SegmentPortraitPicRequest()                   #二分割
    # req = models.SegmentCustomizedPortraitPicRequest()     #自定义分割
    params = {
    
    
        "Image": str(img, encoding='utf-8'),
        "SegmentationOptions": {
    
    
            # "Background": True,
            # "Hair": True,
            # "LeftEyebrow": True,
            # "RightEyebrow": True,
            # "LeftEye": True,
            # "RightEye": True,
            # "Nose": True,
            # "UpperLip": True,
            # "LowerLip": True,
            # "Tooth": True,
            # "Mouth": True,
            # "LeftEar": True,
            # "RightEar": True,
            "Face": True,
            "Head": True,
            # "Body": True,
            # "Hat": True,
            # "Headdress": True,
            # "Earrings": True,
            # "Necklace": True,
            # "Belongings": True
        }
    }
    req.from_json_string(json.dumps(params))

    # 返回的resp是一个SegmentPortraitPicResponse的实例,与请求对象对应
    resp = client.SegmentPortraitPic(req)                         #二分割
    # resp = client.SegmentCustomizedPortraitPic(req)         #自定义分割
    # 输出json格式的字符串回包
    json_data = resp.to_json_string()
    resp = json.loads(json_data)
    result = str(resp).replace(", ","\n")
    print(result)
    with open("人像分割后的图像保存路径","wb") as file:
      file.write(base64.b64decode(resp["ResultImage"]))         #二分割  
    # with open("自己的图像保存路径","wb") as file:
    #   file.write(base64.b64decode(resp["PortraitImage"]))     #自定义分割    
except TencentCloudSDKException as err:
    print(err)

3.4 Experimental results

insert image description here

Guess you like

Origin blog.csdn.net/m0_37758063/article/details/131081076