python 3调用百度OCR API实现剪贴板文字识别

yipeiwu_com5年前Python基础

本程序调用百度OCR API对剪贴板的图片文字识别,配合CaptureScreen软件,可快速识别文字。

#!python3
import urllib.request, urllib.parse
import os, io, sys, json, socket
import base64
from PIL import ImageGrab
 
socket.setdefaulttimeout(30)
 
def get_auth():
  apikey = 'your apikey'
  secret_key = 'your secret key'
  host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s' % (apikey, secret_key)
  req = urllib.request.Request(host)
  req.add_header('Content-Type', 'application/json; charset=UTF-8')
  res = urllib.request.urlopen(req)
  content = res.read()
  if (content):
    o = json.loads(content.decode())
    return o['access_token']
  return None
 
def ocr_clipboard():
  im = ImageGrab.grabclipboard()
  if im is None:
    print('No image in clipboard')
    return
  print('image size: %sx%s\n>>>\n' % (im.size[0], im.size[1]))
  mf = io.BytesIO()
  im.save(mf, 'JPEG')
  mf.seek(0)
  buf = mf.read()
  b64 = base64.encodebytes(buf)
  access_token = get_auth()
  if access_token is not None:
    url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=%s' % access_token
    data = urllib.parse.urlencode({'image' : b64}).encode()
    req = urllib.request.Request(url, method='POST')
    req.add_header('Content-Type', 'application/x-www-form-urlencoded')
    with urllib.request.urlopen(req, data) as p:
      res = p.read().decode('utf-8')
      o = json.loads(res)
      if o['words_result'] is not None:
        for w in o['words_result']:
          print(w['words'])
      print('\n<<<')
  else:
    print('access_token is none')
 
if __name__ == '__main__':
 
  x = input('ocr form clipboard image: z to ocr, q to quit-->')
  while(x != 'q'):
    if x=='z':
      ocr_clipboard()
    x = input('ocr from clipboard image: r to ocr, q to quit-->')
  print('bye')

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python中字符串的常见操作技巧总结

本文实例总结了Python中字符串的常见操作技巧。分享给大家供大家参考,具体如下: 反转一个字符串 >>> S = 'abcdefghijklmnop' >&...

Django 路由控制的实现代码

一、URL路由基础 URL是web服务的路口,用户通过浏览器发送过来的任何请求都会被发送到一个指定的URL地址里,然后被响应。 在django项目中编写路由就是向外暴露我们接收哪些U...

CentOS中使用virtualenv搭建python3环境

问题描述 环境: CentOS6.5 想在此环境下使用python3进行开发,但CentOS6.5默认的python环境是2.6.6版本。 之前的做法是直接从源码安装python3,...

python 正则表达式 概述及常用字符

1.元字符: . 它匹配除了换行字符外的任何字符,在 alternate 模式(re.DOTALL)下它甚至可以匹配换行 ^ 匹配行首。除非设置 MULTILINE 标志,它只是匹配字符...

Python使用MD5加密字符串示例

Python加密模块有好几个,但无论是哪种加密方式都需要先导入相应的加密模块然后再使用模块对字符串加密。 先导入md5加密所需模块: 复制代码 代码如下: import hashlib...