通用图像分割

本文档为您介绍通用图像分割常用语言和常见情况的示例代码。

说明
  • 您可以进入在线咨询获取在线人工帮助。

  • 阿里云视觉智能开放平台视觉AI能力API接入、接口使用或问题咨询等,请通过钉钉群(23109592)加入阿里云视觉智能开放平台咨询群联系我们。

能力介绍

关于通用图像分割的功能介绍以及具体调用参数说明,请参见通用分割

SDK包安装

常见语言的SDK依赖包信息,请参见SDK总览

配置环境变量

配置环境变量ALIBABA_CLOUD_ACCESS_KEY_IDALIBABA_CLOUD_ACCESS_KEY_SECRET

重要
  • 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维,具体操作,请参见创建RAM用户

  • 请不要将AccessKey ID和AccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。

  • Linux和macOS系统配置方法

    1. 在IntelliJ IDEA中打开终端Terminal。

    2. 执行以下命令,配置环境变量。

      <access_key_id>需替换为您RAM用户的AccessKey ID,<access_key_secret>替换为您RAM用户的AccessKey Secret。如果后续需要进行更多权限相关的配置,具体操作请参见使用RAM Policy控制访问权限

      export ALIBABA_CLOUD_ACCESS_KEY_ID=<access_key_id> 
      export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<access_key_secret>
  • Windows系统配置方法

    新建环境变量文件,添加环境变量ALIBABA_CLOUD_ACCESS_KEY_IDALIBABA_CLOUD_ACCESS_KEY_SECRET,并写入已准备好的AccessKey ID和AccessKey Secret。然后重启Windows系统。本操作以Windows 10为例进行说明。

    1. 打开文件资源管理器,在此电脑上右键单击属性。

    2. 在右侧导航栏,单击高级系统配置

    3. 系统属性对话框的高级页签下,单击环境变量

    4. 环境变量对话框中,单击新建(W)image.png

    5. 在弹出的新建系统变量对话框中,添加环境变量ALIBABA_CLOUD_ACCESS_KEY_IDALIBABA_CLOUD_ACCESS_KEY_SECRET,并写入已准备好的AccessKey ID和AccessKey Secret。

    6. 重启Windows系统,使配置生效。

示例代码

文件在上海地域OSS

/*
<!-- https://mvnrepository.com/artifact/com.aliyun/imageseg20191230 -->
<dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>imageseg20191230</artifactId>
      <version>${aliyun.imageseg.version}</version>
</dependency>
*/

import com.aliyun.imageseg20191230.models.SegmentCommonImageResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaModel;

public class SegmentCommonImage {
    public static com.aliyun.imageseg20191230.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        /*
          初始化配置对象com.aliyun.teaopenapi.models.Config
          Config对象存放 AccessKeyId、AccessKeySecret、endpoint等配置
         */
         com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "imageseg.cn-shanghai.aliyuncs.com";
        return new com.aliyun.imageseg20191230.Client(config);
    }

    public static void main(String[] args_) throws Exception {
        // 创建AccessKey ID和AccessKey Secret,请参考https://help.aliyun.com/document_detail/175144.html
        // 如果您使用的是RAM用户的AccessKey,还需要为子账号授予权限AliyunVIAPIFullAccess,请参考https://help.aliyun.com/document_detail/145025.html
        // 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行代码示例前必须先配置环境变量。
        String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
        String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); 
        com.aliyun.imageseg20191230.Client client = SegmentCommonImage.createClient(accessKeyId, accessKeySecret);
        com.aliyun.imageseg20191230.models.SegmentCommonImageRequest segmentCommonImageRequest = new com.aliyun.imageseg20191230.models.SegmentCommonImageRequest()
                .setImageURL("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/imageseg/SegmentCommonImage/SegmentCommonImage1.jpg");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            SegmentCommonImageResponse segmentCommonImageResponse = client.segmentCommonImageWithOptions(segmentCommonImageRequest, runtime);
            // 获取整体结果
            System.out.println(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(segmentCommonImageResponse)));
            // 获取单个字段
            System.out.println(segmentCommonImageResponse.getBody().data.imageURL);
        } catch (TeaException teaException) {
            // 获取整体报错信息
            System.out.println(com.aliyun.teautil.Common.toJSONString(teaException));
            // 获取单个字段
            System.out.println(teaException.getCode());
        }
    }
}
# -*- coding: utf-8 -*-
# 引入依赖包
# pip install alibabacloud_imageseg20191230

import os
from alibabacloud_imageseg20191230.client import Client
from alibabacloud_imageseg20191230.models import SegmentCommonImageRequest
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptions

config = Config(
    # 创建AccessKey ID和AccessKey Secret,请参考https://help.aliyun.com/document_detail/175144.html。
    # 如果您用的是RAM用户的AccessKey,还需要为RAM用户授予权限AliyunVIAPIFullAccess,请参考https://help.aliyun.com/document_detail/145025.html。
    # 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行代码示例前必须先配置环境变量。
    access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
    access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
    # 访问的域名。
    endpoint='imageseg.cn-shanghai.aliyuncs.com',
    # 访问的域名对应的region
    region_id='cn-shanghai'
)
segment_common_image_request = SegmentCommonImageRequest(
   image_url='http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/imageseg/SegmentCommonImage/SegmentCommonImage1.jpg',
   return_form='crop'
   # ReturnForm参数设置:
   # 指定返回的图像形式。
   # 如果设置为mask,则返回单通道黑白图。
   # 如果设置为crop,则返回裁剪之后的四通道PNG图(裁掉边缘空白区域)。
   # 如果设置为whiteBK,则返回白底图。
   # 如果不设置或者设置为其他值,则返回四通道PNG图。
)
runtime = RuntimeOptions()
try:
  # 初始化Client
  client = Client(config)
  response = client.segment_common_image_with_options(segment_common_image_request, runtime)
  # 获取整体结果
  print(response.body)
except Exception as error:
  # 获取整体报错信息
  print(error)
  # 获取单个字段
  print(error.code)
  # tips: 可通过error.__dict__查看属性名称
<?php

//安装依赖包
//composer require alibabacloud/imageseg-20191230
  
use AlibabaCloud\SDK\Imageseg\V20191230\Imageseg;
use AlibabaCloud\Tea\Utils\Utils;
use \Exception;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Imageseg\V20191230\Models\SegmentCommonImageRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;

class SegmentCommonImage {

    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Imageseg Client
     */
    public static function createClient($accessKeyId, $accessKeySecret){
        //初始化配置对象Darabonba\OpenApi\Models\Config。
        //Config对象存放accessKeyId、accessKeySecret、endpoint等配置
        $config = new Config([
            "accessKeyId" => $accessKeyId,
            "accessKeySecret" => $accessKeySecret
        ]);
        // 访问的域名
        $config->endpoint = "imageseg.cn-shanghai.aliyuncs.com";
        return new Imageseg($config);
    }
    /**
     * @param string[] $args
     * @return void
     */
    public static function main($args){
        // 创建AccessKey ID和AccessKey Secret,请参考https://help.aliyun.com/document_detail/175144.html。
        // 如果您用的是RAM用户的AccessKey,还需要为RAM用户授予权限AliyunVIAPIFullAccess,请参考https://help.aliyun.com/document_detail/145025.html。
        // 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行示例前必须先配置环境变量。    
        $accessKeyId = getenv('ALIBABA_CLOUD_ACCESS_KEY_ID');      
        $accessKeySecret = getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET');
        $client = self::createClient($accessKeyId, $accessKeySecret);
        $segmentCommonImageRequest = new SegmentCommonImageRequest([
            "imageURL" => "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/imageseg/SegmentCommonImage/SegmentCommonImage1.jpg",
            "returnForm" => "mask"
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            $resp = $client->segmentCommonImageWithOptions($segmentCommonImageRequest, $runtime);
            # 获取整体结果
            echo Utils::toJSONString($resp->body);
        } catch (Exception $exception) {
            # 获取整体报错信息
            echo Utils::toJSONString($exception);
            # 获取单个字段
            echo $exception->getCode();
        }
    }
}
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
    require_once $path;
}
//$argv是预留的数组入参参数,无实际意义,无需进行修改
SegmentCommonImage::main(array_slice($argv, 1));
// 安装依赖包
// npm install @alicloud/imageseg20191230
const ImagesegClient = require('@alicloud/imageseg20191230');
const OpenapiClient = require('@alicloud/openapi-client');
const TeaUtil = require('@alicloud/tea-util');

let config = new OpenapiClient.Config({
    // 创建AccessKey ID和AccessKey Secret,请参考https://help.aliyun.com/document_detail/175144.html。
    // 如果您用的是RAM用户AccessKey,还需要为RAM用户授予权限AliyunVIAPIFullAccess,请参考https://help.aliyun.com/document_detail/145025.html。
    // 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行示例前必须先配置环境变量。 
    accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,   
    accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET
});
// 访问的域名
config.endpoint = `imageseg.cn-shanghai.aliyuncs.com`;
const client = new ImagesegClient.default(config);
let segmentCommonImageRequest = new ImagesegClient.SegmentCommonImageRequest({
  imageURL: "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/imageseg/SegmentCommonImage/SegmentCommonImage1.jpg",
});
let runtime = new TeaUtil.RuntimeOptions({ });
client.segmentCommonImageWithOptions(segmentCommonImageRequest, runtime)
  .then(function(segmentCommonImageResponse) {
    // 获取整体结果
    console.log(segmentCommonImageResponse);
    // 获取单个字段
    console.log(segmentCommonImageResponse.body.data);
  }, function(error) {
    // 获取整体报错信息
    console.log(error);
    // 获取单个字段
    console.log(error.data.Code);
  })
/**
依赖github.com/alibabacloud-go/imageseg-20191230/v2
建议使用go mod tidy安装依赖
 */

import (
	"fmt"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	imageseg20191230 "github.com/alibabacloud-go/imageseg-20191230/v2/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
)

func main() {
  // 从环境变量读取配置的AccessKey ID
  // 运行示例前必须先配置环境变量  
  // 创建AccessKey ID和AccessKey Secret,请参考https://help.aliyun.com/document_detail/175144.html。
  // 如果您用的是RAM用户的AccessKey,还需要为RAM用户授予权限AliyunVIAPIFullAccess,请参考https://help.aliyun.com/document_detail/145025.html。
  // 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行示例前必须先配置环境变量。  
  accessKeyId := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")  
  accessKeySecret := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
  // 初始化配置对象 &openapi.Config。Config对象存放AccessKeyId、AccessKeySecret、Endpoint等配置。
  config := &openapi.Config{
    AccessKeyId: tea.String(accessKeyId),
    AccessKeySecret: tea.String(accessKeySecret)
	}
	// 访问的域名
	config.Endpoint = tea.String("imageseg.cn-shanghai.aliyuncs.com")
	client, err := imageseg20191230.NewClient(config)
	if err != nil {
		panic(err)
	}
	segmentCommonImageRequest := &imageseg20191230.SegmentCommonImageRequest{
		ImageURL: tea.String("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/imageseg/SegmentBody/SegmentBody1.png"),
	}
	runtime := &util.RuntimeOptions{}
	segmentCommonImageResponse, err := client.SegmentCommonImageWithOptions(segmentCommonImageRequest, runtime)
	if err != nil {
		// 获取整体报错信息
		fmt.Println(err.Error())
	} else {
		// 获取整体结果
		fmt.Println(segmentCommonImageResponse)
	}
}
// 安装依赖包
// dotnet add package AlibabaCloud.SDK.Imageseg20191230
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using AlibabaCloud.SDK.Imageseg20191230.Models;
using Tea;
using Tea.Utils;

namespace AlibabaCloud.SDK.Sample
{
    public class Sample
    {
      /**
          * 使用AK&SK初始化账号Client
          * @param accessKeyId
          * @param accessKeySecret
          * @return Client
          * @throws Exception
      */
        public static AlibabaCloud.SDK.Imageseg20191230.Client CreateClient(string accessKeyId, string accessKeySecret)
        {
            AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
            {
              AccessKeyId = accessKeyId,
              AccessKeySecret = accessKeySecret,
            };
            // 访问的域名
            config.Endpoint = "imageseg.cn-shanghai.aliyuncs.com";
            return new AlibabaCloud.SDK.Imageseg20191230.Client(config);
        }
        public static void Main(string[] args)
        {
            // 创建AccessKey ID和AccessKey Secret,请参考https://help.aliyun.com/document_detail/175144.html
            // 如果您使用的是RAM用户的AccessKey,还需要为子账号授予权限AliyunVIAPIFullAccess,请参考https://help.aliyun.com/document_detail/145025.html
            // 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行代码示例前必须先配置环境变量。
            AlibabaCloud.SDK.Imageseg20191230.Client client = CreateClient(System.Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"), System.Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
            AlibabaCloud.SDK.Imageseg20191230.Models.SegmentCommonImageRequest segmentCommonImageRequest = new AlibabaCloud.SDK.Imageseg20191230.Models.SegmentCommonImageRequest
            {
                ImageURL = "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/imageseg/SegmentCommonImage/SegmentCommonImage1.jpg",
            };
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            try
            {
                AlibabaCloud.SDK.Imageseg20191230.Models.SegmentCommonImageResponse segmentCommonImageResponse = client.SegmentCommonImageWithOptions(segmentCommonImageRequest, runtime);
                // 获取整体结果
                Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(segmentCommonImageResponse.Body));
                // 获取单个字段
                Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(segmentCommonImageResponse.Body.Data));
            }
            catch (TeaException error)
            {
                // 如有需要,请打印 error
                Console.WriteLine(AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message));
            }
            catch (Exception _error)
            {
                TeaException error = new TeaException(new Dictionary<string, object>
              {
                { "message", _error.Message }
              });
                // 如有需要,请打印 error
                Console.WriteLine(AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message));
            }
        }
    }
}

文件在本地或可访问的URL

/*
<!-- https://mvnrepository.com/artifact/com.aliyun/imageseg20191230 -->
<dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>imageseg20191230</artifactId>
      <version>${aliyun.imageseg.version}</version>
</dependency>
*/

import com.aliyun.imageseg20191230.models.SegmentCommonImageResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaModel;

import java.io.InputStream;
import java.net.URL;

public class SegmentCommonImage {
    public static com.aliyun.imageseg20191230.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        /*
          初始化配置对象com.aliyun.teaopenapi.models.Config
          Config对象存放 AccessKeyId、AccessKeySecret、endpoint等配置
         */
         com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "imageseg.cn-shanghai.aliyuncs.com";
        return new com.aliyun.imageseg20191230.Client(config);
    }

    public static void main(String[] args_) throws Exception {
        // 创建AccessKey ID和AccessKey Secret,请参考https://help.aliyun.com/document_detail/175144.html
        // 如果您使用的是RAM用户的AccessKey,还需要为子账号授予权限AliyunVIAPIFullAccess,请参考https://help.aliyun.com/document_detail/145025.html
        // 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行代码示例前必须先配置环境变量。
        String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
        String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); 
        com.aliyun.imageseg20191230.Client client = SegmentCommonImage.createClient(accessKeyId, accessKeySecret);
        // 场景一,使用本地文件
        // InputStream inputStream = new FileInputStream(new File("/tmp/SegmentCommonImage.jpg"));
        // 场景二,使用任意可访问的url
        URL url = new URL("https://viapi-test-bj.oss-cn-beijing.aliyuncs.com/viapi-3.0domepic/imageseg/SegmentCommonImage/SegmentCommonImage1.jpg");
        InputStream inputStream = url.openConnection().getInputStream();
        com.aliyun.imageseg20191230.models.SegmentCommonImageAdvanceRequest segmentCommonImageAdvanceRequest = new com.aliyun.imageseg20191230.models.SegmentCommonImageAdvanceRequest()
                .setImageURLObject(inputStream);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            SegmentCommonImageResponse segmentCommonImageResponse = client.segmentCommonImageAdvance(segmentCommonImageAdvanceRequest, runtime);
            // 获取整体结果
            System.out.println(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(segmentCommonImageResponse)));
            // 获取单个字段
            System.out.println(segmentCommonImageResponse.getBody().data.imageURL);
        } catch (TeaException teaException) {
            // 获取整体报错信息
            System.out.println(com.aliyun.teautil.Common.toJSONString(teaException));
            // 获取单个字段
            System.out.println(teaException.getCode());
        }
    }
}
# -*- coding: utf-8 -*-
# 引入依赖包
# pip install alibabacloud_imageseg20191230

import os
import io
from urllib.request import urlopen
from alibabacloud_imageseg20191230.client import Client
from alibabacloud_imageseg20191230.models import SegmentCommonImageAdvanceRequest
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptions

config = Config(
    # 创建AccessKey ID和AccessKey Secret,请参考https://help.aliyun.com/document_detail/175144.html。
    # 如果您用的是RAM用户的AccessKey,还需要为RAM用户授予权限AliyunVIAPIFullAccess,请参考https://help.aliyun.com/document_detail/145025.html。
    # 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行代码示例前必须先配置环境变量。
    access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
    access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
    # 访问的域名。
    endpoint='imageseg.cn-shanghai.aliyuncs.com',
    # 访问的域名对应的region
    region_id='cn-shanghai'
)
segment_common_image_request = SegmentCommonImageAdvanceRequest()
#场景一:文件在本地
#stream = open(r'/tmp/SegmentCommonImage.png', 'rb')
#segment_common_image_request.image_urlobject = stream

#场景二:使用任意可访问的url
url = 'https://viapi-test-bj.oss-cn-beijing.aliyuncs.com/viapi-3.0domepic/imageseg/SegmentCommonImage/SegmentCommonImage1.jpg'
img = urlopen(url).read()
segment_common_image_request.image_urlobject = io.BytesIO(img)
segment_common_image_request.return_form = 'crop'

runtime = RuntimeOptions()
try:
  # 初始化Client
  client = Client(config)
  response = client.segment_common_image_advance(segment_common_image_request, runtime)
  # 获取整体结果
  print(response.body)
except Exception as error:
  # 获取整体报错信息
  print(error)
  # 获取单个字段
  print(error.code)
  # tips: 可通过error.__dict__查看属性名称

#关闭流
#stream.close()
<?php

//安装依赖包
//composer require alibabacloud/imageseg-20191230 
  
use AlibabaCloud\SDK\Imageseg\V20191230\Imageseg;
use AlibabaCloud\Tea\Utils\Utils;
use \Exception;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Imageseg\V20191230\Models\SegmentCommonImageAdvanceRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use GuzzleHttp\Psr7\Stream;

class SegmentCommonImageAdvance {

    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Imageseg Client
     */
    public static function createClient($accessKeyId, $accessKeySecret){
        //初始化配置对象Darabonba\OpenApi\Models\Config。
        //Config对象存放accessKeyId、accessKeySecret、endpoint等配置
        $config = new Config([
            "accessKeyId" => $accessKeyId,
            "accessKeySecret" => $accessKeySecret
        ]);
        // 访问的域名
        $config->endpoint = "imageseg.cn-shanghai.aliyuncs.com";
        return new Imageseg($config);
    }
    /**
     * @param string[] $args
     * @return void
     */
    public static function main($args){
        // 创建AccessKey ID和AccessKey Secret,请参考https://help.aliyun.com/document_detail/175144.html。
        // 如果您用的是RAM用户的AccessKey,还需要为RAM用户授予权限AliyunVIAPIFullAccess,请参考https://help.aliyun.com/document_detail/145025.html。
        // 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行示例前必须先配置环境变量。    
        $accessKeyId = getenv('ALIBABA_CLOUD_ACCESS_KEY_ID');      
        $accessKeySecret = getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET');
        $client = self::createClient($accessKeyId, $accessKeySecret);
        // 场景一,使用本地文件
        //$file = fopen('/tmp/SegmentCommonImage1.jpg', 'rb');
        //$stream = new Stream($file);
        // 场景二,使用任意可访问的url
        $file = fopen('https://viapi-test-bj.oss-cn-beijing.aliyuncs.com/viapi-3.0domepic/imageseg/SegmentCommonImage/SegmentCommonImage1.jpg', 'rb');
        $stream = new Stream($file);
        $segmentCommonImageAdvanceRequest = new SegmentCommonImageAdvanceRequest([
            "imageURLObject" => $stream,
            "returnForm" => "mask"
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            $resp = $client->segmentCommonImageAdvance($segmentCommonImageAdvanceRequest, $runtime);
            # 获取整体结果
            echo Utils::toJSONString($resp->body);
        } catch (Exception $exception) {
            # 获取整体报错信息
            echo Utils::toJSONString($exception);
            # 获取单个字段
            echo $exception->getCode();
        }
    }
}
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
    require_once $path;
}
//$argv是预留的数组入参参数,无实际意义,无需进行修改
SegmentCommonImageAdvance::main(array_slice($argv, 1));
// 安装依赖包
// npm install @alicloud/imageseg20191230
const ImagesegClient = require('@alicloud/imageseg20191230');
const OpenapiClient = require('@alicloud/openapi-client');
const TeaUtil = require('@alicloud/tea-util');
const fs = require('fs');
const http = require('http');
const https = require('https');

let config = new OpenapiClient.Config({
    // 创建AccessKey ID和AccessKey Secret,请参考https://help.aliyun.com/document_detail/175144.html。
    // 如果您用的是RAM用户AccessKey,还需要为RAM用户授予权限AliyunVIAPIFullAccess,请参考https://help.aliyun.com/document_detail/145025.html。
    // 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行示例前必须先配置环境变量。 
    accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,   
    accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET
});
// 访问的域名
config.endpoint = `imageseg.cn-shanghai.aliyuncs.com`;
const client = new ImagesegClient.default(config);
const getResponse = function (httpClient, url) {
  return new Promise((resolve, reject) => {
    httpClient.get(url, function (response) {
      resolve(response);
    })
  })
}
const request = async function () {
  try {
    let segmentCommonImageAdvanceRequest = new ImagesegClient.SegmentCommonImageAdvanceRequest();
    // 场景一,使用本地文件
    // const fileStream = fs.createReadStream('/tmp/SegmentCommonImage1.jpg');
    // segmentCommonImageAdvanceRequest.imageURLObject = fileStream;
    // 场景二,使用任意可访问的url
    const url = new URL("https://viapi-test-bj.oss-cn-beijing.aliyuncs.com/viapi-3.0domepic/imageseg/SegmentCommonImage/SegmentCommonImage1.jpg");
    const httpClient = (url.protocol == "https:") ? https : http;
    segmentCommonImageAdvanceRequest.imageURLObject = await getResponse(httpClient, url);
    let runtime = new TeaUtil.RuntimeOptions({});
    client.segmentCommonImageAdvance(segmentCommonImageAdvanceRequest, runtime)
      .then(function (segmentCommonImageResponse) {
        // 获取整体结果
        console.log(segmentCommonImageResponse);
        // 获取单个字段
        console.log(segmentCommonImageResponse.body.data);
      }, function (error) {
        // 获取整体报错信息
        console.log(error);
        // 获取单个字段
        console.log(error.data.Code);
      })
  } catch (error) {
    console.log(error);
  }
}();
/**
依赖github.com/alibabacloud-go/imageseg-20191230/v2
建议使用go mod tidy安装依赖
 */

import (
	"fmt"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	imageseg20191230 "github.com/alibabacloud-go/imageseg-20191230/v2/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"net/http"
)

func main() {
  // 从环境变量读取配置的AccessKey ID
  // 运行示例前必须先配置环境变量  
  // 创建AccessKey ID和AccessKey Secret,请参考https://help.aliyun.com/document_detail/175144.html。
  // 如果您用的是RAM用户的AccessKey,还需要为RAM用户授予权限AliyunVIAPIFullAccess,请参考https://help.aliyun.com/document_detail/145025.html。
  // 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行示例前必须先配置环境变量。  
  accessKeyId := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")  
  accessKeySecret := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
  // 初始化配置对象 &openapi.Config。Config对象存放AccessKeyId、AccessKeySecret、Endpoint等配置。
  config := &openapi.Config{
    AccessKeyId: tea.String(accessKeyId),
    AccessKeySecret: tea.String(accessKeySecret)
	}
	// 访问的域名
	config.Endpoint = tea.String("imageseg.cn-shanghai.aliyuncs.com")
	client, err := imageseg20191230.NewClient(config)
	if err != nil {
		panic(err)
	}
	// 场景一,使用本地文件
	//file, err := os.Open("/tmp/SegmentCommonImage.png")
	//if err != nil {
	//	fmt.Println("can not open file", err)
	//	panic(err)
	//}
	//segmentCommonImageAdvanceRequest := &imageseg20191230.SegmentCommonImageAdvanceRequest{
	//	ImageURLObject: file,
	//}
	// 场景二,使用任意可访问的url
	httpClient := http.Client{}
	file, _ := httpClient.Get("https://viapi-test-bj.oss-cn-beijing.aliyuncs.com/viapi-3.0domepic/imageseg/SegmentCommonImage/SegmentCommonImage1.jpg")
	segmentCommonImageAdvanceRequest := &imageseg20191230.SegmentCommonImageAdvanceRequest{
		ImageURLObject: file.Body,
	}
	runtime := &util.RuntimeOptions{}
	segmentCommonImageAdvanceResponse, err := client.SegmentCommonImageAdvance(segmentCommonImageAdvanceRequest, runtime)
	if err != nil {
		// 获取整体报错信息
		fmt.Println(err.Error())
	} else {
		// 获取整体结果
		fmt.Println(segmentCommonImageAdvanceResponse)
	}
}
// 安装依赖包
// dotnet add package AlibabaCloud.SDK.Imageseg20191230
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using AlibabaCloud.SDK.Imageseg20191230.Models;
using Tea;
using Tea.Utils;

namespace AlibabaCloud.SDK.Sample
{
    public class Sample
    {
        /**
        * 使用AK&SK初始化账号Client
        * @param accessKeyId
        * @param accessKeySecret
        * @return Client
        * @throws Exception
        */
        public static AlibabaCloud.SDK.Imageseg20191230.Client CreateClient(string accessKeyId, string accessKeySecret)
        {
            AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
            {
              AccessKeyId = accessKeyId,
              AccessKeySecret = accessKeySecret,
            };
            // 访问的域名
            config.Endpoint = "imageseg.cn-shanghai.aliyuncs.com";
            return new AlibabaCloud.SDK.Imageseg20191230.Client(config);
        }
        public static void Main(string[] args)
        {
            // 创建AccessKey ID和AccessKey Secret,请参考https://help.aliyun.com/document_detail/175144.html
            // 如果您使用的是RAM用户的AccessKey,还需要为子账号授予权限AliyunVIAPIFullAccess,请参考https://help.aliyun.com/document_detail/145025.html
            // 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行代码示例前必须先配置环境变量。
            AlibabaCloud.SDK.Imageseg20191230.Client client = CreateClient(System.Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"), System.Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
            AlibabaCloud.SDK.Imageseg20191230.Models.SegmentCommonImageAdvanceRequest segmentCommonImageAdvanceRequest = new AlibabaCloud.SDK.Imageseg20191230.Models.SegmentCommonImageAdvanceRequest
            ();
            // 场景一,使用本地文件
            System.IO.StreamReader file = new System.IO.StreamReader(@"/tmp/SegmentCommonImage1.jpg");
            segmentCommonImageAdvanceRequest.ImageURLObject = file.BaseStream;

            // 场景二,使用任意可访问的url
            //HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://viapi-test-bj.oss-cn-beijing.aliyuncs.com/viapi-3.0domepic/imageseg/SegmentCommonImage/SegmentCommonImage1.jpg");
            //WebResponse response = request.GetResponse();
            //Stream stream = response.GetResponseStream();
            //segmentBodyAdvanceRequest.ImageURLObject = stream;
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            try
            {
                AlibabaCloud.SDK.Imageseg20191230.Models.SegmentCommonImageResponse segmentCommonImageResponse = client.SegmentCommonImageAdvance(segmentCommonImageAdvanceRequest, runtime);
                // 获取整体结果
                Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(segmentCommonImageResponse.Body));
                // 获取单个字段
                Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(segmentCommonImageResponse.Body.Data));
            }
            catch (TeaException error)
            {
                // 如有需要,请打印 error
                Console.WriteLine(AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message));
            }
            catch (Exception _error)
            {
                TeaException error = new TeaException(new Dictionary<string, object>
              {
                { "message", _error.Message }
              });
                // 如有需要,请打印 error
                Console.WriteLine(AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message));
            }
        }
    }
}

常见的处理后结果

背景融合

调用通用分割后,可以获取主体与背景分割后的前景物体图(4通道),可以与另一张图片进行背景融合。

以python语言为例进行代码演示。

  1. 安装相关依赖,实现依赖OpenCV。更多信息,请参见OpenCV

    pip install opencv-python
  2. 将分割后的图片下载到本地,与原图和背景图一起放到data文件夹下。

    背景图:image

    相关代码如下:

    import argparse
    import math
    import cv2
    from typing import List
    import numpy as np
    import urllib.request
    #背景变换
    def change_background_demo(
            args: List[str],
    ) -> None:
        assert (args.param is not None and len(args.param) > 3), "parameters wrong, use -h for details!"
        of_file = args.param[3]
        [sc_image, seg_img, bg_image] = [cv2.imread(img_file, cv2.IMREAD_UNCHANGED)
                                for img_file in args.param[0:3]]
        # 将分割结果进行新背景融合
        rst_image = image_merge_background(sc_image, seg_img, bg_image)
        # 保存结果到本地
        cv2.imwrite(of_file, rst_image)
    #分割后的图合并到背景图中
    def image_merge_background(sc_image, png_image, bg_image):
        assert (sc_image is not None and png_image is not None and bg_image is not None), "read image input error!"
        h, w, c = sc_image.shape
        # keep sc_image, png_image and bg_image same size
        viapi_image = cv2.resize(png_image, (w, h))
        bg_image = cv2.resize(bg_image, (w, h))
        if len(viapi_image.shape) == 2:
            mask = viapi_image[:, :, np.newaxis]
        elif viapi_image.shape[2] == 4:
            mask = viapi_image[:, :, 3:4]
        elif viapi_image.shape[2] == 3:
            mask = viapi_image[:, :, 0:1]
        else:
            raise Exception("invalid image mask!")
        mask = mask / 255.0
        # merge background(合并背景)
        sc_image = sc_image.astype(float)
        bg_image = bg_image.astype(float)
        rst_image = (sc_image - bg_image) * mask + bg_image
        rst_image = np.clip(rst_image, 0, 255)
        return rst_image
    def define_options():
        parser = argparse.ArgumentParser(description='Human segmentation examples.')
        parser.add_argument('-p', '--param', nargs=4
                                , default=['./data/source.jpg', './data/output.png', './data/background.jpg', 'result.jpg']
                                , type=str
                                , help=('source_image_path output_image_path background_path result_path'))
        args = parser.parse_args()
        return args
    if __name__ == '__main__':
        args = define_options()
        change_background_demo(args)

    效果图如下:

    image

    背景融合的相关代码,请参见merge_background

    说明

    代码解压后运行python merge_background.py即可,目前示例代码中的背景图需要使用JPG格式图片。