General image segmentation

更新时间:
复制 MD 格式

This topic provides code samples to help you use the general image segmentation feature. Examples are available in multiple programming languages for common use cases.

Note
  • For real-time assistance, start an online consultation.

  • If you have questions about API access or usage for the Alibaba Cloud Vision AI Platform, join our DingTalk group (ID: 23109592) to contact us.

Overview

For a functional overview and detailed parameter descriptions for general image segmentation, see General Segmentation.

Install the SDK package

For information about SDK dependencies for supported programming languages, see SDK Overview.

Configure environment variables

Configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.

Important
  • An Alibaba Cloud account has full access to all API operations. We recommend that you use a RAM user for API calls or routine O&M. For more information, see Create a RAM user.

  • Do not save your AccessKey ID or AccessKey Secret in project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account may be compromised.

  • Configure environment variables on Linux and macOS

    1. Open a terminal in IntelliJ IDEA.

    2. Run the following commands to configure the environment variables.

      Replace <access_key_id> with the AccessKey ID of your RAM user and <access_key_secret> with the AccessKey Secret of your RAM user. If you need to configure more permissions, see Control access permissions using a RAM policy.

      export ALIBABA_CLOUD_ACCESS_KEY_ID=<access_key_id>
      export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<access_key_secret>
  • Configure environment variables on Windows

    Create a new environment variable file, add the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET, and set them to the AccessKey ID and AccessKey Secret that you have prepared. Then, restart the Windows operating system. The following example uses Windows 10.

    1. Open File Explorer, right-click This PC, and then select Properties.

    2. In the left-side navigation pane, click Advanced system settings.

    3. On the Advanced tab of the System Properties dialog box, click Environment Variables.

    4. In the Environment Variables dialog box, click New.

    5. In the New System Variable dialog box, add the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET, and set them to the AccessKey ID and AccessKey Secret that you have prepared.

    6. Restart the Windows operating system for the configurations to take effect.

Sample code

Image in OSS (Shanghai)

/*
<!-- 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 {
        /*
          Initialize the configuration object com.aliyun.teaopenapi.models.Config.
          The Config object stores configuration parameters such as your AccessKey ID, AccessKey Secret, and endpoint.
         */
         com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        // The endpoint of the service.
        config.endpoint = "imageseg.cn-shanghai.aliyuncs.com";
        return new com.aliyun.imageseg20191230.Client(config);
    }

    public static void main(String[] args_) throws Exception {
        // For information on how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
        // If you use the AccessKey pair of a RAM user, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
        // Obtain the AccessKey ID and AccessKey Secret from environment variables. You must configure environment variables before running the sample code.
        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);
            // Get the entire result.
            System.out.println(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(segmentCommonImageResponse)));
            // Get a specific field.
            System.out.println(segmentCommonImageResponse.getBody().data.imageURL);
        } catch (TeaException teaException) {
            // Get the complete error message.
            System.out.println(com.aliyun.teautil.Common.toJSONString(teaException));
            // Get a specific field from the error.
            System.out.println(teaException.getCode());
        }
    }
}
# -*- coding: utf-8 -*-
# Import the required dependencies.
# 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(
    # For information on how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
    # If you use the AccessKey pair of a RAM user, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
    # Obtain the AccessKey ID and AccessKey Secret from environment variables. You must configure environment variables before running the sample code.
    access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
    access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
    # The endpoint of the service.
    endpoint='imageseg.cn-shanghai.aliyuncs.com',
    # The region ID that corresponds to the endpoint.
    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'
   # Settings for the ReturnForm parameter:
   # Specifies the format of the returned image.
   # If you set this parameter to 'mask', the service returns a single-channel grayscale image (mask).
   # If you set this parameter to 'crop', the service returns a four-channel PNG image with the empty border areas cropped.
   # If you set this parameter to 'whiteBK', the service returns an image with a white background.
   # If you do not set this parameter or set it to another value, the service returns a four-channel PNG image.
)
runtime = RuntimeOptions()
try:
  # Initialize the client.
  client = Client(config)
  response = client.segment_common_image_with_options(segment_common_image_request, runtime)
  # Get the entire result.
  print(response.body)
except Exception as error:
  # Get the complete error message.
  print(error)
  # Get a specific field from the error.
  print(error.code)
  # Tip: You can view attribute names by using error.__dict__.
<?php

// Install dependencies.
// 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 {

    /**
     * Initialize the client by using an AccessKey pair.
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Imageseg Client
     */
    public static function createClient($accessKeyId, $accessKeySecret){
        // Initialize the configuration object Darabonba\OpenApi\Models\Config.
        // The Config object stores configuration parameters such as your accessKeyId, accessKeySecret, and endpoint.
        $config = new Config([
            "accessKeyId" => $accessKeyId,
            "accessKeySecret" => $accessKeySecret
        ]);
        // The endpoint of the service.
        $config->endpoint = "imageseg.cn-shanghai.aliyuncs.com";
        return new Imageseg($config);
    }
    /**
     * @param string[] $args
     * @return void
     */
    public static function main($args){
        // For information on how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
        // If you use the AccessKey pair of a RAM user, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
        // Obtain the AccessKey ID and AccessKey Secret from environment variables. You must configure environment variables before running the sample code.    
        $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);
            # Get the entire result.
            echo Utils::toJSONString($resp->body);
        } catch (Exception $exception) {
            # Get the complete error message.
            echo Utils::toJSONString($exception);
            # Get a specific field from the error.
            echo $exception->getCode();
        }
    }
}
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
    require_once $path;
}
// $argv is a reserved array for input parameters and does not need to be modified.
SegmentCommonImage::main(array_slice($argv, 1));
// Install dependencies.
// 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({
    // For information on how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
    // If you use the AccessKey pair of a RAM user, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
    // Obtain the AccessKey ID and AccessKey Secret from environment variables. You must configure environment variables before running the sample code. 
    accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,   
    accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET
});
// The endpoint of the service.
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) {
    // Get the entire result.
    console.log(segmentCommonImageResponse);
    // Get a specific field.
    console.log(segmentCommonImageResponse.body.data);
  }, function(error) {
    // Get the complete error message.
    console.log(error);
    // Get a specific field from the error.
    console.log(error.data.Code);
  })
/**
This code depends on github.com/alibabacloud-go/imageseg-20191230/v2.
We recommend that you use `go mod tidy` to install the dependency.
 */

import (
	"fmt"
	"os"
	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() {
  // For information on how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
  // If you use the AccessKey pair of a RAM user, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
  // Obtain the AccessKey ID and AccessKey Secret from environment variables. You must configure environment variables before running the sample code.  
  accessKeyId := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")  
  accessKeySecret := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
  // Initialize the configuration object &openapi.Config. The Config object stores configuration parameters such as your AccessKey ID, AccessKey Secret, and endpoint.
  config := &openapi.Config{
    AccessKeyId: tea.String(accessKeyId),
    AccessKeySecret: tea.String(accessKeySecret)
	}
	// The endpoint of the service.
	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 {
		// Get the complete error message.
		fmt.Println(err.Error())
	} else {
		// Get the entire result.
		fmt.Println(segmentCommonImageResponse)
	}
}
// Install dependencies.
// 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
    {
      /**
          * Initialize the client by using an AccessKey pair.
          * @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,
            };
            // The endpoint of the service.
            config.Endpoint = "imageseg.cn-shanghai.aliyuncs.com";
            return new AlibabaCloud.SDK.Imageseg20191230.Client(config);
        }
        public static void Main(string[] args)
        {
            // For information on how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
            // If you use the AccessKey pair of a RAM user, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
            // Obtain the AccessKey ID and AccessKey Secret from environment variables. You must configure environment variables before running the sample code.
            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);
                // Get the entire result.
                Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(segmentCommonImageResponse.Body));
                // Get a specific field.
                Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(segmentCommonImageResponse.Body.Data));
            }
            catch (TeaException error)
            {
                // If an error occurs, print the error message.
                Console.WriteLine(AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message));
            }
            catch (Exception _error)
            {
                TeaException error = new TeaException(new Dictionary<string, object>
              {
                { "message", _error.Message }
              });
                // If an error occurs, print the error message.
                Console.WriteLine(AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message));
            }
        }
    }
}

Local file or public 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 {
        /*
          Initialize the configuration object com.aliyun.teaopenapi.models.Config.
          The Config object stores configuration parameters such as your AccessKey ID, AccessKey Secret, and endpoint.
         */
         com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        // The endpoint of the service.
        config.endpoint = "imageseg.cn-shanghai.aliyuncs.com";
        return new com.aliyun.imageseg20191230.Client(config);
    }

    public static void main(String[] args_) throws Exception {
        // For information on how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
        // If you use the AccessKey pair of a RAM user, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
        // Obtain the AccessKey ID and AccessKey Secret from environment variables. You must configure environment variables before running the sample code.
        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);
        // Scenario 1: Use a local file.
        // InputStream inputStream = new FileInputStream(new File("/tmp/SegmentCommonImage.jpg"));
        // Scenario 2: Use a public URL.
        URL url = new URL("http://viapi-test.oss-cn-shanghai.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);
            // Get the entire result.
            System.out.println(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(segmentCommonImageResponse)));
            // Get a specific field.
            System.out.println(segmentCommonImageResponse.getBody().data.imageURL);
        } catch (TeaException teaException) {
            // Get the complete error message.
            System.out.println(com.aliyun.teautil.Common.toJSONString(teaException));
            // Get a specific field from the error.
            System.out.println(teaException.getCode());
        }
    }
}
# -*- coding: utf-8 -*-
# Import the required dependencies.
# 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(
    # For information on how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
    # If you use the AccessKey pair of a RAM user, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
    # Obtain the AccessKey ID and AccessKey Secret from environment variables. You must configure environment variables before running the sample code.
    access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
    access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
    # The endpoint of the service.
    endpoint='imageseg.cn-shanghai.aliyuncs.com',
    # The region ID that corresponds to the endpoint.
    region_id='cn-shanghai'
)
segment_common_image_request = SegmentCommonImageAdvanceRequest()
# Scenario 1: Use a local file.
# stream = open(r'/tmp/SegmentCommonImage.png', 'rb')
# segment_common_image_request.image_urlobject = stream

# Scenario 2: Use a public URL.
url = 'http://viapi-test.oss-cn-shanghai.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:
  # Initialize the client.
  client = Client(config)
  response = client.segment_common_image_advance(segment_common_image_request, runtime)
  # Get the entire result.
  print(response.body)
except Exception as error:
  # Get the complete error message.
  print(error)
  # Get a specific field from the error.
  print(error.code)
  # Tip: You can view attribute names by using error.__dict__.
<?php

// Install dependencies.
// 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 {

    /**
     * Initialize the client by using an AccessKey pair.
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Imageseg Client
     */
    public static function createClient($accessKeyId, $accessKeySecret){
        // Initialize the configuration object Darabonba\OpenApi\Models\Config.
        // The Config object stores configuration parameters such as your accessKeyId, accessKeySecret, and endpoint.
        $config = new Config([
            "accessKeyId" => $accessKeyId,
            "accessKeySecret" => $accessKeySecret
        ]);
        // The endpoint of the service.
        $config->endpoint = "imageseg.cn-shanghai.aliyuncs.com";
        return new Imageseg($config);
    }
    /**
     * @param string[] $args
     * @return void
     */
    public static function main($args){
        // For information on how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
        // If you use the AccessKey pair of a RAM user, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
        // Obtain the AccessKey ID and AccessKey Secret from environment variables. You must configure environment variables before running the sample code.    
        $accessKeyId = getenv('ALIBABA_CLOUD_ACCESS_KEY_ID');      
        $accessKeySecret = getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET');
        $client = self::createClient($accessKeyId, $accessKeySecret);
        // Scenario 1: Use a local file.
        // $file = fopen('/tmp/SegmentCommonImage1.jpg', 'rb');
        // $stream = new Stream($file);
        // Scenario 2: Use a public URL.
        $file = fopen('http://viapi-test.oss-cn-shanghai.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);
            # Get the entire result.
            echo Utils::toJSONString($resp->body);
        } catch (Exception $exception) {
            # Get the complete error message.
            echo Utils::toJSONString($exception);
            # Get a specific field from the error.
            echo $exception->getCode();
        }
    }
}
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
    require_once $path;
}
// $argv is a reserved array for input parameters and does not need to be modified.
SegmentCommonImageAdvance::main(array_slice($argv, 1));
// Install dependencies.
// 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({
    // For information on how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
    // If you use the AccessKey pair of a RAM user, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
    // Obtain the AccessKey ID and AccessKey Secret from environment variables. You must configure environment variables before running the sample code. 
    accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,   
    accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET
});
// The endpoint of the service.
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();
    // Scenario 1: Use a local file.
    // const fileStream = fs.createReadStream('/tmp/SegmentCommonImage1.jpg');
    // segmentCommonImageAdvanceRequest.imageURLObject = fileStream;
    // Scenario 2: Use a public URL.
    const url = new URL("http://viapi-test.oss-cn-shanghai.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) {
        // Get the entire result.
        console.log(segmentCommonImageResponse);
        // Get a specific field.
        console.log(segmentCommonImageResponse.body.data);
      }, function (error) {
        // Get the complete error message.
        console.log(error);
        // Get a specific field from the error.
        console.log(error.data.Code);
      })
  } catch (error) {
    console.log(error);
  }
}();
/**
This code depends on github.com/alibabacloud-go/imageseg-20191230/v2.
We recommend that you use `go mod tidy` to install the dependency.
 */

import (
	"fmt"
	"net/http"
	"os"
	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() {
  // For information on how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
  // If you use the AccessKey pair of a RAM user, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
  // Obtain the AccessKey ID and AccessKey Secret from environment variables. You must configure environment variables before running the sample code.  
  accessKeyId := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")  
  accessKeySecret := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
  // Initialize the configuration object &openapi.Config. The Config object stores configuration parameters such as your AccessKey ID, AccessKey Secret, and endpoint.
  config := &openapi.Config{
    AccessKeyId: tea.String(accessKeyId),
    AccessKeySecret: tea.String(accessKeySecret)
	}
	// The endpoint of the service.
	config.Endpoint = tea.String("imageseg.cn-shanghai.aliyuncs.com")
	client, err := imageseg20191230.NewClient(config)
	if err != nil {
		panic(err)
	}
	// Scenario 1: Use a local file.
	//file, err := os.Open("/tmp/SegmentCommonImage.png")
	//if err != nil {
	//	fmt.Println("can not open file", err)
	//	panic(err)
	//}
	//segmentCommonImageAdvanceRequest := &imageseg20191230.SegmentCommonImageAdvanceRequest{
	//	ImageURLObject: file,
	//}
	// Scenario 2: Use a public URL.
	httpClient := http.Client{}
	file, _ := httpClient.Get("http://viapi-test.oss-cn-shanghai.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 {
		// Get the complete error message.
		fmt.Println(err.Error())
	} else {
		// Get the entire result.
		fmt.Println(segmentCommonImageAdvanceResponse)
	}
}
// Install dependencies.
// dotnet add package AlibabaCloud.SDK.Imageseg20191230
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using AlibabaCloud.SDK.Imageseg20191230.Models;
using Tea;
using Tea.Utils;

namespace AlibabaCloud.SDK.Sample
{
    public class Sample
    {
        /**
        * Initialize the client by using an AccessKey pair.
        * @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,
            };
            // The endpoint of the service.
            config.Endpoint = "imageseg.cn-shanghai.aliyuncs.com";
            return new AlibabaCloud.SDK.Imageseg20191230.Client(config);
        }
        public static void Main(string[] args)
        {
            // For information on how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
            // If you use the AccessKey pair of a RAM user, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
            // Obtain the AccessKey ID and AccessKey Secret from environment variables. You must configure environment variables before running the sample code.
            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
            ();
            // Scenario 1: Use a local file.
            //System.IO.StreamReader file = new System.IO.StreamReader(@"/tmp/SegmentCommonImage1.jpg");
            //segmentCommonImageAdvanceRequest.ImageURLObject = file.BaseStream;

            // Scenario 2: Use a public URL.
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/imageseg/SegmentCommonImage/SegmentCommonImage1.jpg");
            WebResponse response = request.GetResponse();
            Stream stream = response.GetResponseStream();
            segmentCommonImageAdvanceRequest.ImageURLObject = stream;
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            try
            {
                AlibabaCloud.SDK.Imageseg20191230.Models.SegmentCommonImageResponse segmentCommonImageResponse = client.SegmentCommonImageAdvance(segmentCommonImageAdvanceRequest, runtime);
                // Get the entire result.
                Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(segmentCommonImageResponse.Body));
                // Get a specific field.
                Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(segmentCommonImageResponse.Body.Data));
            }
            catch (TeaException error)
            {
                // If an error occurs, print the error message.
                Console.WriteLine(AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message));
            }
            catch (Exception _error)
            {
                TeaException error = new TeaException(new Dictionary<string, object>
              {
                { "message", _error.Message }
              });
                // If an error occurs, print the error message.
                Console.WriteLine(AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message));
            }
        }
    }
}

Post-processing examples

Background blending

After you call the general image segmentation API, you receive a four-channel image of the foreground object. You can then blend this object with a new background image.

The following Python code demonstrates this operation.

  1. Install the required dependencies. This example uses OpenCV. For more information, see OpenCV.

    pip install opencv-python
  2. Download the segmented image to your computer and place it in the data folder along with the source image and the background image.

    Background image:image

    The following is the sample code:

    import argparse
    import math
    import cv2
    from typing import List
    import numpy as np
    import urllib.request
    # Change the background.
    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]]
        # Blend the segmented image with a new background.
        rst_image = image_merge_background(sc_image, seg_img, bg_image)
        # Save the result to a local file.
        cv2.imwrite(of_file, rst_image)
    # Blend the segmented image with the background 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 the 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
        # Blend the foreground onto the background by using the mask.
        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)

    The following figure shows the result:

    image

    For the complete code for background blending, see merge_background.

    Note

    After you extract the code package, run the python merge_background.py command. The background image in the sample code must be in JPG format.