This topic describes how to install Image Search SDK for Python and provides sample code on how to use the SDK.

Preparations

  • Before you install and use an Alibaba Cloud SDK, make sure that you have created an Alibaba Cloud account and obtained the AccessKey pair of the Alibaba Cloud account. For more information, see Create an AccessKey pair.
  • Run the following command to install the dependency:
  pip install alibabacloud_imagesearch20201214

Add

  • Sample code
    from alibabacloud_imagesearch20201214.client import Client
    from alibabacloud_imagesearch20201214.models import AddImageAdvanceRequest
    from alibabacloud_tea_openapi.models import Config
    from alibabacloud_oss_util.models import RuntimeOptions
    def addImage():
        request = AddImageAdvanceRequest()
        # Required. The name of the Image Search instance. 
        request.instance_name = '<instanceName>'
        # Required. The ID of the product. The value cannot exceed 512 characters in length. 
        # A product ID can relate to multiple image names. 
        request.product_id = '<productId>'
        # Required. The name of the image. The value cannot exceed 512 characters in length. 
        # 1. An image is uniquely identified by the values of the product_id and pic_name parameters. 
        # 2. If you add multiple images that share the same values of the product_id and pic_name parameters, only the last image that you add is retained. 
        request.pic_name = '<picName>'
        # The image. The image cannot exceed 4 MB in size. The transmission timeout period is 5 seconds. Only the following image formats are supported: PNG, JPG, JPEG, BMP, GIF, WebP, TIFF, and PPM.
        # For product, brand, and generic images, the length and the width of the image must range from 100 pixels to 4,096 pixels.
        # For cloth images, the length and the width of the image must range from 448 pixels to 4,096 pixels.
        # The image cannot contain rotation information.
        f = open('<filePath>', 'rb')
        request.pic_content_object = f
        # Optional. The ID of the product category. 
        # 1. For product image searches: If you set a category ID for an image, the specified category prevails. If you do not set a category ID for an image, the system predicts the category, and returns the ID of the predicted category in the response. 
        # 2. For cloth, brand, and generic image searches: The category ID is set to 88888888 regardless of whether a category ID is set. 
        request.categoryId = 3
        # Optional. The description that you want to add. The value cannot exceed 4,096 characters in length. 
        # If you set this parameter, the response includes this parameter and its value. You can add text such as an image description. 
        request.customContent = "this is a simple test"
        # Optional. The attribute of the INT type. The attribute can be used to filter images in image searches. If you set this parameter, the response includes this parameter and its value. 
        # For example, you can set different attributes for images from different sites or different users. This way, users can filter images by attribute and obtain more accurate search results.
        request.intAttr = 56
        # Optional. The attribute of the STRING type. The value cannot exceed 128 characters in length. The attribute can be used to filter images in image searches. If you set this parameter, the response includes this parameter and its value. 
        request.strAttr = "test" # Optional. Specifies whether to recognize the main subject in the image. Default value: True. 
        # 1.If you set this parameter to True, the system recognizes the main subject in the image, and searches for images based on the recognized subject. The response includes the recognition result. 
        # 2. If you set this parameter to False, the system does not recognize the main subject in the image, and searches for images based on the entire image. 
        # 3.For cloth image searches, this parameter does not take effect. The system searches for images based on the entire image. 
        request.crop = True
        # Optional. The main area of the image. The value is in the format of x1,x2,y1,y2. x1 and y1 indicate the position of the upper-left point of the area, in pixels. x2 and y2 indicate the position of the lower-right point of the area, in pixels. The specified area cannot cross the boundary of the image. 
        # If you set the main area, the system searches for images based on the main area regardless of the value of the crop parameter. 
        # For cloth image searches, this parameter does not take effect. The system searches for images based on the entire image. 
        request.region = "167,467,221,407"
        config = Config()
        config.access_key_id = '<accessKeyId>'
        config.access_key_secret = '<accessKeySecret>'
        config.endpoint = 'imagesearch.[regionId].aliyuncs.com'
        config.region_id = '<regionId>'
        config.type = 'access_key'
        client = Client(config)
        runtime_option = RuntimeOptions()
        response = client.add_image_advance(request, runtime_option)
        print(response.to_map())
        f.close()
    if __name__ == '__main__':
        addImage()
  • Sample response
    {
      'RequestId': '7F769FFC-4F45-476E-BE6C-E4EF82E012A7',
      'Success': True,
      'Message': 'success',
      'Code': 0,
      'PicInfo': {
        'CategoryId': 20,
        'Region': '474,747,497,784'
      }
    }

SearchImageByPic

  • Sample code
    from alibabacloud_imagesearch20201214.client import Client
    from alibabacloud_imagesearch20201214.models import SearchImageByPicAdvanceRequest
    from alibabacloud_tea_openapi.models import Config
    from alibabacloud_oss_util.models import RuntimeOptions
    def searchImageByPic() :
        request = SearchImageByPicAdvanceRequest()
        # Required. The name of the Image Search instance. 
        request.instance_name = '<instanceName>'
        # The image. The image cannot exceed 4 MB in size. The transmission timeout period is 5 seconds. Only the following image formats are supported: PNG, JPG, JPEG, BMP, GIF, WebP, TIFF, and PPM.
        # For product, brand, and generic images, the length and the width of the image must range from 100 pixels to 4,096 pixels.
        # For cloth images, the length and the width of the image must range from 448 pixels to 4,096 pixels.
        # The image cannot contain rotation information.
        f = open('<filePath>', 'rb')
        request.pic_content_object = f
        # Optional. The ID of the product category. 
        # 1. For product image searches: If you set a category ID for an image, the specified category prevails. If you do not set a category ID for an image, the system predicts the category, and returns the ID of the predicted category in the response. 
        # 2. For cloth, brand, and generic image searches: The category ID is set to 88888888 regardless of whether a category ID is set. 
        request.categoryId = 3
        # Optional. The number of entries to be returned. Valid values: 1 to 100. Default value: 10. 
        request.num = 10
        # Optional. The ordinal number of the first entry that is returned. Valid values: 0 to 499. Default value: 0. 
        request.start = 0
        # Optional. Specifies whether to recognize the main subject in the image. Default value: True. 
        # 1.If you set this parameter to True, the system recognizes the main subject in the image, and searches for images based on the recognized subject. The response includes the recognition result. 
        # 2. If you set this parameter to False, the system does not recognize the main subject in the image, and searches for images based on the entire image. 
        # 3.For cloth image searches, this parameter does not take effect. The system searches for images based on the entire image. 
        request.crop = True
        # Optional. The main area of the image. The value is in the format of x1,x2,y1,y2. x1 and y1 indicate the position of the upper-left point of the area, in pixels. x2 and y2 indicate the position of the lower-right point of the area, in pixels. The specified area cannot cross the boundary of the image. 
        # If you set the main area, the system searches for images based on the main area regardless of the value of the crop parameter. 
        # 3.For cloth image searches, this parameter does not take effect. The system searches for images based on the entire image. 
        request.region="167,467,221,407"
        # Optional. The filter condition.
        # The int_attr field supports the following operators: >, >=, <, <=, and =. The str_attr field supports the following operators: = and !=.You can join multiple filter conditions by using the AND or OR logical operator. 
        # Examples:
        # 1. Filter images based on the int_attr field: int_attr>=100
        # 2. Filter images based on the str_attr field: str_attr!="value1" 
        # 3. Filter images based on int_attr and str_attr fields: int_attr=1000 AND str_attr="value1"
        request.filter="int_attr=56 AND str_attr=\"test\""
        config = Config()
        config.access_key_id = '<accessKeyId>'
        config.access_key_secret = '<accessKeySecret>'
        config.endpoint = 'imagesearch.[regionId].aliyuncs.com'
        config.region_id = '<regionId>'
        config.type = 'access_key'
        client = Client(config)
        runtime_option = RuntimeOptions()
        response = client.search_image_by_pic_advance(request, runtime_option)
        print(response.to_map())
        f.close()
    if __name__ == '__main__':
        searchImageByPic()
  • Sample response
    {
      'RequestId': '53C481F3-E064-428D-AB25-B6C57A704E68',
      'Success': True,
      'Code': 0,
      'Msg': 'success',
      'Auctions': [{
        'CategoryId': 20,
        'ProductId': 'test-version-001',
        'PicName': 'test-version-001.jpg',
        'CustomContent': None,
        'Score': 1.0
        'SortExprValues': '5.37633353624177e+24;0',
        'IntAttr': None,
        'StrAttr': None
      }, {
        'CategoryId': 20,
        'ProductId': 'test_0426_1',
        'PicName': 'test_0426_1.png',
        'CustomContent': None,
        'Score': 1.0,
        'SortExprValues': '2.71303606033325;263',
        'IntAttr': None,
        'StrAttr': None
      }],
      'Head': {
        'DocsReturn': 5,
        'DocsFound': 5,
        'SearchTime': 295
      },
      'PicInfo': {
        'CategoryId': 20,
        'Region': '474,747,497,784',
        'AllCategories': [{
          'Id': 0,
          'Name': 'Tops'
        }, {
          'Id': 1,
          'Name': 'Dress'
        }, {
          'Id': 2,
          'Name': 'Bottoms'
        }, {
          'Id': 3,
          'Name': 'Bag'
        }, {
          'Id': 4,
          'Name': 'Shoes'
        }, {
          'Id': 5,
          'Name': 'Accessories'
        }, {
          'Id': 6,
          'Name': 'Snack'
        }, {
          'Id': 7,
          'Name': 'Makeup'
        }, {
          'Id': 8,
          'Name': 'Bottle'
        }, {
          'Id': 9,
          'Name': 'Furniture'
        }, {
          'Id': 20,
          'Name': 'Toy'
        }, {
          'Id': 21,
          'Name': 'Underwear'
        }, {
          'Id': 22,
          'Name': 'Digital device'
        }, {
          'Id': 88888888,
          'Name': 'Other'
        }],
        'MultiRegion': [{
            'Region': '112,440,76,387'
         }]
      }
    }

SearchImageByName

  • Sample code
    from alibabacloud_imagesearch20201214.client import Client
    from alibabacloud_imagesearch20201214.models import SearchImageByNameRequest
    from alibabacloud_tea_openapi.models import Config
    from alibabacloud_oss_util.models import RuntimeOptions
    def searchImageByName() :
        request = SearchImageByNameRequest()
        # Required. The name of the Image Search instance. 
        request.instance_name = '<instanceName>'
        # Required. The ID of the product. The value cannot exceed 512 characters in length. 
        # A product ID can relate to multiple image names. 
        request.product_id = '<productId>'
        # Required. The name of the image. The value cannot exceed 512 characters in length. 
        # 1. An image is uniquely identified by the values of the product_id and pic_name parameters. 
        # 2. If you add multiple images that share the same values of the product_id and pic_name parameters, only the last image that you add is retained. 
        request.pic_name = '<picName>'
        # Optional. The ID of the product category. 
        # 1. For product image searches: If you set a category ID for an image, the specified category prevails. If you do not set a category ID for an image, the system predicts the category, and returns the ID of the predicted category in the response. 
        # 2. For cloth, brand, and generic image searches: The category ID is set to 88888888 regardless of whether a category ID is set. 
        request.categoryId = 3
        # Optional. The number of entries to be returned. Valid values: 1 to 100. Default value: 10. 
        request.num = 10
        # Optional. The ordinal number of the first entry that is returned. Valid values: 0 to 499. Default value: 0. 
        request.start = 0
        # Optional. Specifies whether to recognize the main subject in the image. Default value: True. 
        # 1.If you set this parameter to True, the system recognizes the main subject in the image, and searches for images based on the recognized subject. The response includes the recognition result. 
        # 2. If you set this parameter to False, the system does not recognize the main subject in the image, and searches for images based on the entire image. 
        # 3.For cloth image searches, this parameter does not take effect. The system searches for images based on the entire image. 
        request.crop = True
        # Optional. The main area of the image. The value is in the format of x1,x2,y1,y2. x1 and y1 indicate the position of the upper-left point of the area, in pixels. x2 and y2 indicate the position of the lower-right point of the area, in pixels. The specified area cannot cross the boundary of the image. 
        # If you set the main area, the system searches for images based on the main area regardless of the value of the crop parameter. 
        # 3.For cloth image searches, this parameter does not take effect. The system searches for images based on the entire image. 
        request.region="167,467,221,407"
        # Optional. The filter condition.
        # The int_attr field supports the following operators: >, >=, <, <=, and =. The str_attr field supports the following operators: = and !=.You can join multiple filter conditions by using the AND or OR logical operator. 
        # Examples:
        # 1. Filter images based on the int_attr field: int_attr>=100
        # 2. Filter images based on the str_attr field: str_attr!="value1" 
        # 3. Filter images based on int_attr and str_attr fields: int_attr=1000 AND str_attr="value1"
        request.filter="int_attr=56 AND str_attr=\"test\""
        config = Config()
        config.access_key_id = '<accessKeyId>'
        config.access_key_secret = '<accessKeySecret>'
        config.endpoint = 'imagesearch.[regionId].aliyuncs.com'
        config.region_id = '<regionId>'
        config.type = 'access_key'
        client = Client(config)
        response = client.search_image_by_name(request)
        print(response.to_map())
    if __name__ == '__main__':
        searchImageByName()
  • Sample response
    {
      'RequestId': '7BC00158-3B9B-49C4-9E25-FFEC28AF3CE8',
      'Success': True,
      'Code': 0,
      'Msg': 'success',
      'Auctions': [{
        'CategoryId': 20,
        'ProductId': 'test-version-001',
        'PicName': 'test-version-001.jpg',
        'CustomContent': None,
        'score':1.0,
        'SortExprValues': '5.37633353624177e+24;0',
        'IntAttr': None,
        'StrAttr': None
      }, {
        'CategoryId': 20,
        'ProductId': 'test_0426_1',
        'PicName': 'test_0426_1.png',
        'CustomContent': None,
        'score':1.0,
        'SortExprValues': '2.71303606033325;263',
        'IntAttr': None,
        'StrAttr': None
      }],
      'Head': {
        'DocsReturn': 5,
        'DocsFound': 5,
        'SearchTime': 15
      },
      'PicInfo': {
        'CategoryId': 20,
        'Region': None,
        'AllCategories': [{
          'Id': 0,
          'Name': 'Tops'
        }, {
          'Id': 1,
          'Name': 'Dress'
        }, {
          'Id': 2,
          'Name': 'Bottoms'
        }, {
          'Id': 3,
          'Name': 'Bag'
        }, {
          'Id': 4,
          'Name': 'Shoes'
        }, {
          'Id': 5,
          'Name': 'Accessories'
        }, {
          'Id': 6,
          'Name': 'Snack'
        }, {
          'Id': 7,
          'Name': 'Makeup'
        }, {
          'Id': 8,
          'Name': 'Bottle'
        }, {
          'Id': 9,
          'Name': 'Furniture'
        }, {
          'Id': 20,
          'Name': 'Toy'
        }, {
          'Id': 21,
          'Name': 'Underwear'
        }, {
          'Id': 22,
          'Name': 'Digital device'
        }, {
          'Id': 88888888,
          'Name': 'Other'
        }],
        'MultiRegion': [{
            'Region': '112,440,76,387'
         }]
      }
    }

Delete

  • Sample code
    def deleteImage() :
        request = DeleteImageRequest()
        # Required. The name of the Image Search instance. 
        request.instance_name = '<instanceName>'
        # Required. The ID of the product. The value cannot exceed 512 characters in length. 
        # A product ID can relate to multiple image names. 
        request.product_id = '<productId>'
        # Optional. The name of the image. The value cannot exceed 512 characters in length. 
        # 1. An image is uniquely identified by the values of the product_id and pic_name parameters. 
        # 2. If you do not set this parameter, the system deletes all the images that are related to the specified product ID. If you set this parameter, the system deletes only the image that is specified by the product_id and pic_name parameters. 
        request.pic_name = '<picName>'
        config = Config()
        config.access_key_id = '<accessKeyId>'
        config.access_key_secret = '<accessKeySecret>'
        config.endpoint = 'imagesearch.[regionId].aliyuncs.com'
        config.region_id = '<regionId>'
        config.type = 'access_key'
        client = Client(config)
        response = client.delete_image(request)
        print(response.to_map())
    if __name__ == '__main__':
        deleteImage()
  • Sample response
    {
      'RequestId': '9ADA959B-B639-4B3B-841D-2399F1C34DA8',
      'Success': True,
      'Message': 'success',
      'Code': 0
    }