加入收藏 | 设为首页 | 会员中心 | 我要投稿 常州站长网 (https://www.0519zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

PHP OCR实战:用Tesseract从图像中读取文字

发布时间:2016-10-01 19:58:44 所属栏目:PHP教程 来源:站长网
导读:副标题#e# OpticalCharacterRecognition(OCR)即光学字符辨识是把打印文本转换成一个数字表示的过程。它有各种各样的实际应用从数字化印刷书籍、创建收据的电子记录,到车牌识别甚至破解基于图像的验证码。 498)this.width=498;' onmousewheel = 'javascript

结果应该如下:

  1. :ii‘i 
  2. Customer Service Helplines 
  3.  
  4. British Airways Helpline 
  5.  
  6. 09040 490 541 

它没有挑出正文文本,这是我们能料到的,因为图片质量太差。虽然识别了号码但是也有一些“噪声”。

为了提取相关信息,有如下几件事我们可以做。

你可以让Tesseract 把它的结果限制在一定的字符集内,所以我们告诉它只返回数字型的内容代码如下:

  1. $tesseract->setWhitelist(range(0,9)); 

但这样有个问题。它常常把非数字字符解释成数字而非忽略它们。比如“Bob”可能被解释称数字“808”。

所以我们采用两步处理。

  1. 尝试提取可能是电话号码的数字串。

  2. 用一个库轮流评估每一个候选字符,一旦找到一个有效电话号码则停止。

第一步,我们可以用一个基本的正则表达式。可以用谷歌电话库来确定一个数字串是否是合法电话号码。

备注:我已在Sitepoint 写过关于谷歌电话库的内容。

让我们给谷歌电话库添加一个PHP 端口,修改composer.json,添加:

  1. "giggsey/libphonenumber-for-php": "~7.0" 

别忘了升级:

  1. composer update 

现在我们可以写一个函数,输入为一个字符串,尝试提取一个合法的电话号码

  1. /** 
  2. * Parse a string, trying to find a valid telephone number. As soon as it finds a 
  3. * valid number, it'll return it in E1624 format. If it can't find any, it'll 
  4. * simply return NULL. 
  5. * @param  string   $text           The string to parse 
  6. * @param  string   $country_code   The two digit country code to use as a "hint" 
  7. * @return string | NULL 
  8. */ 
  9. function findPhoneNumber($text, $country_code = 'GB') { 
  10.  
  11.   // Get an instance of Google's libphonenumber 
  12.   $phoneUtil = libphonenumberPhoneNumberUtil::getInstance(); 
  13.  
  14.   // Use a simple regular expression to try and find candidate phone numbers 
  15.   preg_match_all('/(+d+)?s*((d+))?([s-]?d+)+/', $text, $matches); 
  16.  
  17.   // Iterate through the matches 
  18.   foreach ($matches as $match) { 
  19.  
  20.     foreach ($match as $value) { 
  21.  
  22.       try { 
  23.  
  24.         // Attempt to parse the number 
  25.         $number = $phoneUtil->parse(trim($value), $country_code);    
  26.  
  27.         // Just because we parsed it successfully, doesn't make it vald - so check it 
  28.         if ($phoneUtil->isValidNumber($number)) { 
  29.  
  30.           // We've found a telephone number. Format using E.164, and exit 
  31.           return $phoneUtil->format($number, libphonenumberPhoneNumberFormat::E164); 
  32.  
  33.         } 
  34.  
  35.       } catch (libphonenumberNumberParseException $e) { 
  36.  
  37.         // Ignore silently; getting here simply means we found something that isn't a phone number 
  38.  
  39.       } 
  40.  
  41.     } 
  42.   } 
  43.  
  44.   return null; 
  45.  

希望注释能解释这个函数在干什么。注意如果这个库没能从字符串中解析出一个合法的电话号码它会抛出一个异常。这不是什么问题;我们直接忽略它并继续下一个候选字符。

如果我们找到一个电话号码,我们以E.164的形式返回它。这提供了一个国际化的号码,我们可以用来打电话或者发送SMS。

(编辑:常州站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读