利用pytesser模块实现图片文字识别

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. "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  
  8.   
  9.   
  10.   
注:该模块需要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.   
  6. import Image  
  7. import subprocess  
  8. import os  
  9. import StringIO  
  10.   
  11. import util  
  12. import errors  
  13.   
  14.   
  15. tesseract_exe_name = 'dlltest' # Name of executable to be called at command line  
  16. scratch_image_name = "temp.bmp" # This file must be .bmp or other Tesseract-compatible format  
  17. scratch_text_name_root = "temp" # Leave out the .txt extension  
  18. _cleanup_scratch_flag = True  # Temporary files cleaned up after OCR operation  
  19. _language = "" # Tesseract uses English if language is not given  
  20. _pagesegmode = "" # Tesseract uses fully automatic page segmentation if psm is not given (psm is available in v3.01)  
  21.   
  22. _working_dir = os.getcwd()  
  23.   
  24. def call_tesseract(input_filename, output_filename, language, pagesegmode):  
  25.         """Calls external tesseract.exe on input file (restrictions on types), 
  26.         outputting output_filename+'txt'"""  
  27.         current_dir = os.getcwd()  
  28.         error_stream = StringIO.StringIO()  
  29.         try:  
  30.                 os.chdir(_working_dir)  
  31.                 args = [tesseract_exe_name, input_filename, output_filename]  
  32.                 if len(language) > 0:  
  33.                         args.append("-l")  
  34.                         args.append(language)  
  35.                 if len(str(pagesegmode)) > 0:  
  36.                         args.append("-psm")  
  37.                         args.append(str(pagesegmode))  
  38.                 try:  
  39.                         proc = subprocess.Popen(args)  
  40.                 except (TypeError, AttributeError):  
  41.                         proc = subprocess.Popen(args, shell=True)  
  42.                 retcode = proc.wait()  
  43.                 if retcode!=0:  
  44.                         error_text = error_stream.getvalue()  
  45.                         errors.check_for_errors(error_stream_text = error_text)  
  46.         finally:  # Guarantee that we return to the original directory  
  47.                 error_stream.close()  
  48.                 os.chdir(current_dir)  
  49.   
  50. def image_to_string(im, lang = _language, psm = _pagesegmode, cleanup = _cleanup_scratch_flag):  
  51.         """Converts im to file, applies tesseract, and fetches resulting text. 
  52.         If cleanup=True, delete scratch files after operation."""  
  53.         try:  
  54.                 util.image_to_scratch(im, scratch_image_name)  
  55.                 call_tesseract(scratch_image_name, scratch_text_name_root, lang, psm)  
  56.                 result = util.retrieve_result(scratch_text_name_root)  
  57.         finally:  
  58.                 if cleanup:  
  59.                         util.perform_cleanup(scratch_image_name, scratch_text_name_root)  
  60.         return result  
  61.   
  62. def image_file_to_string(filename, lang = _language, psm = _pagesegmode, cleanup = _cleanup_scratch_flag, graceful_errors=True):  
  63.         """Applies tesseract to filename; or, if image is incompatible and graceful_errors=True, 
  64.         converts to compatible format and then applies tesseract.  Fetches resulting text. 
  65.         If cleanup=True, delete scratch files after operation. Parameter lang specifies used language. 
  66.         If lang is empty, English is used. Page segmentation mode parameter psm is available in Tesseract 3.01. 
  67.         psm values are: 
  68.         0 = Orientation and script detection (OSD) only. 
  69.         1 = Automatic page segmentation with OSD. 
  70.         2 = Automatic page segmentation, but no OSD, or OCR 
  71.         3 = Fully automatic page segmentation, but no OSD. (Default) 
  72.         4 = Assume a single column of text of variable sizes. 
  73.         5 = Assume a single uniform block of vertically aligned text. 
  74.         6 = Assume a single uniform block of text. 
  75.         7 = Treat the image as a single text line. 
  76.         8 = Treat the image as a single word. 
  77.         9 = Treat the image as a single word in a circle. 
  78.         10 = Treat the image as a single character."""  
  79.         try:  
  80.                 try:  
  81.                         call_tesseract(filename, scratch_text_name_root, lang, psm)  
  82.                         result = util.retrieve_result(scratch_text_name_root)  
  83.                 except errors.Tesser_General_Exception:  
  84.                         if graceful_errors:  
  85.                                 im = Image.open(filename)  
  86.                                 result = image_to_string(im, cleanup)  
  87.                         else:  
  88.                                 raise  
  89.         finally:  
  90.                 if cleanup:  
  91.                         util.perform_cleanup(scratch_image_name, scratch_text_name_root)  
  92.         return result  
  93.           
  94.   
  95. if __name__=='__main__':  
  96.         im = Image.open('phototest.tif')  
  97.         text = image_to_string(im, cleanup=False)  
  98.         print text  
  99.         text = image_to_string(im, psm=2, cleanup=False)  
  100.         print text  
  101.         try:  
  102.                 text = image_file_to_string('fnord.tif', graceful_errors=False)  
  103.         except errors.Tesser_General_Exception, value:  
  104.                 print "fnord.tif is incompatible filetype.  Try graceful_errors=True"  
  105.                 #print value  
  106.         text = image_file_to_string('fnord.tif', graceful_errors=True, cleanup=False)  
  107.         print "fnord.tif contents:", text  
  108.         text = image_file_to_string('fonts_test.png', graceful_errors=True)  
  109.         print text  
  110.         text = image_file_to_string('fonts_test.png', lang="eng", psm=4, graceful_errors=True)  
  111.         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.   
  6. import Image  
  7. import subprocess  
  8. import util  
  9. import errors  
  10.   
  11. tesseract_exe_name = 'tesseract' # 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.   
  16. def call_tesseract(input_filename, output_filename, language):  
  17.     """Calls external tesseract.exe on input file (restrictions on types), 
  18.     outputting output_filename+'txt'"""  
  19.     args = [tesseract_exe_name, input_filename, output_filename, "-l", language]  
  20.     proc = subprocess.Popen(args)  
  21.     retcode = proc.wait()  
  22.     if retcode!=0:  
  23.         errors.check_for_errors()  
  24.   
  25. def image_to_string(im, cleanup = cleanup_scratch_flag, language = "eng"):  
  26.     """Converts im to file, applies tesseract, and fetches resulting text. 
  27.     If cleanup=True, delete scratch files after operation."""  
  28.     try:  
  29.         util.image_to_scratch(im, scratch_image_name)  
  30.         call_tesseract(scratch_image_name, scratch_text_name_root,language)  
  31.         text = util.retrieve_text(scratch_text_name_root)  
  32.     finally:  
  33.         if cleanup:  
  34.             util.perform_cleanup(scratch_image_name, scratch_text_name_root)  
  35.     return text  
  36.   
  37. def image_file_to_string(filename, cleanup = cleanup_scratch_flag, graceful_errors=True, language = "eng"):  
  38.     """Applies tesseract to filename; or, if image is incompatible and graceful_errors=True, 
  39.     converts to compatible format and then applies tesseract.  Fetches resulting text. 
  40.     If cleanup=True, delete scratch files after operation."""  
  41.     try:  
  42.         try:  
  43.             call_tesseract(filename, scratch_text_name_root, language)  
  44.             text = util.retrieve_text(scratch_text_name_root)  
  45.         except errors.Tesser_General_Exception:  
  46.             if graceful_errors:  
  47.                 im = Image.open(filename)  
  48.                 text = image_to_string(im, cleanup)  
  49.             else:  
  50.                 raise  
  51.     finally:  
  52.         if cleanup:  
  53.             util.perform_cleanup(scratch_image_name, scratch_text_name_root)  
  54.     return text  
  55.       
  56.   
  57. if __name__=='__main__':  
  58.     im = Image.open('phototest.tif')  
  59.     text = image_to_string(im)  
  60.     print text  
  61.     try:  
  62.         text = image_file_to_string('fnord.tif', graceful_errors=False)  
  63.     except errors.Tesser_General_Exception, value:  
  64.         print "fnord.tif is incompatible filetype.  Try graceful_errors=True"  
  65.         print value  
  66.     text = image_file_to_string('fnord.tif', graceful_errors=True)  
  67.     print "fnord.tif contents:", text  
  68.     text = image_file_to_string('fonts_test.png', graceful_errors=True)  
  69.     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")就可以了

你可能感兴趣的:(python)