5

Relevant Code:

import boto3
from PIL import Image
import base64

client = boto3.client('rekognition')

filename = r'C:\Users\H-63\Pictures\scantests\Rekognition test.JPG'

with open(filename, 'rb') as image_file:
    image = image_file.read()

image = base64.b64encode(image).decode('UTF-8')

response = client.detect_text(
    Image={'Bytes': image
        })

However, When I run this, I get an error:

An error occurred (InvalidImageFormatException) when calling the DetectText operation: Request has Invalid image format

How do I get my image to be the right format for detect_text? The documentation says it has to be base64 encoding.

M Waz
  • 755
  • 1
  • 7
  • 18
  • U can jst load the image and convert it to base 64 – user1767754 Nov 28 '17 at 23:00
  • Possible duplicate of [How to convert PIL Image.image object to base64 string?](https://stackoverflow.com/questions/31826335/how-to-convert-pil-image-image-object-to-base64-string) – user1767754 Nov 28 '17 at 23:01

2 Answers2

7

I'm not sure why the documentation even mentions base64, but the function requires bytes. So just use:

with open(filename, 'rb') as image_file:
  image = image_file.read()
  client.detect_text(Image={'Bytes': image})
kichik
  • 33,220
  • 7
  • 94
  • 114
3

You can just use bytes the return of read() https://docs.aws.amazon.com/rekognition/latest/dg/images-bytes.html

#Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)

import boto3

if __name__ == "__main__":

 imageFile='input.jpg'
 client=boto3.client('rekognition')

 with open(imageFile, 'rb') as image:
     response = client.detect_labels(Image={'Bytes': image.read()})

 print('Detected labels in ' + imageFile)    
 for label in response['Labels']:
     print (label['Name'] + ' : ' + str(label['Confidence']))

 print('Done...')


[1]: https://docs.aws.amazon.com/rekognition/latest/dg/images-bytes.html