2017-06-14 5 views
0

Ich habe den folgenden Code in Google App Engine, die ein Bild vom Benutzer akzeptiert, und führt anschließend eine OCR für dieses Bild.Google App Engine: Bild zu Base64 String für OCR (Python)

index.html:

<form action="/submit" method="post" enctype="multipart/form-data"> 
    <input type="file" name="newImage" capture="camera"> 
    <input type="submit" value="Submit"> 
</form> 

main.py:

import requests 

def image_to_text(encoded_string, content_type="jpeg"): 

    api_key = "API_KEY" 
    overlay = False 
    language = 'eng' 

    payload = {'isOverlayRequired': overlay, 
      'apikey': api_key, 
      'language': language, 
      'base64Image': "data:image/{};base64,{}".format(content_type, 
                  encoded_string) 
      } 

    r = requests.post('https://api.ocr.space/parse/image', 
        data=payload) 
    return r.content.decode() 



class Submit(webapp2.RequestHandler): 
    def post(self): 
     new_image = self.request.get("newImage") 
     if new_image is not '': # ie user uploads an image 
      IMG = UploadImage() 
      IMG.img = new_image # ndb.BlobProperty() 
      img_key = IMG.put() # stores it in datastore 
      img_key_url = img_key.urlsafe() 
      base64_string = new_image.encode('base64') # this is the step that I may be doing wrongly 
      text= image_to_text(base64_string) 

jedoch bekam ich einen Fehler, der besagt, dass es keine gültige base64 Bild ist.

Der folgende Code (zum Lesen eines Bildes und Konvertieren in Base64-Zeichenfolge) funktioniert, wenn ich eine Datei von meiner lokalen Festplatte obwohl. (Die OCR-API, die ich verwende sind hier zu finden: https://ocr.space/ocrapi#python

OCR.py:.!

import requests 
import base64 

def image_to_text(base64_encoded_string=None,content_type="jpeg"): 
    filename = 'image.jpg' 
    with open(filename, 'rb') as f: 
     encoded_string = base64.b64encode(f.read()).strip('\n') 

     api_key = "API_KEY" 
     overlay = False # Boolean value indicating if the overlay is required along with the image/pdf parsed result 
     language = 'eng' 

     payload = {'isOverlayRequired': overlay, 
      'apikey': api_key, 
      'language': language, 
      'base64Image':"data:image/{};base64,{}".format(content_type, 
                  encoded_string) 
      } 



    r = requests.post('https://api.ocr.space/parse/image', 
         data=payload) 
    return r.content.decode() 

Jede Hilfe wäre sehr dankbar Dank

Antwort

0

Oh warte ich löste es auf meinem eigene, indem Sie dies tun:

encoded_string = base64.b64encode(image).strip('\n')