This document provides sample code for Video Human Matting in various programming languages for common scenarios.
-
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.
Capability overview
For an overview of Video Human Matting and its request parameters, see Video Human Matting.
SDK installation
For SDK dependencies across different programming languages, see SDK Overview.
Configure environment variables
Configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.
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
Open a terminal in IntelliJ IDEA.
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_IDandALIBABA_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.Open File Explorer, right-click This PC, and then select Properties.
In the left-side navigation pane, click Advanced system settings.
On the Advanced tab of the System Properties dialog box, click Environment Variables.
In the Environment Variables dialog box, click New.
In the New System Variable dialog box, add the environment variables
ALIBABA_CLOUD_ACCESS_KEY_IDandALIBABA_CLOUD_ACCESS_KEY_SECRET, and set them to the AccessKey ID and AccessKey Secret that you have prepared.Restart the Windows operating system for the configurations to take effect.
Sample code
File from an OSS bucket
For sample code in common languages on how to query the results of an asynchronous task, see Query asynchronous task results.
// Add the dependency.
// Minimum SDK version required: 1.0.3 for videoseg20200320.
// You can find the latest SDK version in this repository: https://mvnrepository.com/artifact/com.aliyun/videoseg20200320
// <dependency>
// <groupId>com.aliyun</groupId>
// <artifactId>videoseg20200320</artifactId>
// <version>${aliyun.videoseg.version}</version>
// </dependency>
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaModel;
import com.aliyun.videoseg20200320.models.SegmentVideoBodyResponse;
public class SegmentVideoBody {
public static com.aliyun.videoseg20200320.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
/*
Initialize the configuration object com.aliyun.teaopenapi.models.Config.
This object stores configuration details 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 service endpoint.
config.endpoint = "videoseg.cn-shanghai.aliyuncs.com";
return new com.aliyun.videoseg20200320.Client(config);
}
public static void main(String[] args) throws Exception {
// For information about how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you use a RAM user's AccessKey, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
// Read the AccessKey ID and AccessKey Secret from environment variables. You must configure these 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.videoseg20200320.Client client = SegmentVideoBody.createClient(accessKeyId, accessKeySecret);
com.aliyun.videoseg20200320.models.SegmentVideoBodyRequest segmentVideoBodyRequest = new com.aliyun.videoseg20200320.models.SegmentVideoBodyRequest()
.setVideoUrl("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/videoseg/SegmentVideoBody/SegmentVideoBody1.mp4");
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
// Print the API response when you run the code.
SegmentVideoBodyResponse response = client.segmentVideoBodyWithOptions(segmentVideoBodyRequest, runtime);
System.out.println(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(response)));
} catch (TeaException error) {
// Get the complete error message.
System.out.println(com.aliyun.teautil.Common.toJSONString(error));
// Get a specific field from the error message.
System.out.println(error.getCode());
}
}
}# -*- coding: utf-8 -*-
# Install the dependency.
# pip install alibabacloud_videoseg20200320
# Minimum SDK version required: 3.0.2 for videoseg20200320.
# You can find the latest SDK version in this repository: https://pypi.org/project/alibabacloud-videoseg20200320/
import os
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptions
from alibabacloud_videoseg20200320.client import Client
from alibabacloud_videoseg20200320.models import SegmentVideoBodyRequest
config = Config(
# For information about how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
# If you use a RAM user's AccessKey, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
# Read the AccessKey ID and AccessKey Secret from environment variables. You must configure these 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 service endpoint.
endpoint='videoseg.cn-shanghai.aliyuncs.com',
# The region ID of the endpoint.
region_id='cn-shanghai'
)
segment_video_body_request = SegmentVideoBodyRequest(
video_url='http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/videoseg/SegmentVideoBody/SegmentVideoBody1.mp4'
)
runtime = RuntimeOptions()
try:
# Initialize the client.
client = Client(config)
response = client.segment_video_body_with_options(segment_video_body_request, runtime)
# Get the complete result.
print(response.body)
except Exception as error:
# Get the complete error message.
print(error)
# Get a specific field from the error message.
print(error.code)<?php
// Install the dependency.
// Minimum SDK version required: 1.0.4 for videoseg-20200320.
// You can find the latest SDK version in this repository: https://packagist.org/packages/alibabacloud/videoseg-20200320
// composer require alibabacloud/videoseg-20200320
use AlibabaCloud\SDK\Videoseg\V20200320\Videoseg;
use \Exception;
use AlibabaCloud\Tea\Utils\Utils;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Videoseg\V20200320\Models\SegmentVideoBodyRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
class SegmentVideoBody {
/**
* Initialize the client by using an AccessKey pair.
* @param string $accessKeyId
* @param string $accessKeySecret
* @return Videoseg Client
*/
public static function createClient($accessKeyId, $accessKeySecret){
// Initialize the configuration object Darabonba\OpenApi\Models\Config.
// This object stores configuration details such as your AccessKey ID, AccessKey Secret, and endpoint.
$config = new Config([
"accessKeyId" => $accessKeyId,
"accessKeySecret" => $accessKeySecret
]);
// The service endpoint.
$config->endpoint = "videoseg.cn-shanghai.aliyuncs.com";
return new Videoseg($config);
}
/**
* @param string[] $args
* @return void
*/
public static function main($args){
// For information about how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you use a RAM user's AccessKey, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
// Read the AccessKey ID and AccessKey Secret from environment variables. You must configure these 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);
$segmentVideoBodyRequest = new SegmentVideoBodyRequest([
"videoUrl" => "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/videoseg/SegmentVideoBody/SegmentVideoBody1.mp4"
]);
$runtime = new RuntimeOptions([]);
try {
$resp = $client->segmentVideoBodyWithOptions($segmentVideoBodyRequest, $runtime);
# Get the complete 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 message.
echo $exception->getCode();
}
}
}
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
require_once $path;
}
// The $argv array is reserved for input parameters and does not need to be modified.
SegmentVideoBody::main(array_slice($argv, 1));// Install the dependency.
// npm install @alicloud/videoseg20200320
// Minimum SDK version required: 3.0.2 for videoseg20200320.
// You can find the latest SDK version in this repository: https://npmjs.com/package/@alicloud/videoseg20200320
const VideosegClient = require('@alicloud/videoseg20200320');
const OpenapiClient = require('@alicloud/openapi-client');
const TeaUtil = require('@alicloud/tea-util');
let config = new OpenapiClient.Config({
// For information about how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you use a RAM user's AccessKey, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
// Read the AccessKey ID and AccessKey Secret from environment variables. You must configure these variables before running the sample code.
accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET
});
// The service endpoint.
config.endpoint = `videoseg.cn-shanghai.aliyuncs.com`;
const client = new VideosegClient.default(config);
let segmentVideoBodyRequest = new VideosegClient.SegmentVideoBodyRequest({
videoUrl: "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/videoseg/SegmentVideoBody/SegmentVideoBody1.mp4",
});
let runtime = new TeaUtil.RuntimeOptions({ });
client.segmentVideoBodyWithOptions(segmentVideoBodyRequest, runtime)
.then(function(segmentVideoBodyResponse) {
// Get the complete result.
console.log(segmentVideoBodyResponse);
// Get a specific field from the result.
console.log(segmentVideoBodyResponse.body.data);
}, function(error) {
// Get the complete error message.
console.log(error);
// Get a specific field from the error message.
console.log(error.data.Code);
})// Install the dependency.
// Minimum SDK version required: 2.0.3 for videoseg20200320.
// You can find the latest SDK version in this repository: github.com/alibabacloud-go/videoseg-20200320/v2
// go get github.com/alibabacloud-go/videoseg-20200320/v2
package main
import (
"fmt"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
util "github.com/alibabacloud-go/tea-utils/v2/service"
"github.com/alibabacloud-go/tea/tea"
videoseg20200320 "github.com/alibabacloud-go/videoseg-20200320/v2/client"
"os"
)
func main() {
// For information about how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you use a RAM user's AccessKey, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
// Read the AccessKey ID and AccessKey Secret from environment variables. You must configure these 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. This object stores configuration details such as your AccessKey ID, AccessKey Secret, and endpoint.
config := &openapi.Config{
AccessKeyId: tea.String(accessKeyId),
AccessKeySecret: tea.String(accessKeySecret),
}
// The service endpoint.
config.Endpoint = tea.String("videoseg.cn-shanghai.aliyuncs.com")
client, err := videoseg20200320.NewClient(config)
if err != nil {
fmt.Println(err.Error())
}
segmentVideoBodyRequest := &videoseg20200320.SegmentVideoBodyRequest{
VideoUrl: tea.String("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/videoseg/SegmentVideoBody/SegmentVideoBody1.mp4"),
}
runtime := &util.RuntimeOptions{}
segmentVideoBodyResponse, _err := client.SegmentVideoBodyWithOptions(segmentVideoBodyRequest, runtime)
if _err != nil {
fmt.Println(_err.Error())
} else {
// Get the complete result.
fmt.Println(segmentVideoBodyResponse)
// Get a specific field from the result.
fmt.Println(segmentVideoBodyResponse.Body.Data)
}
}// Install the dependency.
// dotnet add package AlibabaCloud.SDK.Videoseg20200320
// Minimum SDK version required: 2.0.2 for videoseg20200320.
// You can find the latest SDK version in this repository: https://nuget.org/packages/AlibabaCloud.SDK.Videoseg20200320
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using AlibabaCloud.SDK.Videoseg20200320.Models;
using Tea;
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.Videoseg20200320.Client CreateClient(string accessKeyId, string accessKeySecret)
{
AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
{
AccessKeyId = accessKeyId,
AccessKeySecret = accessKeySecret,
};
// The service endpoint.
config.Endpoint = "videoseg.cn-shanghai.aliyuncs.com";
return new AlibabaCloud.SDK.Videoseg20200320.Client(config);
}
public static void Main(string[] args)
{
// For information about how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you use a RAM user's AccessKey, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
// Read the AccessKey ID and AccessKey Secret from environment variables. You must configure these variables before running the sample code.
AlibabaCloud.SDK.Videoseg20200320.Client client = CreateClient(System.Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"), System.Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
SegmentVideoBodyRequest segmentVideoBodyRequest = new SegmentVideoBodyRequest
{
VideoUrl = "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/videoseg/SegmentVideoBody/SegmentVideoBody1.mp4",
};
AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
try
{
SegmentVideoBodyResponse segmentVideoBodyResponse = client.SegmentVideoBodyWithOptions(segmentVideoBodyRequest, runtime);
// Get the complete result.
Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(segmentVideoBodyResponse.Body));
// Get a specific field from the result.
Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(segmentVideoBodyResponse.Body.Data));
}
catch (TeaException error)
{
// Print the error if necessary.
AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
}
catch (Exception _error)
{
TeaException error = new TeaException(new Dictionary<string, object>
{
{ "message", _error.Message }
});
// Print the error if necessary.
Console.WriteLine(error.Message);
}
}
}
}Local file or public URL
For sample code in common languages on how to query the results of an asynchronous task, see Query asynchronous task results.
// Add the dependency.
// Minimum SDK version required: 1.0.3 for videoseg20200320.
// You can find the latest SDK version in this repository: https://mvnrepository.com/artifact/com.aliyun/videoseg20200320
// <dependency>
// <groupId>com.aliyun</groupId>
// <artifactId>videoseg20200320</artifactId>
// <version>${aliyun.videoseg.version}</version>
// </dependency>
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaModel;
import com.aliyun.videoseg20200320.models.SegmentVideoBodyResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
public class SegmentVideoBody {
public static com.aliyun.videoseg20200320.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
/*
Initialize the configuration object com.aliyun.teaopenapi.models.Config.
This object stores configuration details 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 service endpoint.
config.endpoint = "videoseg.cn-shanghai.aliyuncs.com";
return new com.aliyun.videoseg20200320.Client(config);
}
public static void main(String[] args) throws Exception {
// For information about how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you use a RAM user's AccessKey, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
// Read the AccessKey ID and AccessKey Secret from environment variables. You must configure these 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.videoseg20200320.Client client = SegmentVideoBody.createClient(accessKeyId, accessKeySecret);
// Scenario 1: Use a local file.
//InputStream inputStream = new FileInputStream(new File("/tmp/SegmentVideoBody1.mp4"));
// Scenario 2: Use a file from any publicly accessible URL.
URL url = new URL("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/videoseg/SegmentVideoBody/SegmentVideoBody1.mp4");
InputStream inputStream = url.openConnection().getInputStream();
com.aliyun.videoseg20200320.models.SegmentVideoBodyAdvanceRequest segmentVideoBodyAdvanceRequest = new com.aliyun.videoseg20200320.models.SegmentVideoBodyAdvanceRequest()
.setVideoUrlObject(inputStream);
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
// Print the API response when you run the code.
SegmentVideoBodyResponse response = client.segmentVideoBodyAdvance(segmentVideoBodyAdvanceRequest, runtime);
System.out.println(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(response)));
} catch (TeaException error) {
// Get the complete error message.
System.out.println(com.aliyun.teautil.Common.toJSONString(error));
// Get a specific field from the error message.
System.out.println(error.getCode());
}
}
}# -*- coding: utf-8 -*-
# Install the dependency.
# pip install alibabacloud_videoseg20200320
# Minimum SDK version required: 3.0.2 for videoseg20200320.
# You can find the latest SDK version in this repository: https://pypi.org/project/alibabacloud-videoseg20200320/
import os
import io
from urllib.request import urlopen
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptions
from alibabacloud_videoseg20200320.client import Client
from alibabacloud_videoseg20200320.models import SegmentVideoBodyAdvanceRequest
config = Config(
# For information about how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
# If you use a RAM user's AccessKey, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
# Read the AccessKey ID and AccessKey Secret from environment variables. You must configure these 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 service endpoint.
endpoint='videoseg.cn-shanghai.aliyuncs.com',
# The region ID of the endpoint.
region_id='cn-shanghai'
)
# Scenario 1: Use a local file.
#img = open(r'/tmp/SegmentVideoBody1.mp4', 'rb')
# Scenario 2: Use a file from any publicly accessible URL.
url = 'http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/videoseg/SegmentVideoBody/SegmentVideoBody1.mp4'
img = io.BytesIO(urlopen(url).read())
segment_video_body_request = SegmentVideoBodyAdvanceRequest()
segment_video_body_request.video_url_object = img
runtime = RuntimeOptions()
try:
# Initialize the client.
client = Client(config)
response = client.segment_video_body_advance(segment_video_body_request, runtime)
# Get the complete result.
print(response.body)
except Exception as error:
# Get the complete error message.
print(error)
# Get a specific field from the error message.
print(error.code)<?php
// Install the dependency.
// Minimum SDK version required: 1.0.4 for videoseg-20200320.
// You can find the latest SDK version in this repository: https://packagist.org/packages/alibabacloud/videoseg-20200320
// composer require alibabacloud/videoseg-20200320
use AlibabaCloud\SDK\Videoseg\V20200320\Videoseg;
use \Exception;
use AlibabaCloud\Tea\Utils\Utils;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Videoseg\V20200320\Models\SegmentVideoBodyAdvanceRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use GuzzleHttp\Psr7\Stream;
class SegmentVideoBodyAdvance {
/**
* Initialize the client by using an AccessKey pair.
* @param string $accessKeyId
* @param string $accessKeySecret
* @return Videoseg Client
*/
public static function createClient($accessKeyId, $accessKeySecret){
// Initialize the configuration object Darabonba\OpenApi\Models\Config.
// This object stores configuration details such as your AccessKey ID, AccessKey Secret, and endpoint.
$config = new Config([
"accessKeyId" => $accessKeyId,
"accessKeySecret" => $accessKeySecret
]);
// The service endpoint.
$config->endpoint = "videoseg.cn-shanghai.aliyuncs.com";
return new Videoseg($config);
}
/**
* @param string[] $args
* @return void
*/
public static function main($args){
// For information about how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you use a RAM user's AccessKey, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
// Read the AccessKey ID and AccessKey Secret from environment variables. You must configure these 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/SegmentVideoBody1.mp4', 'rb');
//$stream = new Stream($file);
// Scenario 2: Use a file from any publicly accessible URL.
$file = fopen('http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/videoseg/SegmentVideoBody/SegmentVideoBody1.mp4', 'rb');
$stream = new Stream($file);
$segmentVideoBodyAdvanceRequest = new SegmentVideoBodyAdvanceRequest([
"videoUrlObject" => $stream
]);
$runtime = new RuntimeOptions([]);
try {
$resp = $client->segmentVideoBodyAdvance($segmentVideoBodyAdvanceRequest, $runtime);
# Get the complete 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 message.
echo $exception->getCode();
}
}
}
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
require_once $path;
}
// The $argv array is reserved for input parameters and does not need to be modified.
SegmentVideoBodyAdvance::main(array_slice($argv, 1));// Install the dependency.
// npm install @alicloud/videoseg20200320
// Minimum SDK version required: 3.0.2 for videoseg20200320.
// You can find the latest SDK version in this repository: https://npmjs.com/package/@alicloud/videoseg20200320
const VideosegClient = require('@alicloud/videoseg20200320');
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 about how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you use a RAM user's AccessKey, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
// Read the AccessKey ID and AccessKey Secret from environment variables. You must configure these variables before running the sample code.
accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET
});
// The service endpoint.
config.endpoint = `videoseg.cn-shanghai.aliyuncs.com`;
const client = new VideosegClient.default(config);
const getResponse = function (httpClient, url) {
return new Promise((resolve, reject) => {
httpClient.get(url, function (response) {
resolve(response);
})
})
}
const request = async function () {
try {
const segmentVideoBodyAdvanceRequest = new VideosegClient.SegmentVideoBodyAdvanceRequest();
// Scenario 1: Use a local file.
// const fileStream = fs.createReadStream('/tmp/SegmentVideoBody1.mp4');
// segmentVideoBodyAdvanceRequest.videoUrlObject = fileStream;
// Scenario 2: Use a file from any publicly accessible URL.
const url = new URL("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/videoseg/SegmentVideoBody/SegmentVideoBody1.mp4");
const httpClient = (url.protocol == "https:") ? https : http;
segmentVideoBodyAdvanceRequest.videoUrlObject = await getResponse(httpClient, url);
let runtime = new TeaUtil.RuntimeOptions({});
client.segmentVideoBodyAdvance(segmentVideoBodyAdvanceRequest, runtime)
.then(function (segmentVideoBodyResponse) {
// Get the complete result.
console.log(segmentVideoBodyResponse);
// Get a specific field from the result.
//console.log(segmentVideoBodyResponse.body.data);
}, function (error) {
// Get the complete error message.
console.log(error);
// Get a specific field from the error message.
console.log(error.data.Code);
})
} catch (error) {
console.log(error);
}
}();// Install the dependency.
// Minimum SDK version required: 2.0.3 for videoseg20200320.
// You can find the latest SDK version in this repository: github.com/alibabacloud-go/videoseg-20200320/v2
// go get github.com/alibabacloud-go/videoseg-20200320/v2
package main
import (
"fmt"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
util "github.com/alibabacloud-go/tea-utils/v2/service"
"github.com/alibabacloud-go/tea/tea"
videoseg20200320 "github.com/alibabacloud-go/videoseg-20200320/v2/client"
"net/http"
"os"
)
func main() {
// For information about how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you use a RAM user's AccessKey, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
// Read the AccessKey ID and AccessKey Secret from environment variables. You must configure these 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. This object stores configuration details such as your AccessKey ID, AccessKey Secret, and endpoint.
config := &openapi.Config{
AccessKeyId: tea.String(accessKeyId),
AccessKeySecret: tea.String(accessKeySecret),
}
// The service endpoint.
config.Endpoint = tea.String("videoseg.cn-shanghai.aliyuncs.com")
client, err := videoseg20200320.NewClient(config)
if err != nil {
fmt.Println(err.Error())
}
// Scenario 1: Use a local file.
//file, err := os.Open("/tmp/SegmentVideoBody1.mp4")
//if err != nil {
// fmt.Println("can not open file", err)
//}
//segmentVideoBodyAdvanceRequest := &videoseg20200320.SegmentVideoBodyAdvanceRequest{
// VideoUrlObject: file,
//}
// Scenario 2: Use a file from any publicly accessible URL.
httpClient := http.Client{}
file1, _ := httpClient.Get("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/videoseg/SegmentVideoBody/SegmentVideoBody1.mp4")
segmentVideoBodyAdvanceRequest := &videoseg20200320.SegmentVideoBodyAdvanceRequest{
VideoUrlObject: file1.Body,
}
runtime := &util.RuntimeOptions{}
segmentVideoBodyResponse, _err := client.SegmentVideoBodyAdvance(segmentVideoBodyAdvanceRequest, runtime)
if _err != nil {
fmt.Println(_err.Error())
} else {
// Get the complete result.
fmt.Println(segmentVideoBodyResponse)
// Get a specific field from the result.
fmt.Println(segmentVideoBodyResponse.Body.Data)
}
}// Install the dependency.
// dotnet add package AlibabaCloud.SDK.Videoseg20200320
// Minimum SDK version required: 2.0.2 for videoseg20200320.
// You can find the latest SDK version in this repository: https://nuget.org/packages/AlibabaCloud.SDK.Videoseg20200320
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using AlibabaCloud.SDK.Videoseg20200320.Models;
using Tea;
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.Videoseg20200320.Client CreateClient(string accessKeyId, string accessKeySecret)
{
AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
{
AccessKeyId = accessKeyId,
AccessKeySecret = accessKeySecret,
};
// The service endpoint.
config.Endpoint = "videoseg.cn-shanghai.aliyuncs.com";
return new AlibabaCloud.SDK.Videoseg20200320.Client(config);
}
public static void Main(string[] args)
{
// For information about how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you use a RAM user's AccessKey, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
// Read the AccessKey ID and AccessKey Secret from environment variables. You must configure these variables before running the sample code.
AlibabaCloud.SDK.Videoseg20200320.Client client = CreateClient(System.Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"), System.Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
SegmentVideoBodyAdvanceRequest segmentVideoBodyAdvanceRequest = new SegmentVideoBodyAdvanceRequest
();
// Scenario 1: Use a local file.
//System.IO.StreamReader file = new System.IO.StreamReader(@"/tmp/SegmentVideoBody1.mp4");
//segmentVideoBodyAdvanceRequest.VideoUrlObject = file.BaseStream;
// Scenario 2: Use a file from any publicly accessible URL.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/videoseg/SegmentVideoBody/SegmentVideoBody1.mp4");
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
segmentVideoBodyAdvanceRequest.VideoUrlObject = stream;
AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
try
{
SegmentVideoBodyResponse segmentVideoBodyResponse = client.SegmentVideoBodyAdvance(segmentVideoBodyAdvanceRequest, runtime);
// Get the complete result.
Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(segmentVideoBodyResponse.Body));
// Get a specific field from the result.
Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(segmentVideoBodyResponse.Body.Data));
}
catch (TeaException error)
{
// Print the error if necessary.
AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
}
catch (Exception _error)
{
TeaException error = new TeaException(new Dictionary<string, object>
{
{ "message", _error.Message }
});
// Print the error if necessary.
Console.WriteLine(error.Message);
}
}
}
}Common post-processing tasks
Mask video compositing
After calling the Video Human Matting API, you receive a mask video. You can then composite this mask video with a background image to complete the matting effect.
Install the required dependencies. This example uses OpenCV. For more information, see OpenCV.
pip install opencv-pythonDownload the mask video and place it in a
datafolder with the original video and a background image.Background image:

Sample code:
import cv2 import numpy as np # Path to the original video video_root = './data/video.mp4' # Path to the local mask video returned by the Video Human Matting API mask_root = './data/mask.mp4' video = cv2.VideoCapture(video_root) mask = cv2.VideoCapture(mask_root) rval, frame = video.read() rval_mask, frame_mask = mask.read() fps = video.get(cv2.CAP_PROP_FPS) h, w = frame.shape[:2] fourcc = cv2.VideoWriter_fourcc(*'mp4v') video_writer = cv2.VideoWriter('com.mp4', fourcc, fps, (w, h)) num_frame = video.get(cv2.CAP_PROP_FRAME_COUNT) # Path to the background image background_root = './data/img.jpg' background = cv2.imread(background_root) background = cv2.resize(background, (w, h)) for c in range(0,int(num_frame)): if (frame is None) or (frame_mask is None): continue fg_com = frame * (frame_mask/255) + background * (1-frame_mask/255) video_writer.write(fg_com.astype(np.uint8)) rval, frame = video.read() rval_mask, frame_mask = mask.read() video_writer.release()Resulting video:
For the complete code for compositing the segmented human figure with a background, see com_back.
NoteAfter you decompress the code package, run python com_back.py. The sample code composites the video with any three-channel image as the background.