Pytesser——OCR in Python using the Tesseract engine from Google
pytesser是谷歌OCR开源项目的一个模块,在python中导入这个模块即可将图片中的文字转换成文本。
链接: https://code.google.com/p/pytesser/
pytesser  调用了  tesseract。在python中调用pytesser模块,pytesser又用tesseract识别图片中的文字。
下面是整个过程的实现步骤:
1、首先要在code.google.com下载pytesser。https://code.google.com/p/pytesser/downloads/detail?name=pytesser_v0.0.1.zip
这个是免安装的,可以放在python安装文件夹的\Lib\site-packages\  下直接使用
pytesser里包含了tesseract.exe和英语的数据包(默认只识别英文),还有一些示例图片,所以解压缩后即可使用。
可通过以下代码测试:
[python]  view plain copy
  1. >>> from pytesser import *
  2. >>> image = Image.open('fnord.tif')  # Open image object using PIL
  3. >>> print image_to_string(image)     # Run tesseract.exe on image
  4. fnord
  5. >>> print image_file_to_string('fnord.tif')
  6. fnord
[python]  view plain copy
  1. <pre name="code" class="python">from pytesser import *
  2. #im = Image.open('fnord.tif')
  3. #im = Image.open('phototest.tif')
  4. #im = Image.open('eurotext.tif')
  5. im = Image.open('fonts_test.png')
  6. text = image_to_string(im)
  7. print text</pre>
  8. <pre></pre>
  9. <pre></pre>
  10. <pre></pre>
注:该模块需要PIL库的支持。
2、解决识别率低的问题
可以增强图片的显示效果,或者将其转换为黑白的,这样可以使其识别率提升不少:
[python]  view plain copy
  1. enhancer = ImageEnhance.Contrast(image1)
  2. image2 = enhancer.enhance(4)

可以再对image2调用 image_to_string识别

3、识别其他语言
tesseract是一个命令行下运行的程序,参数如下:
tesseract  imagename outbase [-l  lang]  [-psm N]  [configfile...]
imagename是输入的image的名字
outbase是输出的文本的名字,默认为outbase.txt
-l  lang  是定义要识别的的语言,默认为英文
详见 http://tesseract-ocr.googlecode.com/svn-history/r725/trunk/doc/tesseract.1.html
通过以下步骤可以识别其他语言:
(1)、下载其他语言数据包:
https://code.google.com/p/tesseract-ocr/downloads/list
将语言包放入pytesser的tessdata文件夹下
接下来修改pytesser.py的参数,下面是一个例子:
[python]  view plain copy
  1. """OCR in Python using the Tesseract engine from Google
  2. http://code.google.com/p/pytesser/
  3. by Michael J.T. O'Kelly
  4. V 0.0.2, 5/26/08"""
  5. import Image
  6. import subprocess
  7. import os
  8. import StringIO
  9. import util
  10. import errors
  11. tesseract_exe_name = 'dlltest' # Name of executable to be called at command line
  12. scratch_image_name = "temp.bmp" # This file must be .bmp or other Tesseract-compatible format
  13. scratch_text_name_root = "temp" # Leave out the .txt extension
  14. _cleanup_scratch_flag = True  # Temporary files cleaned up after OCR operation
  15. _language = "" # Tesseract uses English if language is not given
  16. _pagesegmode = "" # Tesseract uses fully automatic page segmentation if psm is not given (psm is available in v3.01)
  17. _working_dir = os.getcwd()
  18. def call_tesseract(input_filename, output_filename, language, pagesegmode):
  19. """Calls external tesseract.exe on input file (restrictions on types),
  20. outputting output_filename+'txt'"""
  21. current_dir = os.getcwd()
  22. error_stream = StringIO.StringIO()
  23. try:
  24. os.chdir(_working_dir)
  25. args = [tesseract_exe_name, input_filename, output_filename]
  26. if len(language) > 0:
  27. args.append("-l")
  28. args.append(language)
  29. if len(str(pagesegmode)) > 0:
  30. args.append("-psm")
  31. args.append(str(pagesegmode))
  32. try:
  33. proc = subprocess.Popen(args)
  34. except (TypeError, AttributeError):
  35. proc = subprocess.Popen(args, shell=True)
  36. retcode = proc.wait()
  37. if retcode!=0:
  38. error_text = error_stream.getvalue()
  39. errors.check_for_errors(error_stream_text = error_text)
  40. finally:  # Guarantee that we return to the original directory
  41. error_stream.close()
  42. os.chdir(current_dir)
  43. def image_to_string(im, lang = _language, psm = _pagesegmode, cleanup = _cleanup_scratch_flag):
  44. """Converts im to file, applies tesseract, and fetches resulting text.
  45. If cleanup=True, delete scratch files after operation."""
  46. try:
  47. util.image_to_scratch(im, scratch_image_name)
  48. call_tesseract(scratch_image_name, scratch_text_name_root, lang, psm)
  49. result = util.retrieve_result(scratch_text_name_root)
  50. finally:
  51. if cleanup:
  52. util.perform_cleanup(scratch_image_name, scratch_text_name_root)
  53. return result
  54. def image_file_to_string(filename, lang = _language, psm = _pagesegmode, cleanup = _cleanup_scratch_flag, graceful_errors=True):
  55. """Applies tesseract to filename; or, if image is incompatible and graceful_errors=True,
  56. converts to compatible format and then applies tesseract.  Fetches resulting text.
  57. If cleanup=True, delete scratch files after operation. Parameter lang specifies used language.
  58. If lang is empty, English is used. Page segmentation mode parameter psm is available in Tesseract 3.01.
  59. psm values are:
  60. 0 = Orientation and script detection (OSD) only.
  61. 1 = Automatic page segmentation with OSD.
  62. 2 = Automatic page segmentation, but no OSD, or OCR
  63. 3 = Fully automatic page segmentation, but no OSD. (Default)
  64. 4 = Assume a single column of text of variable sizes.
  65. 5 = Assume a single uniform block of vertically aligned text.
  66. 6 = Assume a single uniform block of text.
  67. 7 = Treat the image as a single text line.
  68. 8 = Treat the image as a single word.
  69. 9 = Treat the image as a single word in a circle.
  70. 10 = Treat the image as a single character."""
  71. try:
  72. try:
  73. call_tesseract(filename, scratch_text_name_root, lang, psm)
  74. result = util.retrieve_result(scratch_text_name_root)
  75. except errors.Tesser_General_Exception:
  76. if graceful_errors:
  77. im = Image.open(filename)
  78. result = image_to_string(im, cleanup)
  79. else:
  80. raise
  81. finally:
  82. if cleanup:
  83. util.perform_cleanup(scratch_image_name, scratch_text_name_root)
  84. return result
  85. if __name__=='__main__':
  86. im = Image.open('phototest.tif')
  87. text = image_to_string(im, cleanup=False)
  88. print text
  89. text = image_to_string(im, psm=2, cleanup=False)
  90. print text
  91. try:
  92. text = image_file_to_string('fnord.tif', graceful_errors=False)
  93. except errors.Tesser_General_Exception, value:
  94. print "fnord.tif is incompatible filetype.  Try graceful_errors=True"
  95. #print value
  96. text = image_file_to_string('fnord.tif', graceful_errors=True, cleanup=False)
  97. print "fnord.tif contents:", text
  98. text = image_file_to_string('fonts_test.png', graceful_errors=True)
  99. print text
  100. text = image_file_to_string('fonts_test.png', lang="eng", psm=4, graceful_errors=True)
  101. print text
这个是source里面提供的,其实若只要识别其他语言只要添加一个language参数就行了,下面是我的例子:
[python]  view plain copy
  1. """OCR in Python using the Tesseract engine from Google
  2. http://code.google.com/p/pytesser/
  3. by Michael J.T. O'Kelly
  4. V 0.0.1, 3/10/07"""
  5. import Image
  6. import subprocess
  7. import util
  8. import errors
  9. tesseract_exe_name = 'tesseract' # Name of executable to be called at command line
  10. scratch_image_name = "temp.bmp" # This file must be .bmp or other Tesseract-compatible format
  11. scratch_text_name_root = "temp" # Leave out the .txt extension
  12. cleanup_scratch_flag = True  # Temporary files cleaned up after OCR operation
  13. def call_tesseract(input_filename, output_filename, language):
  14. """Calls external tesseract.exe on input file (restrictions on types),
  15. outputting output_filename+'txt'"""
  16. args = [tesseract_exe_name, input_filename, output_filename, "-l", language]
  17. proc = subprocess.Popen(args)
  18. retcode = proc.wait()
  19. if retcode!=0:
  20. errors.check_for_errors()
  21. def image_to_string(im, cleanup = cleanup_scratch_flag, language = "eng"):
  22. """Converts im to file, applies tesseract, and fetches resulting text.
  23. If cleanup=True, delete scratch files after operation."""
  24. try:
  25. util.image_to_scratch(im, scratch_image_name)
  26. call_tesseract(scratch_image_name, scratch_text_name_root,language)
  27. text = util.retrieve_text(scratch_text_name_root)
  28. finally:
  29. if cleanup:
  30. util.perform_cleanup(scratch_image_name, scratch_text_name_root)
  31. return text
  32. def image_file_to_string(filename, cleanup = cleanup_scratch_flag, graceful_errors=True, language = "eng"):
  33. """Applies tesseract to filename; or, if image is incompatible and graceful_errors=True,
  34. converts to compatible format and then applies tesseract.  Fetches resulting text.
  35. If cleanup=True, delete scratch files after operation."""
  36. try:
  37. try:
  38. call_tesseract(filename, scratch_text_name_root, language)
  39. text = util.retrieve_text(scratch_text_name_root)
  40. except errors.Tesser_General_Exception:
  41. if graceful_errors:
  42. im = Image.open(filename)
  43. text = image_to_string(im, cleanup)
  44. else:
  45. raise
  46. finally:
  47. if cleanup:
  48. util.perform_cleanup(scratch_image_name, scratch_text_name_root)
  49. return text
  50. if __name__=='__main__':
  51. im = Image.open('phototest.tif')
  52. text = image_to_string(im)
  53. print text
  54. try:
  55. text = image_file_to_string('fnord.tif', graceful_errors=False)
  56. except errors.Tesser_General_Exception, value:
  57. print "fnord.tif is incompatible filetype.  Try graceful_errors=True"
  58. print value
  59. text = image_file_to_string('fnord.tif', graceful_errors=True)
  60. print "fnord.tif contents:", text
  61. text = image_file_to_string('fonts_test.png', graceful_errors=True)
  62. print text

在调用image_to_string函数时,只要加上相应的language参数就可以了,如简体中文最后一个参数即为 chi_sim, 繁体中文chi_tra,

也就是下载的语言包的 XXX.traineddata 文件的名字XXX,如下载的中文包是 chi_sim.traineddata, 参数就是chi_sim :
[python]  view plain copy
  1. text = image_to_string(self.im, language = 'chi_sim')

至此,图片识别就完成了。

额外附加一句:有可能中文识别出来了,但是乱码,需要相应地将text转换为你所用的中文编码方式,如:
text.decode("utf8")就可以了

利用pytesser模块实现图片文字识别相关推荐

  1. python批量识别图片中文字_利用Python批量进行图片文字识别

    实现逻辑 1. 批量获取图片的路径 2. 通过调用百度OCR接口批量识别图片 3. 将返回值写入txt 实现过程 1. 安装百度的Python SDK pip install baidu-aip 2. ...

  2. python批量图片文字识别_利用Python批量进行图片文字识别

    实现逻辑 1. 批量获取图片的路径 2. 通过调用百度OCR接口批量识别图片 3. 将返回值写入txt 实现过程 1. 安装百度的Python SDK pip install baidu-aip 2. ...

  3. Python模块介绍使用:EasyOCR快速实现图片文字识别

    hello,大家好,我是wangzirui32,今天我们来学习如何使用EasyOCR快速实现图片文字识别,开始学习吧! 1. 什么是OCR 2. 安装EasyOCR 安装命令: pip install ...

  4. 吴恩达《机器学习》第十八章:图片文字识别OCR

    文章目录 十八.应用实例:图片文字识别OCR 18.1 问题描述和流程图 18.2 滑动窗口 18.3 获取大量数据和人工数据 18.4 上限分析:下一步工作 十八.应用实例:图片文字识别OCR 18 ...

  5. 吴恩达机器学习(十五)—— 应用实例:图片文字识别

    应用实例:图片文字识别 1. 问题描述和流水线 2. 滑动窗口 3. 获取大量数据:人工数据合成 4. 上限分析:流水线的哪个模块最有改进价值   学习图片文字识别的应用实例要做的事情: 展示一个复杂 ...

  6. 2021-02-21 Python Easyocr 图片文字识别

    Python Easyocr 图片文字识别 前段时间做了车牌识别相关的内容分享,参看: 车牌识别(1)-车牌数据集生成 车牌识别(2)-搭建车牌识别模型 今天给大家分享一个简单的OCR文本识别工具:e ...

  7. 吴恩达《Machine Learning》精炼笔记 12:大规模机器学习和图片文字识别 OCR

    作者 | Peter 编辑 | AI有道 系列文章: 吴恩达<Machine Learning>精炼笔记 1:监督学习与非监督学习 吴恩达<Machine Learning>精 ...

  8. Android 图片文字识别DEMO(基于百度OCR)

    前言   OCR 是 Optical Character Recognition 的缩写,翻译为光学字符识别,指的是针对印刷体字符,采用光学的方式将纸质文档中的文字转换成为黑白点阵的图像文件,通过识别 ...

  9. python存数据库c读数据库喷码加工_python图片文字识别

    Python语言读取Marc后处理文件基础知识_材料科学_工程科技_专业资料.Python语言简介,Marc计算结果文件读取,焊接模拟后处理实例 基于python 的焊接后处理知识要点: ? ?... ...

  10. (python)实现一个简单的图片文字识别脚本

    文章目录 截图 文字识别## 访问剪切板 总结 快毕业了,除了准备答辩之外,就是看看书,各种瞎晃~ 那么,这两天在看书的时候遇到这么个问题: 首先,部分电子版的书籍是以扫描图片的形式展现的,在阅读过程 ...

最新文章

  1. 掌握 MySQL 这 19 个骚操作,效率至少提高3倍
  2. mysql+在服务中无法启动_MySQL服务初始化后无法启动
  3. js递归函数使用介绍
  4. 是否可以从一个static方法内部发出对非static方法的调用?
  5. 解锁UI自动化新姿势-UI Recorder
  6. 华硕笔记本自带win10改win7的方法
  7. React-Context
  8. omct问题之-webapps下多出的ROOT目录
  9. u盘被保护怎样解除?(第十招)
  10. 基于 MVP 的 Android 组件化开发框架实践 1
  11. mysql免费框架_MySQL(ORM框架)
  12. Newton迭代法求无约束目标函数极小值matlab实现
  13. Tapestry5单元测试
  14. 《Redis视频教程》(p19)
  15. 胡乱学Java_遇见类与对象
  16. 【思考】阿里云的混合云战略,凭啥扯上Zstack?
  17. 电脑配件 - 机械键盘的由来, 与普通键盘的区别以及如何选购及使用维护 - 学习/实践
  18. VUE+ ELEMENT 选人的弹窗组件
  19. NRF51822蓝牙服务(9)——动态修改设备的名称
  20. ei拼音的四个声调对应的字_幼儿园学前班拼音教案:复习 ei 以及四声调

热门文章

  1. Git 笔记 - git branch
  2. unity3d---物体加点击事件
  3. 软考报名全流程及注意事项
  4. node 爬虫 nightmare-handler
  5. python安装geopandas和Fiona报错:A GDAL API version must be specified.
  6. ​棱镜动态 | “TOPPer新训营”第二期开营啦!
  7. spring boot快速入门 4: jpa数据库操作 实现增删改查
  8. 数据分析 --- day16正则表达式
  9. 哪个语言更适合人工智能 女生能学人工智能吗
  10. 关于QTChart图表中附加文字标识(数据点名称)