Search code examples
python-3.xbase64ocrgoogle-vision

Trying to pass a base_64 encoded image to google authentication


So i am working on a small project(a restful service so json format which is not mentioned in the code) in which the code accepts base_64 image data and decodes it to from an image ,i'm able to convert it back to image but i am not able to use google vision(googel ocr) on the image to extract the text . The only part that isn't working is the following block of code:


from flask import Flask,request,jsonify
import os,io,re,glob,base64
from google.cloud import vision
from google.cloud.vision import types
from PIL import Image
app = Flask(__name__)
os.environ['GOOGLE_APPLICATION_CREDENTIALS']=r'date_scanner.json'
@app.route('/jason_example',methods=['POST'])
def jason_example():
    req_data=request.get_json()
    base_64_image_content=req_data['imgcnt']
#the issue starts from here 
    image = base64.b64decode(base_64_image_content)
    image=Image.open(io.BytesIO(image))
    image=vision.types.Image(content=content)
    response=client.text_detection(image=image)
    texts=response.text_annotations`
    enter code here

Solution

  • No need to use Image.open which I think is a PIL method anyway. You should be able to decode this straight to a byte string with base64.decodebytes, as outlined in this answer,

    The code should look like:

    # the issue starts from here 
    image_bytes = base64.decodebytes(base_64_image_content)
    image = vision.types.Image(content=image_bytes)
    response=client.text_detection(image=image)
    texts=response.text_annotations