利用Tesseract-ocr进行图片文字识别

文章作者:易明
个人博客:https://yiming1012.github.io
主页:https://www.jianshu.com/u/6ebea55f5cec
邮箱地址:[email protected]

背景简介

    最近有一个需求,识别随车清单图片,并提取关键信息。经过调研选取了两种方法尝试:

1、Google维护的Tesseract-ocr
2、百度云OCR

Tesseract-ocr介绍

1、从https://github.com/UB-Mannheim/tesseract/wiki
下载对应的版本。推荐4.0以上。

2、安装过程中需要下载Additional language data。你可以全选,也可以只下载中文包。安装的过程比较漫长……

3、测试Tesseract

  1. 查看版本:tesseract -v



    2.查看语言:tesseract --list-langs



    3.识别图片:tesseract hua.png out

由上面看出,识别出来的都是啥啊。

4、通过Python识别图片文字。

  1. Python代码
# -*- coding: utf-8 -*-
from PIL import Image as myImage
import pytesseract
# 指定tesseract路径
pytesseract.pytesseract.tesseract_cmd = 'C:/Program Files (x86)/Tesseract-OCR/tesseract.exe'
# 读取图片
img = myImage.open('hua.png')
# 识别图片
text = pytesseract.image_to_string(img, lang='chi_sim')
print(text)
  1. 待识别的图片


  2. 识别效果

    可以看出,tesseract-ocr的识别效果较差。不过,它的优势是可以通过jTessBoxEditor工具来修正错误数据训练字库,感兴趣的同学可以尝试,这里不再赘述。

百度云OCR

1、调用百度云文字识别的API,首先需要进入百度智能云官网——产品服务——文字识别——应用列表——创建应用。创建成功之后,便可以获的AppIDAPI KeySecret Key三个参数。


2、Python开发者可以参考Python-SDK指南,其中对Python如何调用接口以及具体参数配置做了详细说明。其他语言开发者可以参考该网站其他SDK文档。
3、通过pip安装baidu-aip包: pip install baidu-aip
4、代码展示:

# -*- coding: gbk -*-
from aip import AipOcr
import pandas as pd

# 配置百度参数
config = {
    'appId': 'yourappid',
    'apiKey': 'yourapiKey',
    'secretKey': 'yoursecretKey'
}
client = AipOcr(**config)

def get_file_content(file):
    with open(file, 'rb') as fp:
        return fp.read()

def img_to_str(image_path):
    image = get_file_content(image_path)
    """ 如果有可选参数 """
    options = {}
    # 是否检测图像朝向,默认不检测
    options["detect_direction"] = "true"
    # 是否返回识别结构中每一行的置信度
    options["probability"] = "true"
    # result = client.basicGeneral(image)
    result = client.basicAccurate(image, options)
    print(result.get("words_result"))
    df = pd.DataFrame(result.get("words_result"))
    return df

pictureContent = img_to_str('hua.png')
print(pictureContent)
print(list(pictureContent['words']))

5、效果展示



其中,图片为向左旋转90度后的,从上面看出,该接口能检测图片朝向,并能识别图中文字,而且准确率非常高。

你可能感兴趣的:(利用Tesseract-ocr进行图片文字识别)