This topic describes how to use Content Moderation SDK for Go to perform optical character recognition (OCR). This way, you can recognize text in images.
Prerequisites
Go dependencies are installed. For more information, see Installation.
Note
You must use the required Go version described in the Installation topic to install the dependencies. Otherwise, subsequent operation calls fail.
Submit synchronous OCR tasks
Operation | Description | Supported region |
ImageSyncScanRequest | Submits synchronous OCR tasks with the scenes parameter set to ocr to recognize text in images. |
|
Sample code
package main
import (
"encoding/json"
"fmt"
"github.com/aliyun/alibaba-cloud-sdk-go/services/green"
"strconv"
)
func main() {
/**
* Note: We recommend that you reuse the instantiated client as much as possible. This improves moderation performance and avoids repeated client connections.
* Common ways to obtain environment variables:
* Obtain the AccessKey ID of your RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
* Obtain the AccessKey secret of your RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
*/
client, _err := green.NewClientWithAccessKey(
"cn-shanghai",
"We recommend that you obtain the AccessKey ID of your RAM user from environment variables",
"We recommend that you obtain the AccessKey secret of your RAM user from environment variables")
if err != nil {
fmt.Println(err.Error())
return
}
task1 := map[string]interface{}{"dataId": "ID of the image to be moderated", "url": "URL of the image to be moderated"}
// Example: If you moderate the image of the front side of an ID card, specify id-card-front.
cardExtras := map[string]interface{}{"card": "id-card-front"}
// Example: If you moderate the image of the back side of an ID card, specify id-card-back.
// cardExtras := map[string]interface{}{"card": "id-card-back"}
// scenes: the moderation scenarios.
content, _ := json.Marshal(
map[string]interface{}{
"tasks": task1, "scenes": [...]string{"ocr"}, "bizType": "Business scenario", "extras": cardExtras,
},
)
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())
}