Image clustering

更新时间:
复制 MD 格式

Image clustering groups visually similar images together, allowing you to filter and organize related images in an album, such as those taken in a continuous burst.

Use cases

  • Cloud drives and photo album services: Group similar images in your cloud drive or photo albums to create personalized image collections.

  • Image deduplication: Identify similar images within your application and remove duplicates to save storage space and reduce costs.

Prerequisites

  • Create a metadata index for files based on the use case. For more information, see Create a metadata index.

  • Create the dataset using the Official:ImageManagement template.

Create image clusters

Call the CreateSimilarImageClusteringTask operation to group similar images in the test-dataset dataset of the test-project project.

Note

Image clustering incurs API call fees. For more information, see Billable items of IMM.

Request example

{
  "ProjectName": "test-project",
  "DatasetName": "test-dataset"
}

Response example

{
  "TaskId": "SimilarImageClustering-3b4ce06c-f19e-43ba-8ae9-29a4ba617eac",
  "RequestId": "0FA88E7A-85C8-5016-8182-80FA2A711D29",
  "EventId": "3BF-1mc8MI8FsJWMMgJhDO6O98mepq1"
}

Sample code

# -*- coding: utf-8 -*-
# This file is auto-generated, don't edit it. Thanks.
import os
import sys

from typing import List

from alibabacloud_imm20200930.client import Client as imm20200930Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_imm20200930 import models as imm_20200930_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient


class Sample:
    def __init__(self):
        pass

    @staticmethod
    def create_client(
        access_key_id: str,
        access_key_secret: str,
    ) -> imm20200930Client:
        """
        Initializes a client using an AccessKey ID and an AccessKey secret.
        @param access_key_id:
        @param access_key_secret:
        @return: Client
        @throws Exception
        """
        config = open_api_models.Config(
            # Required. Your AccessKey ID.
            access_key_id=access_key_id,
            # Required. Your AccessKey secret.
            access_key_secret=access_key_secret
        )
        # For more information about the endpoint, see https://api.aliyun.com/product/imm.
        config.endpoint = f'imm.cn-beijing.aliyuncs.com'
        return imm20200930Client(config)

    @staticmethod
    def main(
        args: List[str],
    ) -> None:
        # Before you run the sample code, make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured.
        # Leaking your AccessKey pair may compromise the security of all resources in your account. We recommend that you use a more secure method, such as using Security Token Service (STS) credentials, to call API operations. For more information about authentication, see https://help.aliyun.com/document_detail/378659.html.
        client = Sample.create_client(os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'], os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'])
        create_similar_image_clustering_task_request = imm_20200930_models.CreateSimilarImageClusteringTaskRequest(
            project_name='test-project',
            dataset_name='test-dataset'
        )
        runtime = util_models.RuntimeOptions()
        try:
            # You can add your own code to print the API response.
            client.create_similar_image_clustering_task_with_options(create_similar_image_clustering_task_request, runtime)
        except Exception as error:
            # This sample only prints the error message for demonstration purposes. In a production environment, you must implement proper exception handling.
            # Error message
            print(error.message)
            # Troubleshooting URL
            print(error.data.get("Recommend"))
            UtilClient.assert_as_string(error.message)

    @staticmethod
    async def main_async(
        args: List[str],
    ) -> None:
        # Before you run the sample code, make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured.
        # Leaking your AccessKey pair may compromise the security of all resources in your account. We recommend that you use a more secure method, such as using Security Token Service (STS) credentials, to call API operations. For more information about authentication, see https://help.aliyun.com/document_detail/378659.html.
        client = Sample.create_client(os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'], os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'])
        create_similar_image_clustering_task_request = imm_20200930_models.CreateSimilarImageClusteringTaskRequest(
            project_name='test-project',
            dataset_name='test-dataset'
        )
        runtime = util_models.RuntimeOptions()
        try:
            # You can add your own code to print the API response.
            await client.create_similar_image_clustering_task_with_options_async(create_similar_image_clustering_task_request, runtime)
        except Exception as error:
            # This sample only prints the error message for demonstration purposes. In a production environment, you must implement proper exception handling.
            # Error message
            print(error.message)
            # Troubleshooting URL
            print(error.data.get("Recommend"))
            UtilClient.assert_as_string(error.message)


if __name__ == '__main__':
    Sample.main(sys.argv[1:])

Query image clusters

Call the QuerySimilarImageClusters operation to retrieve image clusters in the test-dataset dataset of the test-project project.

Request example

{
  "ProjectName": "test-project",
  "DatasetName": "test-dataset"
}

Response example

{
  "SimilarImageClusters": [
    {
      "ObjectId": "SimilarImageCluster-e5cdfdad-c02a-4093-aa58-400ff2e4520b",
      "CreateTime": "2024-03-07T14:57:13.047481088+08:00",
      "UpdateTime": "2024-03-07T14:57:13.047481088+08:00",
      "Files": [
        {
          "ImageScore": 0.749,
          "URI": "oss://test-ivanivan/p637447.jpeg"
        },
        {
          "ImageScore": 0.749,
          "URI": "oss://test-ivanivan/p637448.jpeg"
        }
      ]
    },
    {
      "ObjectId": "SimilarImageCluster-3350bbcf-a044-42f2-bedc-57eede4d476f",
      "CreateTime": "2024-03-07T14:57:12.955958016+08:00",
      "UpdateTime": "2024-03-07T14:57:12.955958016+08:00",
      "Files": [
        {
          "ImageScore": 0.736,
          "URI": "oss://test-ivanivan/hanhong.png"
        },
        {
          "ImageScore": 0.736,
          "URI": "oss://test-ivanivan/hanhong2.png"
        }
      ]
    },
    {
      "ObjectId": "SimilarImageCluster-4c239671-5504-4910-90f6-03cd863f686e",
      "CreateTime": "2024-03-07T14:57:12.886128896+08:00",
      "UpdateTime": "2024-03-07T14:57:12.886128896+08:00",
      "Files": [
        {
          "ImageScore": 0.692,
          "URI": "oss://test-ivanivan/dir1/mp4_png.png"
        },
        {
          "ImageScore": 0.67,
          "URI": "oss://test-ivanivan/dir1/demo.gif"
        }
      ]
    },
    {
      "ObjectId": "SimilarImageCluster-e77ac1ad-44b4-49d5-baa7-ad871efd0503",
      "CreateTime": "2024-03-07T14:57:12.817118976+08:00",
      "UpdateTime": "2024-03-07T14:57:12.817118976+08:00",
      "Files": [
        {
          "ImageScore": 0.717,
          "URI": "oss://test-ivanivan/OIP-C.jpeg"
        },
        {
          "ImageScore": 0.717,
          "URI": "oss://test-ivanivan/OIP-C1.jpeg"
        }
      ]
    },
    {
      "ObjectId": "SimilarImageCluster-315751c6-5b69-43b4-8c37-00e7ad2ec0e6",
      "CreateTime": "2024-03-07T14:57:12.745981952+08:00",
      "UpdateTime": "2024-03-07T14:57:12.745981952+08:00",
      "Files": [
        {
          "ImageScore": 0.714,
          "URI": "oss://test-ivanivan/A6.jpg"
        },
        {
          "ImageScore": 0.709,
          "URI": "oss://test-ivanivan/A4 (1).jpg"
        }
      ]
    },
    {
      "ObjectId": "SimilarImageCluster-140d3e92-7e67-4b9d-8066-3aea778e5898",
      "CreateTime": "2024-03-07T14:57:12.65400192+08:00",
      "UpdateTime": "2024-03-07T14:57:12.65400192+08:00",
      "Files": [
        {
          "ImageScore": 0.709,
          "URI": "oss://test-ivanivan/A1 (1).jpg"
        },
        {
          "ImageScore": 0.709,
          "URI": "oss://test-ivanivan/A2 (1).jpg"
        }
      ]
    }
  ],
  "RequestId": "5830FFD2-C2E5-5431-9180-EBBACCC2FECE",
  "NextToken": ""
}

Sample code

# -*- coding: utf-8 -*-
# This file is auto-generated, don't edit it. Thanks.
import os
import sys

from typing import List

from alibabacloud_imm20200930.client import Client as imm20200930Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_imm20200930 import models as imm_20200930_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient


class Sample:
    def __init__(self):
        pass

    @staticmethod
    def create_client(
        access_key_id: str,
        access_key_secret: str,
    ) -> imm20200930Client:
        """
        Initializes a client using an AccessKey ID and an AccessKey secret.
        @param access_key_id:
        @param access_key_secret:
        @return: Client
        @throws Exception
        """
        config = open_api_models.Config(
            # Required. Your AccessKey ID.
            access_key_id=access_key_id,
            # Required. Your AccessKey secret.
            access_key_secret=access_key_secret
        )
        # For more information about the endpoint, see https://api.aliyun.com/product/imm.
        config.endpoint = f'imm.cn-beijing.aliyuncs.com'
        return imm20200930Client(config)

    @staticmethod
    def main(
        args: List[str],
    ) -> None:
        # Before you run the sample code, make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured.
        # Leaking your AccessKey pair may compromise the security of all resources in your account. We recommend that you use a more secure method, such as using Security Token Service (STS) credentials, to call API operations. For more information about authentication, see https://help.aliyun.com/document_detail/378659.html.
        client = Sample.create_client(os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'], os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'])
        query_similar_image_clusters_request = imm_20200930_models.QuerySimilarImageClustersRequest(
            dataset_name='test-dataset',
            project_name='test-project'
        )
        runtime = util_models.RuntimeOptions()
        try:
            # You can add your own code to print the API response.
            client.query_similar_image_clusters_with_options(query_similar_image_clusters_request, runtime)
        except Exception as error:
            # This sample only prints the error message for demonstration purposes. In a production environment, you must implement proper exception handling.
            # Error message
            print(error.message)
            # Troubleshooting URL
            print(error.data.get("Recommend"))
            UtilClient.assert_as_string(error.message)

    @staticmethod
    async def main_async(
        args: List[str],
    ) -> None:
        # Before you run the sample code, make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured.
        # Leaking your AccessKey pair may compromise the security of all resources in your account. We recommend that you use a more secure method, such as using Security Token Service (STS) credentials, to call API operations. For more information about authentication, see https://help.aliyun.com/document_detail/378659.html.
        client = Sample.create_client(os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'], os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'])
        query_similar_image_clusters_request = imm_20200930_models.QuerySimilarImageClustersRequest(
            dataset_name='test-dataset',
            project_name='test-project'
        )
        runtime = util_models.RuntimeOptions()
        try:
            # You can add your own code to print the API response.
            await client.query_similar_image_clusters_with_options_async(query_similar_image_clusters_request, runtime)
        except Exception as error:
            # This sample only prints the error message for demonstration purposes. In a production environment, you must implement proper exception handling.
            # Error message
            print(error.message)
            # Troubleshooting URL
            print(error.data.get("Recommend"))
            UtilClient.assert_as_string(error.message)


if __name__ == '__main__':
    Sample.main(sys.argv[1:])