B4J Question Send Image to Googles Vision API

Blueforcer

Well-Known Member
Licensed User
Longtime User
Hi,

im trying to use googles Cloud AI and the Vision API.
https://cloud.google.com/vision/docs/reference/rest/v1/images/annotate

I found an example for phyton:

B4X:
def detect_text(image_file, access_token=None):

    with open(image_file, 'rb') as image:
        base64_image = base64.b64encode(image.read()).decode()

    url = 'https://vision.googleapis.com/v1/images:annotate?key={}'.format(access_token)
    header = {'Content-Type': 'application/json'}
    body = {
        'requests': [{
            'image': {
                'content': base64_image,
            },
            'features': [{
                'type': 'TEXT_DETECTION',
                'maxResults': 1,
            }]

        }]
    }
    response = requests.post(url, headers=header, json=body).json()
    text = response['responses'][0]['textAnnotations'][0]['description'] if len(response['responses'][0]) > 0 else ''
    return text

I tried to code this in B4J:

B4X:
    Dim img () As Byte
    img=Bit.InputStreamToBytes(File.OpenInput(xui.DefaultFolder, "image.png"))
    Dim su As StringUtils
    Dim encoded As String
    encoded = su.EncodeBase64(img)
 
    Dim body As Map
    body.Initialize

    Dim image As Map
    image.Initialize
    image.Put("content",encoded)

    Dim features As Map
    features.Initialize
    features.Put("type","TEXT_DETECTION")
    features.Put("maxResults",1)
 
    body.Put("requests",image)
    body.Put("features",features)
 
    Dim j As JSONGenerator
    j.Initialize(body)
    job.PostString("https://vision.googleapis.com/v1/images:annotate?key="&googlekey,j.ToString)
 
    Wait For (job) JobDone(job As HttpJob)
    If job.Success Then
        Log(job.GetString)
    Else
        Log(job.ErrorMessage)
    End If

But i get the message that the JSON Payload is invalid.
B4X:
    "message": "Invalid JSON payload received. Unknown name \"{\"features\":{\"maxResults\":1,\"type\":\"TEXT_DETECTION\"},\"requests\":{\"content\":\"iVBORw0KGgoAAAANSUh...
Can someone help me?
 
Last edited:

DonManfred

Expert
Licensed User
Longtime User
request and features must be a List based on the code above

{
'requests': [{
'image': {
'content': base64_image,
},
'features': [{
'type': 'TEXT_DETECTION',
'maxResults': 1,
}]

}]

requests must be a list. It contains a
map which contains the key image which is a map too.
The map also need to have a list inside. features
the features list contains one map with the key type and maxResults
 
Upvote 0

yiankos1

Well-Known Member
Licensed User
Longtime User
Last edited:
Upvote 0
Top