すべてのプロダクト
Search
ドキュメントセンター

Object Storage Service:画像ラベル検出

最終更新日:Feb 05, 2025

画像ラベル検出を使用して、シーン、オブジェクト、イベントなどの画像コンテンツを検出し、自動的に画像にラベルを付けることができます。 このトピックでは、イメージラベル検出を使用するために指定できるパラメーターについて説明し、イメージラベル検出の使用方法の例を示します。

概要

画像ラベル検出は、シーン、オブジェクト、イベントなどの画像コンテンツを認識し、画像に自動的にラベルを付けます。 IMMは、30を超えるカテゴリに分類される数千の画像ラベルを提供します。 次の表に、ラベルカテゴリを示します。

图片标签检测..jpeg

シナリオ

シナリオ

説明

コンテンツ認識

イメージラベル検出を使用して、オブジェクトの識別と科学の普及を伴うイメージコンテンツ認識アプリケーションを構築できます。 これらのアプリケーションは、画像内のオブジェクトやシーンなどの情報を認識できます。

写真とアルバムの管理

フォトアルバム内の写真は、画像コンテンツに基づいて自動的に分類されます。 これは、効率的かつ自動化された写真管理を可能にする。

シーン分析

画像コンテンツは自動的に分析およびラベル付けされるため、分析効率が向上し、手動ラベル付けコストが削減されます。

コンテンツマーケティング

画像ラベル検出を使用すると、ソーシャルネットワーキング、ニュース、eコマースプラットフォームなどのプラットフォームでのコンテンツマーケティングを改善できます。

前提条件

  • インテリジェントメディア管理 (IMM) が有効になります。 詳細については、「IMMの有効化」をご参照ください。

  • インテリジェントメディア管理 (IMM) プロジェクトはバケットにバインドされています。 OSSコンソールでIMMプロジェクトをバケットにバインドする方法の詳細については、「開始」をご参照ください。 API操作を呼び出してIMMプロジェクトをバケットにバインドする方法の詳細については、「AttachOSSBucket」をご参照ください。

使用上の注意

  • 画像ラベル検出は、同期処理 (x-oss-process) のみをサポートします。

  • 匿名アクセスは拒否されます。

  • 機能を使用するには、必要な権限が必要です。 詳細は、「アクセス許可」をご参照ください。

  • JPG、PNG、およびJPEGのみがサポートされています。

  • 次の画像サイズ制限が適用されます。

    • 検出する画像のサイズは20 MBを超えることはできません。

    • 検出する画像の高さまたは幅は30,000ピクセルを超えることはできません。

    • 画像の総ピクセル数は250,000,000を超えることはできません。

パラメーターの説明

アクション: 画像 /ラベル

リクエストパラメーター

パラメーター

必須 / 任意

説明

thr

int

いいえ

信頼度が指定したしきい値より低いラベルを表示しないように指定します。 有効値: 0~100。 デフォルト値: 70。

50

応答パラメーター

説明

レスポンスパラメーターの詳細については、「DetectImageLabels」をご参照ください。

OSS SDKの使用

次のサンプルコードは、一般的なプログラミング言語のOSS SDKを使用してイメージ内のラベルを検出する方法の例を示しています。 他のプログラミング言語を使用して画像内のラベルを検出する場合は、次のサンプルコードに基づいてパラメーターを変更します。

Java

Java 3.17.4以降のOSS SDKが必要です。

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyuncs.exceptions.ClientException;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class Demo {
    public static void main(String[] args) throws ClientException, ClientException {
        // Specify the endpoint of the region in which the bucket is located. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Specify the ID of the Alibaba Cloud region in which the bucket is located. Example: cn-hangzhou. 
        String region = "cn-hangzhou";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. 
        String bucketName = "examplebucket";
        // If the image is stored in the root directory of the bucket, enter the image name. If the image is not stored in the root directory of the bucket, you must specify the full path of the image. Example: exampledir/example.jpg. 
        String key = "example.jpg";

        // Create an OSSClient instance. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            // Create a processing instruction to detect labels in the image. 
            GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
            getObjectRequest.setProcess("image/labels");

            // Use the process parameter of the getObject method to pass the processing instruction. 
            OSSObject ossObject = ossClient.getObject(getObjectRequest);

            // Read and display the labels. 
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = ossObject.getObjectContent().read(buffer)) != -1) {
                baos.write(buffer, 0, bytesRead);
            }
            String imageLabels = baos.toString("UTF-8");
            System.out.println("Image Labels:");
            System.out.println(imageLabels);
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        } finally {
            // Shut down the OSSClient instance. 
            ossClient.shutdown();
        }
    }
}

Python

Python 2.18.4以降のOSS SDKが必要です。

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
# Specify the ID of the Alibaba Cloud region in which the bucket is located. 
region = 'cn-hangzhou'
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', region=region)

# If the image is stored in the root directory of the bucket, enter the image name. If the image is not stored in the root directory of the bucket, you must specify the full path of the image. Example: exampledir/example.jpg. 
key = 'example.jpg'

# Create a processing instruction to detect labels in the image. 
process = 'image/labels'

try:
    # Use the get_object method and pass the processing instruction by using the process parameter. 
    result = bucket.get_object(key, process=process)

    # Read and display the labels. 
    image_labels = result.read().decode('utf-8')
    print("Image Labels:")
    print(image_labels)
except oss2.exceptions.OssError as e:
    print("Error:", e)

Go

Go 3.0.2以降のOSS SDKが必要です。

package main

import (
	"fmt"
	"io"
	"os"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain the temporary access credentials from the environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	// Create an OSSClient instance. 
	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
	// Specify the ID of the Alibaba Cloud region in which the bucket is located. Example: cn-hangzhou. 
	client, err := oss.New("https://oss-cn-hangzhou.aliyuncs.com", "", "", oss.SetCredentialsProvider(&provider), oss.AuthVersion(oss.AuthV4), oss.Region("cn-hangzhou"))
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	// Specify the name of the bucket. Example: examplebucket. 
	bucketName := "examplebucket"

	bucket, err := client.Bucket(bucketName)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	// If the image is stored in the root directory of the bucket, enter the image name. If the image is not stored in the root directory of the bucket, you must specify the full path of the image. Example: exampledir/example.jpg. 
	// Use the oss.Process method to create a processing instruction to detect labels in the image. 
	body, err := bucket.GetObject("example.jpg", oss.Process("image/labels"))
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	defer body.Close()

	data, err := io.ReadAll(body)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	fmt.Println("data:", string(data))
}

PHP

PHP 2.7.0以降のOSS SDKが必要です。

<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;

try {
    // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
    $provider = new EnvironmentVariableCredentialsProvider(); 
    // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
    $endpoint = 'https://oss-cn-hangzhou.aliyuncs.com';
    // Specify the name of the bucket. Example: examplebucket. 
    $bucket = 'examplebucket';
    // If the image is stored in the root directory of the bucket, enter the image name. If the image is not stored in the root directory of the bucket, you must specify the full path of the image. Example: exampledir/example.jpg. 
    $key = 'example.jpg'; 

    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,        
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        // Specify the ID of the Alibaba Cloud region in which the bucket is located. 
        "region" => "cn-hangzhou"
    );
    $ossClient = new OssClient($config);
  // Create a processing instruction to detect labels in the image. 
  $options[$ossClient::OSS_PROCESS] = "image/labels";
  $result = $ossClient->getObject($bucket,$key,$options);
  var_dump($result);
} catch (OssException $e) {
  printf($e->getMessage() . "\n");
  return;
}

RESTful APIの使用

ビジネスで高度なカスタマイズが必要な場合は、RESTful APIを直接呼び出すことができます。 APIを直接呼び出すには、コードに署名計算を含める必要があります。 承認ヘッダーの計算方法の詳細については、「 (推奨) 承認ヘッダーにV4署名を含める」をご参照ください。

GetObjectリクエストでx-oss-processパラメーターを指定することで、イメージを処理できます。 詳細については、「GetObject」をご参照ください。

thrパラメーターを指定せずに画像のラベルを取得

thrパラメーター

thrパラメーターは空のままにします。

サンプルリクエスト

GET /example.jpg?x-oss-process=image/labels HTTP/1.1
Host: image-demo.oss-cn-hangzhou.aliyuncs.com
Date: Fri, 21 Jul 2023 08:30:25 GMT
Authorization: SignatureValue

サンプル成功応答

HTTP/1.1 200 OK
Server: AliyunOSS
Date: Fri, 21 Jul 2023 08:30:26 GMT
Content-Type: application/json;charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
x-oss-request-id: 64BA42225DFDD13437ECD00E
Last-Modified: Mon, 10 Jul 2023 13:07:30 GMT
x-oss-object-type: Normal
x-oss-hash-crc64ecma: 13420962247653419692
x-oss-storage-class: Standard
x-oss-ec: 0048-00000104
Content-Disposition: attachment
x-oss-force-download: true
x-oss-server-time: 489
Content-Encoding: gzip

{
    "Labels":[
        {
            "CentricScore": 0.823,
            "LabelConfidence": 1.0,
            "LabelLevel": 2,
            "LabelName": "Coat",
            "Language": "zh-Hans",
            "ParentLabelName": "Clothing"
        },
        { 
            "CentricScore": 0.721,
            "LabelConfidence": 0.735,
            "LabelLevel": 2,
            "LabelName": "Apparel",
            "Language": "zh-Hans",
            "ParentLabelName": "Clothing"
        },
    		......,
    ],
    "RequestId": "0EC0B6EC-EB16-5EF4-812B-EF3A60C7D20D"
}
    

thrパラメーターを指定して画像のラベルを取得

thrパラメーター

  • thr: 85

サンプルリクエスト

GET /example.jpg?x-oss-process=image/labels,thr_85 HTTP/1.1
Host: image-demo.oss-cn-hangzhou.aliyuncs.com
Date: Fri, 21 Jul 2023 08:44:58 GMT
Authorization: SignatureValue

サンプル成功応答

HTTP/1.1 200 OK
Server: AliyunOSS
Date: Fri, 21 Jul 2023 08:45:00 GMT
Content-Type: application/json;charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
x-oss-request-id: 64BA458C7FFDC2383651DF09
Last-Modified: Mon, 10 Jul 2023 13:07:30 GMT
x-oss-object-type: Normal
x-oss-hash-crc64ecma: 13420962247653419692
x-oss-storage-class: Standard
x-oss-ec: 0048-00000104
Content-Disposition: attachment
x-oss-force-download: true
x-oss-server-time: 421
Content-Encoding: gzip

{
  "RequestId": "B7BDAFD5-C0AF-5042-A749-88BF6E4F2712", 
  "Labels": [
     {
      	"CentricScore": 0.797,
      	"Language": "zh-Hans",
      	"LabelConfidence": 0.927,
      	"LabelName": "Apparel",
      	"LabelLevel": 2,
      	"ParentLabelName": "Clothing"
      },
        ......,
   ]
}