• 【Python】Python 图片文字识别(OCR)


    Python 图片文字识别(OCR)

    1. OCR与Tesseract介绍

    将图片翻译成文字一般被称为光学文字识别(Optical Character Recognition,OCR)。可以实现OCR 的底层库并不多,目前很多库都是使用共同的几个底层OCR 库,或者是在上面进行定制。

    Tesseract 是一个OCR 库,目前由Google 赞助(Google 也是一家以OCR 和机器学习技术闻名于世的公司)。Tesseract 是目前公认最优秀、最精确的开源OCR 系统。

    除了极高的精确度,Tesseract 也具有很高的灵活性。它可以通过训练识别出任何字体(只要这些字体的风格保持不变就可以),也可以识别出任何Unicode 字符。

    2. Tesseract的安装与使用

    Tesseract的Windows安装包下载地址为: http://digi.bib.uni-mannheim.de/tesseract/tesseract-ocr-setup-4.00.00dev.exe ,下载后双击直接安装即可。安装完后,需要将Tesseract添加到系统变量中。在CMD中输入tesseract -v, 如显示以下界面,则表示Tesseract安装完成且添加到系统变量中。

    Linux 用户可以通过apt-get 安装, Debian 10, Debian 11, Ubuntu 22.04验证通过:

    sudo apt install tesseract-ocr tesseract-ocr-chi-sim python3-tesserocr
    但是要注意 python3-tesserocr 并非是下面要介绍的。这一节介绍的库名称为 pytesseract 。 pytesseract是Tesseract关于Python的接口,还需要一个Python的图片处理模块,可以安装pillow。 使用下面命令安装完后,就可以使用Python调用Tesseract了:

    pip install pytesseract

    import pytesseract

    3. 识别示例1

    用Tesseract可以识别格式规范的文字,主要具有以下特点:

    使用一个标准字体(不包含手写体、草书,或者十分“花哨的”字体)

    虽然被复印或拍照,字体还是很清晰,没有多余的痕迹或污点

    排列整齐,没有歪歪斜斜的字

    没有超出图片范围,也没有残缺不全,或紧紧贴在图片的边缘

    下面将给出几个tesseract识别图片中文字的例子。

    from PIL import Image

    text = pytesseract.image_to_string(Image.open(‘./ocra1.jpg’))
    print(text)
    BREAKING THE STATUE

    i have always known

    i just didn’t understand
    the inner conflictions
    arresting our hands
    gravitating close enough
    expansive distamce between
    i couldn’t give you more
    but 1 meant everything
    when the day comes

    you find your heart

    wants something more

    than a viece and a part
    your life will change
    like astatue set free

    to walk among us

    to created estiny

    we didn’t break any rules
    we didn’t make mistakes
    making beauty in loving
    making lovine for days—

    SHILOW

    4. 识别示例2

    接着是稍微有点倾斜的文字图片th.jpg,识别情况如下:

    可以看到识别的情况不如刚才规范字体的好,但是也能识别图片中的大部分字母。

    text = pytesseract.image_to_string(Image.open(‘./ocrb2.jpg’))
    text
    ‘Vieare!n’
    3.11.5. 识别示例3
    最后是识别简体中文,需要事先安装简体中文语言包,下载地址为:https://github.com/tesseract-ocr/tessdata/find/master/chi_sim.traineddata ,再将 chi_sim.traineddata 放在 C:\Program Files (x86)\Tesseract-OCR\tessdata 目录下。我们以图片timg.jpg为例:

    输入命令:

    tesseract timg.jpg timg.txt -l chi_sim
    示例图片:

    text = pytesseract.image_to_string(
    Image.open(‘./ocrc3.jpg’),
    lang = ‘chi_sim’)
    识别结果如下: 只识别错了一个字,识别率还是不错的。

    print(text)
    长相思
    【清】纳兰性德
    山一程,水一程。身向榆
    关那畔行,夜深干帐灯。
    风一更,雪一更。联碎乡
    心梦不成,故园无此声。
    最后加一句,Tesseract对于彩色图片的识别效果没有黑白图片的效果好。

  • 相关阅读:
    图文并茂,让你一探究竟—— 二叉树(附有源码实现)
    Python中静态方法与类方法
    js检测一个元素是否在另一个元素内部的原生方法document.caretRangeFromPoint
    C++11 新增特性
    C++:类与对象(3)
    html用法总结
    EN 14384立柱式消防栓—CE认证
    这次弄一下maven 多模块项目,用vscode新建一下,便于管理项目
    [附源码]计算机毕业设计springboot网上书城网站
    Window 窗口函数 (Spark Sql)
  • 原文地址:https://blog.csdn.net/wjianwei666/article/details/134272771