How do I convert local .JPG file to Base64 to work with Boto3 and Detect_Text?
Asked Answered
F

2

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.

Fer answered 28/11, 2017 at 22:57 Comment(2)
U can jst load the image and convert it to base 64Fantasm
Possible duplicate of How to convert PIL Image.image object to base64 string?Fantasm
T
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})
Tice answered 28/11, 2017 at 23:45 Comment(0)
I
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
Inheritance answered 3/2, 2019 at 15:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.