This topic describes how to use Alibaba Cloud Image Search SDKs for Python.

Preparations

  • Before you install and use Alibaba Cloud SDKs, make sure that you have created an Alibaba Cloud account and obtained an AccessKey pair. For more information, see Create an AccessKey pair.
  • You can install the core library of the Alibaba Cloud SDK for Python by using the following methods:
    • (Recommended) Use dependency managers.
      Run the following command to install the core library of the Alibaba Cloud SDK for Python:
      pip install aliyun-python-sdk-core
    • Download and install the core library of the Alibaba Cloud SDK for Python.

      You can run the git clone command or use other methods to download aliyun-python-sdk-core, and add a solution.

  • You can install the Alibaba Cloud Image Search SDK for Python by using the following methods:
    • (Recommended) Use dependency managers.
      Run the following command to install the Alibaba Cloud Image Search SDK for Python:
      pip install aliyun-python-sdk-imagesearch
    • Download and install the Alibaba Cloud Image Search SDK for Python.

      You can run the git clone command or use other methods to download aliyun-python-sdk-imagesearch, and add a solution.

Sample code

The following complete sample code is provided:
# -*- coding: utf8 -*-
from aliyunsdkcore.client import AcsClient
import base64
import aliyunsdkimagesearch.request.v20190325.AddImageRequest as AddImageRequest
import aliyunsdkimagesearch.request.v20190325.DeleteImageRequest as DeleteImageRequest
import aliyunsdkimagesearch.request.v20190325.SearchImageRequest as SearchImageRequest
# Create an AcsClient instance.
client = AcsClient("<your-access-key-id>", "<your-access-key-secret>", "<region>")
# Add the image.
request = AddImageRequest.AddImageRequest()
request.set_endpoint("imagesearch.<region>.aliyuncs.com")
request.set_InstanceName("demo")
request.set_ProductId("test")
request.set_PicName("test")
with open('/home/admin/demo.jpg', 'rb') as imgfile:
    encoded_pic_content = base64.b64encode(imgfile.read())
    request.set_PicContent(encoded_pic_content)
response = client.do_action_with_exception(request)
print(response)
# Search for images.
request = SearchImageRequest.SearchImageRequest()
request.set_endpoint("imagesearch.<region>.aliyuncs.com")
request.set_InstanceName("demo")
with open('/home/admin/demo.jpg', 'rb') as imgfile:
    encoded_pic_content = base64.b64encode(imgfile.read())
    request.set_PicContent(encoded_pic_content)
response = client.do_action_with_exception(request)
print(response)
# Delete the image.
request = DeleteImageRequest.DeleteImageRequest()
request.set_endpoint("imagesearch.<region>.aliyuncs.com")
request.set_InstanceName("demo")
request.set_ProductId("test")
response = client.do_action_with_exception(request)
print(response)