如何通过Google Drive OCR从图像获取文本

时间:2019-06-14 20:07:21

标签: python google-drive-api google-oauth2

在Google驱动器中,可以将图像或pdf文件作为Google文档打开。 通过此过程,将使用OCR中的文本创建一个google doc文件。 这是一个免费过程[除Cloud Vision之外] 如何从图像获取文本? 请用python编写代码

1 个答案:

答案 0 :(得分:0)

在Python中使用Drive API,您需要获取项目客户端密码,并将范围设置为https://www.googleapis.com/auth/drive。从您的项目中下载client_secret.json文件,并将其文件位置放在下面的位置:

from __future__ import print_function
import httplib2
import os
import io
from apiclient import discovery
from apiclient.http import MediaFileUpload, MediaIoBaseDownload
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage

SCOPES = "https://www.googleapis.com/auth/drive"
CLIENTSECRET = "<client_secret_json_location>"
APPNAME = "AppName"

def authenticate():

    store = Storage(CLIENTSECRET)
    creds = store.get()
    pycheck = None

    if not creds or creds.invalid:
        flow = client.flow_from_clientsecrets(CLIENTSECRET, SCOPES)
        flow.user_agent = APPNAME
        if pycheck:
            creds = tools.run_flow(flow, store, flags)
        else:
            creds = tools.run(flow, store)

    return creds

然后可以调用API上载图像并检索OCR输出。您可以查看MediaIoBaseDownload类here的文档。 export_media()方法将导出为请求的MIME类型和returns exported content

def main():
    creds = authenticate()
    http = creds.authorize(httplib2.Http())
    service = discovery.build("drive", "v3", http = http)

    imgfile = "image.png"
    txtfile = "output.txt"
    mimeType = "application/vnd.google-apps.document"
    requestBody = {
            "name": imgfile,
            "mimeType": mimeType
        }

    media = MediaFileUpload(imgfile, mimetype = mimeType, resumable = True)

    request = service.files().export_media(fileId = file["id"], mimeType = "text/plain")

    dl = MediaIoBaseDownload(io.FileIO(txtfile, "wb"), request)

    isComplete = False

    while isComplete != True:
        status, isComplete = dl.next_chunk()

    service.files().delete(fileId = file["id"]).execute()
    print("Image uploaded and OCR output saved to " + txtfile + ".")

使用this image输出this text file尝试这段代码。

为进一步阅读或进一步了解OCR,Cloud Vision API具有专用于图像,PDF /文本文件和手写的光学字符识别。您可以查看此文档here