Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 335
M Waz Avatar asked Nov 28 '17 22:11

M Waz


People also ask

Can we convert image to Base64?

The Image encoding tool supports loading the Image File to transform to Base64. Click on the Upload Image button and select File. Image to Base64 Online works well on Windows, MAC, Linux, Chrome, Firefox, Edge, and Safari.

How do I encode to Base64 in Python?

In order to encode the image, we simply use the function base64. b64encode(s) . Python describes the function as follows: Encode the bytes-like object s using Base64 and return the encoded bytes.


1 Answers

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})
like image 177
kichik Avatar answered Oct 13 '22 18:10

kichik