Shot detection
This topic provides code samples that show how to perform shot detection in common programming languages and scenarios.
For live support, visit Contact Us.
For inquiries about API integration, usage, or other topics related to the Vision AI Open Platform, join our DingTalk group (ID: 23109592).
Overview
For a feature overview and detailed parameter descriptions, see Shot detection.
SDK installation
For information about the SDK dependencies for common 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.
Code samples
Video file in OSS (Shanghai)
For sample code on how to query the results of an asynchronous task in common languages, see Query asynchronous task results.
/*
Import the dependency.
<!-- https://mvnrepository.com/artifact/com.aliyun/videorecog20200320 -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>videorecog20200320</artifactId>
<version>${aliyun.videorecog.version}</version>
</dependency>
*/
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaModel;
import com.aliyun.videorecog20200320.models.DetectVideoShotResponse;
public class DetectVideoShot {
public static com.aliyun.videorecog20200320.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
/*
Initialize a Config object with your AccessKey ID, AccessKey Secret, and service endpoint.
*/
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
.setAccessKeyId(accessKeyId)
.setAccessKeySecret(accessKeySecret);
// The endpoint of the service.
config.endpoint = "videorecog.cn-shanghai.aliyuncs.com";
return new com.aliyun.videorecog20200320.Client(config);
}
public static void main(String[] args_) throws Exception {
// To create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you are using 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 set the 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.videorecog20200320.Client client = DetectVideoShot.createClient(accessKeyId, accessKeySecret);
com.aliyun.videorecog20200320.models.DetectVideoShotRequest detectVideoShotRequest = new com.aliyun.videorecog20200320.models.DetectVideoShotRequest()
.setVideoUrl("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/videorecog/DetectVideoShot/DetectVideoShot1.mp4");
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
DetectVideoShotResponse detectVideoShotResponse = client.detectVideoShotWithOptions(detectVideoShotRequest, runtime);
// Get the full response.
System.out.println(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(detectVideoShotResponse)));
// Get a specific field.
System.out.println(detectVideoShotResponse.getBody().getData());
} catch (TeaException teaException) {
// Get the full error message.
System.out.println(com.aliyun.teautil.Common.toJSONString(teaException));
// Get a specific field.
System.out.println(teaException.getCode());
}
}
}# -*- coding: utf-8 -*-
# Import the dependency.
# pip install alibabacloud_videorecog20200320
import os
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptions
from alibabacloud_videorecog20200320.client import Client
from alibabacloud_videorecog20200320.models import DetectVideoShotRequest
config = Config(
# To create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
# If you are using 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 set the 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='videorecog.cn-shanghai.aliyuncs.com',
# The region corresponding to the endpoint.
region_id='cn-shanghai'
)
detect_video_shot_request = DetectVideoShotRequest(
video_url='http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/videorecog/DetectVideoShot/DetectVideoShot2.mp4'
)
runtime = RuntimeOptions()
try:
# Initialize the client.
client = Client(config)
response = client.detect_video_shot_with_options(detect_video_shot_request, runtime)
# Get the full response.
print(response.body)
except Exception as error:
# Get the full error message.
print(error)
# Get a specific field.
print(error.code)
# Tip: You can view attribute names by using error.__dict__.<?php
// Install the dependency.
// composer require alibabacloud/videorecog-20200320
use AlibabaCloud\SDK\Videorecog\V20200320\Videorecog;
use AlibabaCloud\Tea\Utils\Utils;
use \Exception;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Videorecog\V20200320\Models\DetectVideoShotRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
class DetectVideoShot {
/**
* Use an AccessKey pair to initialize the client.
* @param string $accessKeyId
* @param string $accessKeySecret
* @return Videorecog Client
*/
public static function createClient($accessKeyId, $accessKeySecret){
// Initialize a Config object with your AccessKey ID, AccessKey Secret, and service endpoint.
$config = new Config([
"accessKeyId" => $accessKeyId,
"accessKeySecret" => $accessKeySecret
]);
// The endpoint of the service.
$config->endpoint = "videorecog.cn-shanghai.aliyuncs.com";
return new Videorecog($config);
}
/**
* @param string[] $args
* @return void
*/
public static function main($args){
// To create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you are using 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 set the 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);
$detectVideoShotRequest = new DetectVideoShotRequest([
"videoUrl" => "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/videorecog/DetectVideoShot/DetectVideoShot1.mp4"
]);
$runtime = new RuntimeOptions([]);
try {
$resp = $client->detectVideoShotWithOptions($detectVideoShotRequest, $runtime);
# Get the full response.
echo Utils::toJSONString($resp->body);
} catch (Exception $exception) {
# Get the full error message.
echo Utils::toJSONString($exception);
# Get a specific field.
echo $exception->getCode();
}
}
}
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
require_once $path;
}
// The $argv parameter is a reserved array for input arguments and has no practical significance. You do not need to modify it.
DetectVideoShot::main(array_slice($argv, 1));// Install the dependency.
// npm install @alicloud/videorecog20200320
const VideorecogClient = require('@alicloud/videorecog20200320');
const OpenapiClient = require('@alicloud/openapi-client');
const TeaUtil = require('@alicloud/tea-util');
let config = new OpenapiClient.Config({
// To create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you are using 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 set the 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 = `videorecog.cn-shanghai.aliyuncs.com`;
const client = new VideorecogClient.default(config);
let detectVideoShotRequest = new VideorecogClient.DetectVideoShotRequest({
videoUrl: "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/videorecog/DetectVideoShot/DetectVideoShot1.mp4",
});
let runtime = new TeaUtil.RuntimeOptions({ });
client.detectVideoShotWithOptions(detectVideoShotRequest, runtime)
.then(function(detectVideoShotResponse) {
// Get the full response.
console.log(detectVideoShotResponse);
// Get a specific field.
console.log(detectVideoShotResponse.body.data);
}, function(error) {
// Get the full error message.
console.log(error);
// Get a specific field.
console.log(error.data.Code);
})/**
This code depends on github.com/alibabacloud-go/videorecog-20200320/v2.
We recommend using 'go mod tidy' to install the dependency.
*/
import (
"fmt"
"os"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
util "github.com/alibabacloud-go/tea-utils/v2/service"
"github.com/alibabacloud-go/tea/tea"
videorecog20200320 "github.com/alibabacloud-go/videorecog-20200320/v2/client"
)
func main() {
// To create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you are using 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 set the environment variables before running the sample code.
accessKeyId := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
accessKeySecret := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
// Initialize a Config object with your AccessKey ID, AccessKey Secret, and service endpoint.
config := &openapi.Config{
AccessKeyId: tea.String(accessKeyId),
AccessKeySecret: tea.String(accessKeySecret),
}
// The endpoint of the service.
config.Endpoint = tea.String("videorecog.cn-shanghai.aliyuncs.com")
client, err := videorecog20200320.NewClient(config)
if err != nil {
panic(err)
}
detectVideoShotRequest := &videorecog20200320.DetectVideoShotRequest{
VideoUrl: tea.String("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/videorecog/DetectVideoShot/DetectVideoShot1.mp4"),
}
runtime := &util.RuntimeOptions{}
detectVideoShotResponse, err := client.DetectVideoShotWithOptions(detectVideoShotRequest, runtime)
if err != nil {
// Get the full error message.
fmt.Println(err.Error())
} else {
// Get the full response.
fmt.Println(detectVideoShotResponse)
}
}// Install the dependency.
// dotnet add package AlibabaCloud.SDK.Videorecog20200320
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using AlibabaCloud.SDK.Videorecog20200320.Models;
using Tea;
using Tea.Utils;
namespace AlibabaCloud.SDK.Sample
{
public class Sample
{
/**
* Use an AccessKey pair to initialize the client.
* @param accessKeyId
* @param accessKeySecret
* @return Client
* @throws Exception
*/
public static AlibabaCloud.SDK.Videorecog20200320.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 = "videorecog.cn-shanghai.aliyuncs.com";
return new AlibabaCloud.SDK.Videorecog20200320.Client(config);
}
public static void Main(string[] args)
{
// To create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you are using 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 set the environment variables before running the sample code.
AlibabaCloud.SDK.Videorecog20200320.Client client = CreateClient(System.Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"), System.Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
AlibabaCloud.SDK.Videorecog20200320.Models.DetectVideoShotRequest detectVideoShotRequest = new AlibabaCloud.SDK.Videorecog20200320.Models.DetectVideoShotRequest
{
VideoUrl = "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/videorecog/DetectVideoShot/DetectVideoShot1.mp4",
};
AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
try
{
AlibabaCloud.SDK.Videorecog20200320.Models.DetectVideoShotResponse detectVideoShotResponse = client.DetectVideoShotWithOptions(detectVideoShotRequest, runtime);
// Get the full response.
Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(detectVideoShotResponse.Body));
// Get a specific field.
Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(detectVideoShotResponse.Body.Data));
}
catch (TeaException error)
{
// Print the error if necessary.
Console.WriteLine(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(AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message));
}
}
}
}Local file or public URL
For sample code on how to query the results of an asynchronous task in common languages, see Query asynchronous task results.
/*
Import the dependency.
<!-- https://mvnrepository.com/artifact/com.aliyun/videorecog20200320 -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>videorecog20200320</artifactId>
<version>${aliyun.videorecog.version}</version>
</dependency>
*/
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaModel;
import com.aliyun.videorecog20200320.models.DetectVideoShotResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
public class DetectVideoShot {
public static com.aliyun.videorecog20200320.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
/*
Initialize a Config object with your AccessKey ID, AccessKey Secret, and service endpoint.
*/
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
.setAccessKeyId(accessKeyId)
.setAccessKeySecret(accessKeySecret);
// The endpoint of the service.
config.endpoint = "videorecog.cn-shanghai.aliyuncs.com";
return new com.aliyun.videorecog20200320.Client(config);
}
public static void main(String[] args_) throws Exception {
// To create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you are using 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 set the 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.videorecog20200320.Client client = DetectVideoShot.createClient(accessKeyId, accessKeySecret);
// Scenario 1: Use a local file.
// InputStream inputStream = new FileInputStream(new File("/tmp/detectVideoShot.mp4"));
// Scenario 2: Use any publicly accessible URL.
URL url = new URL("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/videorecog/DetectVideoShot/DetectVideoShot1.mp4");
InputStream inputStream = url.openConnection().getInputStream();
com.aliyun.videorecog20200320.models.DetectVideoShotAdvanceRequest detectVideoShotAdvanceRequest = new com.aliyun.videorecog20200320.models.DetectVideoShotAdvanceRequest()
.setVideoUrlObject(inputStream);
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
DetectVideoShotResponse detectVideoShotResponse = client.detectVideoShotAdvance(detectVideoShotAdvanceRequest, runtime);
// Get the full response.
System.out.println(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(detectVideoShotResponse)));
// Get a specific field.
System.out.println(detectVideoShotResponse.getBody().getData());
} catch (TeaException teaException) {
// Get the full error message.
System.out.println(com.aliyun.teautil.Common.toJSONString(teaException));
// Get a specific field.
System.out.println(teaException.getCode());
}
}
}# -*- coding: utf-8 -*-
# Import the dependency.
# pip install alibabacloud_videorecog20200320
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_videorecog20200320.client import Client
from alibabacloud_videorecog20200320.models import DetectVideoShotAdvanceRequest
config = Config(
# To create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
# If you are using 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 set the 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='videorecog.cn-shanghai.aliyuncs.com',
# The region corresponding to the endpoint.
region_id='cn-shanghai'
)
detect_video_shot_request = DetectVideoShotAdvanceRequest()
# Scenario 1: The file is stored locally.
# stream = open(r'/tmp/DetectVideoShot1.mp4', 'rb')
# detect_video_shot_request.video_url_object = stream
# Scenario 2: Use any publicly accessible URL.
url = 'http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/videorecog/DetectVideoShot/DetectVideoShot1.mp4'
img = urlopen(url).read()
detect_video_shot_request.video_url_object = io.BytesIO(img)
runtime = RuntimeOptions()
try:
# Initialize the client.
client = Client(config)
response = client.detect_video_shot_advance(detect_video_shot_request, runtime)
# Get the full response.
print(response.body)
except Exception as error:
# Get the full error message.
print(error)
# Get a specific field.
print(error.code)
# Tip: You can view attribute names by using error.__dict__.
# Close the stream.
# stream.close()<?php
// Install the dependency.
// composer require alibabacloud/videorecog-20200320
use AlibabaCloud\SDK\Videorecog\V20200320\Videorecog;
use AlibabaCloud\Tea\Utils\Utils;
use \Exception;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Videorecog\V20200320\Models\DetectVideoShotAdvanceRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use GuzzleHttp\Psr7\Stream;
class DetectVideoShotAdvance {
/**
* Use an AccessKey pair to initialize the client.
* @param string $accessKeyId
* @param string $accessKeySecret
* @return Videorecog Client
*/
public static function createClient($accessKeyId, $accessKeySecret){
// Initialize a Config object with your AccessKey ID, AccessKey Secret, and service endpoint.
$config = new Config([
"accessKeyId" => $accessKeyId,
"accessKeySecret" => $accessKeySecret
]);
// The endpoint of the service.
$config->endpoint = "videorecog.cn-shanghai.aliyuncs.com";
return new Videorecog($config);
}
/**
* @param string[] $args
* @return void
*/
public static function main($args){
// To create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you are using 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 set the 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/DetectVideoShot1.mp4', 'rb');
// $stream = new Stream($file);
// Scenario 2: Use any publicly accessible URL.
$file = fopen('http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/videorecog/DetectVideoShot/DetectVideoShot1.mp4', 'rb');
$stream = new Stream($file);
$detectVideoShotAdvanceRequest = new DetectVideoShotAdvanceRequest([
"videoUrlObject" => $stream
]);
$runtime = new RuntimeOptions([]);
try {
$resp = $client->detectVideoShotAdvance($detectVideoShotAdvanceRequest, $runtime);
# Get the full response.
echo Utils::toJSONString($resp->body);
} catch (Exception $exception) {
# Get the full error message.
echo Utils::toJSONString($exception);
# Get a specific field.
echo $exception->getCode();
}
}
}
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
require_once $path;
}
// The $argv parameter is a reserved array for input arguments and has no practical significance. You do not need to modify it.
DetectVideoShotAdvance::main(array_slice($argv, 1));// Install the dependency.
// npm install @alicloud/videorecog20200320
const VideorecogClient = require('@alicloud/videorecog20200320');
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({
// To create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you are using 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 set the 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 = `videorecog.cn-shanghai.aliyuncs.com`;
const client = new VideorecogClient.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 detectVideoShotAdvanceRequest = new VideorecogClient.DetectVideoShotAdvanceRequest();
// Scenario 1: Use a local file.
// const fileStream = fs.createReadStream('/tmp/DetectVideoShot1.mp4');
// detectVideoShotAdvanceRequest.videoUrlObject = fileStream;
// Scenario 2: Use any publicly accessible URL.
const url = new URL("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/videorecog/DetectVideoShot/DetectVideoShot1.mp4");
const httpClient = (url.protocol == "https:") ? https : http;
detectVideoShotAdvanceRequest.videoUrlObject = await getResponse(httpClient, url);
let runtime = new TeaUtil.RuntimeOptions({});
client.detectVideoShotAdvance(detectVideoShotAdvanceRequest, runtime)
.then(function (detectVideoShotResponse) {
// Get the full response.
console.log(detectVideoShotResponse);
// Get a specific field.
console.log(detectVideoShotResponse.body.data);
}, function (error) {
// Get the full error message.
console.log(error);
// Get a specific field.
console.log(error.data.Code);
})
} catch (error) {
console.log(error);
}
}();/**
This code depends on github.com/alibabacloud-go/videorecog-20200320/v2.
We recommend using 'go mod tidy' to install the dependency.
*/
import (
"fmt"
"net/http"
"os"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
util "github.com/alibabacloud-go/tea-utils/v2/service"
"github.com/alibabacloud-go/tea/tea"
videorecog20200320 "github.com/alibabacloud-go/videorecog-20200320/v2/client"
)
func main() {
// To create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you are using 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 set the environment variables before running the sample code.
accessKeyId := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
accessKeySecret := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
// Initialize a Config object with your AccessKey ID, AccessKey Secret, and service endpoint.
config := &openapi.Config{
AccessKeyId: tea.String(accessKeyId),
AccessKeySecret: tea.String(accessKeySecret),
}
// The endpoint of the service.
config.Endpoint = tea.String("videorecog.cn-shanghai.aliyuncs.com")
client, err := videorecog20200320.NewClient(config)
if err != nil {
panic(err)
}
// Scenario 1: Use a local file.
// file, err := os.Open("/tmp/DetectVideoShot.mp4")
// if err != nil {
// fmt.Println("can not open file", err)
// panic(err)
// }
// detectVideoShotAdvanceRequest := &videorecog20200320.DetectVideoShotAdvanceRequest{
// VideoUrlObject: file,
// }
// Scenario 2: Use any publicly accessible URL.
httpClient := http.Client{}
file, _ := httpClient.Get("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/videorecog/DetectVideoShot/DetectVideoShot1.mp4")
detectVideoShotAdvanceRequest := &videorecog20200320.DetectVideoShotAdvanceRequest{
VideoUrlObject: file.Body,
}
runtime := &util.RuntimeOptions{}
detectVideoShotAdvanceResponse, err := client.DetectVideoShotAdvance(detectVideoShotAdvanceRequest, runtime)
if err != nil {
// Get the full error message.
fmt.Println(err.Error())
} else {
// Get the full response.
fmt.Println(detectVideoShotAdvanceResponse)
}
}// Install the dependency.
// dotnet add package AlibabaCloud.SDK.Videorecog20200320
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using AlibabaCloud.SDK.Videorecog20200320.Models;
using Tea;
using Tea.Utils;
namespace AlibabaCloud.SDK.Sample
{
public class Sample
{
/**
* Use an AccessKey pair to initialize the client.
* @param accessKeyId
* @param accessKeySecret
* @return Client
* @throws Exception
*/
public static AlibabaCloud.SDK.Videorecog20200320.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 = "videorecog.cn-shanghai.aliyuncs.com";
return new AlibabaCloud.SDK.Videorecog20200320.Client(config);
}
public static void Main(string[] args)
{
// To create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you are using 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 set the environment variables before running the sample code.
AlibabaCloud.SDK.Videorecog20200320.Client client = CreateClient(System.Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"), System.Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
AlibabaCloud.SDK.Videorecog20200320.Models.DetectVideoShotAdvanceRequest detectVideoShotAdvanceRequest = new AlibabaCloud.SDK.Videorecog20200320.Models.DetectVideoShotAdvanceRequest
();
// Scenario 1: Use a local file.
// System.IO.StreamReader file = new System.IO.StreamReader(@"/tmp/DetectVideoShot1.mp4");
// detectVideoShotAdvanceRequest.VideoUrlObject = file.BaseStream;
// Scenario 2: Use any publicly accessible URL.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/videorecog/DetectVideoShot/DetectVideoShot1.mp4");
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
detectVideoShotAdvanceRequest.VideoUrlObject = stream;
AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
try
{
AlibabaCloud.SDK.Videorecog20200320.Models.DetectVideoShotResponse detectVideoShotResponse = client.DetectVideoShotAdvance(detectVideoShotAdvanceRequest, runtime);
// Get the full response.
Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(detectVideoShotResponse.Body));
// Get a specific field.
Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(detectVideoShotResponse.Body.Data));
}
catch (TeaException error)
{
// Print the error if necessary.
Console.WriteLine(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(AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message));
}
}
}
}Result post-processing
Shot splitting
After you call the shot detection API, it returns the frame IDs that mark shot boundaries. You can use these frame IDs with tools like FFmpeg to split the video into separate shots.
For example, you can use FFmpeg to split the video. The following commands show how to do this:
# Use the shot detection results with FFmpeg to split the video. The following commands extract the video and audio segments separately before merging them.
# Sample source video: DetectVideoShot1.mp4
# Shot detection result: "shot_frame_ids":[0,21,56,74,99,128,151,170,200,218,255,271,290,307,323,362,386,416,442,464,481,644,681,716,802,833,889,1027,1049,1075]
# The start and end frames of the eighth shot are 170 and 200, respectively.
# Use ffprobe to find the video frame rate (25) and audio sample rate (44100): ffprobe DetectVideoShot1.mp4
# Extract the video frames for the eighth shot and create 8v.mp4:
ffmpeg -i DetectVideoShot1.mp4 -vf "trim=start_frame=170:end_frame=200,setpts=PTS-STARTPTS" -an 8v.mp4
# Extract the audio for the eighth shot and create 8a.mp4:
ffmpeg -i DetectVideoShot1.mp4 -af "atrim=start_sample=44100/25*170:end_sample=44100/25*200" -vn 8a.mp4
# Combine the audio and video.
ffmpeg -i 8v.mp4 -i 8a.mp4 -c copy 8.mp4