This topic describes how to use the Go software development kit (SDK) to search for images that are similar to a specified image.
Description
The similar image search feature helps you retrieve multiple images from an image library that are similar to a given image. For more information about the parameters, see the Similar Image Search API documentation.
You must use the AI Guardrails endpoint to call the service using the SDK. For more information about API endpoints, see Endpoints.
-
This SDK supports only image URLs. It does not support local files or binary data.
-
The following types of URLs are supported:
-
Public HTTP and HTTPS URLs. The URLs cannot exceed 2,048 characters in length.
-
Alibaba Cloud Object Storage Service (OSS) URLs in the format of
oss://<bucket-name>.<endpoint>/<object-name>. You must grant AI Guardrails the required permissions to access the destination OSS bucket. The bucket and the AI Guardrails service must be in the same region. For more information, see Authorize AI Guardrails to access OSS buckets.
-
Prerequisites
Go dependencies are installed. For more information, see Installation.
You must use the required Go version described in the Installation topic to install the dependencies. Otherwise, subsequent operation calls fail.
Submit a similar image search task
package main
import (
"encoding/json"
"fmt"
"github.com/aliyun/alibaba-cloud-sdk-go/services/green"
"strconv"
)
func main() {
/**
* Note: To improve detection performance, reuse the instantiated client as much as possible.
* This avoids repeatedly establishing connections.
* Common ways to get environment variables:
* To get the AccessKey ID of a RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
* To get the AccessKey secret of a RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
*/
client, _err := green.NewClientWithAccessKey(
"cn-shanghai",
"your-access-key-id",
"your-access-key-secret")
if err != nil {
fmt.Println(err.Error())
return
}
task1 := map[string]interface{}{
"dataId": "your-data-id",
"url": "https://your-image-url.com/example.jpg",
"similarityLibraries": [...]string{"your-image-library-name"},
}
/**
* Set the detection scenario. Billing is based on the scenario specified here.
* similarity: indicates a similar image search.
*/
content, _ := json.Marshal(
map[string]interface{}{
"tasks": task1, "scenes": [...]string{"similarity"},
},
)
request := green.CreateImageSyncScanRequest()
request.SetContent(content)
response, _err := client.ImageSyncScan(request)
if _err != nil {
fmt.Println(_err.Error())
return
}
if response.GetHttpStatus() != 200 {
fmt.Println("response not success. status:" + strconv.Itoa(response.GetHttpStatus()))
}
fmt.Println(response.GetHttpContentString())
}