Programming
PHP OCR Combat: Read text from an image with Tesseract
Optical Character Recognition (OCR) optical character recognition is the process of converting printed text into a digital representation. It has a wide variety of practical applications – from digitally printed books, to the creation of electronic records of receipts, to license plate recognition and even the decoding of image-based verification codes.
Letting Go 2016/01/15
Tesseract is an open source project that enables OCR. You can run this project on *nix Systems, MAC systems and Windows systems, but with a single library, we can use it in PHP projects. The purpose of this tutorial is to teach you how to use.
installation
Prepare
To make things simple and consistent, we'll use virtual machines (this article uses vagrant) to run the application, which involves installing PHP and nginx, and we'll install tesseract to demonstrate the process separately. If you want to install Tesseract on your existing debian-based system, you can skip the next section-or check the README to get installation instructions on other *nix, Mac systems or Windows.
Configure Vagrant
In order to configure Vagrant to follow this tutorial, complete the following steps. Or you can simply get the code from Github.
Enter the following command to download the Homestead improved Vagrant configuration to a folder named Orc:
git clone https://github.com/Swader/homestead_improved OCR
Add the following code in the Nginx configuration file homestead.yml:
Sites: -Map:homestead.app to :/home/vagrant/code/project/public
Modified to:
Sites: -Map:homestead.app to :/home/vagrant/code/public
Also add in the Hosts file
192.168.10.10 Homestead.app
Installing Tesseract
The next step is to install Tesseract
Because Homestead improved uses Debian, we can use Apt-get to install it after using vagrant ssh to log in to the virtual machine, simply run the following command:
sudo apt-get install TESSERACT-OCR
As mentioned above, there are other operating system tutorials in the README.
test and customize the installation
We will use PHP wrapper, but we can test tesseract at the command line.
Save this image first Sign.png
In the virtual machine, execute the following command to read the text from the picture
Tesseract Sign.png out
This will create a file in the current folder: OUT.txt There should be a word: CAUTION
Now try Sign2.jpg
Tesseract sign2.jpg out
This time produces the word einbahnstral ' ie. Very close but not correct-although the text in the image is quite clear, it does not recognize the character ß.
In order to get tesseract to read the string normally, we need to install some new language files-in this case, German.
Here is a comprehensive list of available language files, but we download the required files directly:
wget https://tesseract-ocr.googlecode.com/files/tesseract-ocr-3.02.deu.tar.gz
Extract:
Tar zxvf tesseract-ocr-3.02.deu.tar.gz
Then copy the files to the following directory:
/usr/share/tesseract-ocr/tessdata
For example
CP DEU-FRAK.TRAINEDDATA/USR/SHARE/TESSERACT-OCR/TESSDATACP Deu.traineddata/usr/share/tesseract-ocr/tessdata
Now we're going to execute the original command again, but use –l.
Tesseract sign2.jpg out-l Deu
"Deu" is the German ISO 639-3 code.
This time, the text should be Einbahnstraße (correct).
You can use any language by repeating the above procedure.
Configure the application
We will use this library to use Tesseract with PHP.
We will create a minimalist Web application: Users upload images and view the results of OCR processing. We will use Silex microframework to achieve this. Don't worry that you're not familiar with it, the app itself is simple.
Remember that all the code for this tutorial is available on Github.
The first step is to install the dependent files with composer:
Composer require Silex/silex Twig/twig thiagoalessio/tesseract_ocr:dev-master
Then create a three folder:
-Public-uploads-views
We need to upload the form (vi Ews\index.twig):
Ocr
Need a result display page (Views\results.twig)::
Ocr Results
{{text}} ←go back
Now build the Skeleton Silex app (public\index.php):
Register (new Silex\provider\twigserviceprovider (), [ ' twig.path ' = = __dir__. /.. /views ',]); $app [' debug '] = true; $app->get ('/', function () use ($app) { return $app [' Twig ']->render (' Index.twig '); $app->post ('/'); function (Request $request) use ($app) { //TODO}); $app->run ();
If you access this app in a browser, you should be able to see a file upload form. If you are using homestead improved Vagrant, you can access the app via the link below.
http://homestead.app/
The next step is to implement file uploads. Silex makes this work very simple; $request contains a files component that we can use to get any uploaded file, code:
Grab the uploaded file$file = $request->files->get (' upload '); Extract Some information about the uploaded file$info = new Splfileinfo ($file->getclientoriginalname ());//Create A Quasi-random filename$filename = sprintf ('%d.%s ', Time (), $info->getextension ());//Copy the File$file->move (__ dir__. ' /.. /uploads ', $filename);
As you can see, we generate random filenames to reduce file name collisions-but in this app, it's not important how we name the files. Once we have a copy of the file locally, we can generate an instance of the TESSEARCT Library and analyze It:
Instantiate the TESSEARCT library$tesseract = new TESSERACTOCR (__dir__. '/.. /uploads/'. $FILENAME);
OCR is fairly simple to implement on the image, we simply call the method recognize ().
Perform OCR on the uploaded image$text = $tesseract->recognize ();
Finally, we present the results to the results page:
return $app [' Twig ']->render ( ' Results.twig ', [ ' text ' = = $text, ]);
Try it on some pictures and see how it works. If you have difficulty, you can refer to this
A practical example
Let's look at a more practical example of OCR. In this example, we try to find a formatted phone number in the image.
Take a look at the following image and upload it to your app:
The results should be as follows:
: II ' Icustomer Service helplinesbritish Airways Helpline09040 490 541
It does not pick out the body text, which we can expect, because the quality of the picture is too poor. Although the number is recognized, there are some "noises".
In order to extract the relevant information, there are a few things we can do.
You can let tesseract limit its results to a certain set of characters, so we tell it to return only the numeric type of the content code as follows:
$tesseract->setwhitelist (Range (0,9));
But there's a problem with that. It often interprets non-numeric characters as numbers rather than ignoring them. For example, "Bob" may be interpreted as the number "808".
So we use two-step process.
- Try to extract a number string that may be a phone number.
- Each candidate character is evaluated in turn by a library, and is stopped once a valid phone number is found.
In the first step, we can use a basic regular expression. You can use the Google Phone library to determine if a number string is a legitimate phone number.
Note: I have written about the Google Phone library in SitePoint.
Let's add a PHP port to the Google Phone library, modify Composer.json, add:
"giggsey/libphonenumber-for-php": "~7.0"
Don't forget to upgrade:
Composer Update
Now we can write a function, enter as a string, try to extract a legitimate phone number
/** * Parse A string, trying to find a valid telephone number. As soon as it finds a * valid number, it ' ll return it in E1624 format. If it can ' t find any, it ' ll * simply return NULL. * * @param string $text the string to parse * @param string $country _code the and digit country code to Use as a "hint" * @return string | NULL */function findphonenumber ($text, $country _code = ' GB ') {//Get an instance of Google ' s libphonenumber $phoneUtil = \libphonenumber\phonenumberutil::getinstance (); Use a simple regular expression to try and find candidate phone numbers Preg_match_all ('/(\+\d+)? \s* (\ (\d+\))? ( [\s-]?\d+) +/', $text, $matches); Iterate through the matches foreach ($matches as $match) {foreach ($match as $value) {try {//Attemp T to parse the number = $phoneUtil->parse (Trim ($value), $country _code); Just because we parsed it successfully, doesn ' t make it vald-so check it if ($phoneUtil->isvalidNumber ()) {//We ' ve found a telephone number. Format using->format, and Exit return $phoneUtil (, \libphonenumber\phonenumberformat::e164); }} catch (\libphonenumber\numberparseexception $e) {//Ignore silently; getting here simply means we fou nd something that isn ' t a phone number}}} return null;
Hopefully the comment will explain what this function is doing. Note that if the library does not parse a valid phone number from a string, it throws an exception. This is not a problem; we ignore it directly and continue with the next candidate character.
If we find a phone number, we return it in the form of an. This provides an internationalized number that we can use to call or send SMS.
Now we can use the following:
$text = $tesseract->recognize (); = Findphonenumber ($text, ' GB ');
We need to provide a hint to Google's phone bank to indicate which country this number is. You can also change to your own country.
We pack all of this in a new route:
$app->post ('/identify-telephone-number ', function (Request $request) use ($app) { //Grab the uploaded file $ File = $request->files->get (' upload '); Extract Some information about the uploaded file $info = new Splfileinfo ($file->getclientoriginalname ()); Create a quasi-random filename $filename = sprintf ('%d.%s ', Time (), $info->getextension ()); Copy the file $file->move (__dir__. ' /.. /uploads ', $filename); Instantiate the TESSEARCT library $tesseract = new TESSERACTOCR (__dir__. '/.. /uploads/'. $filename); Perform OCR on the uploaded image $text = $tesseract->recognize (); = Findphonenumber ($text, ' GB '); Return $app->json ( [ ' number ' = , ] );
We now have the basics of a simple API-that is, JSON response-we can use it as a backend for a simple mobile app that can be used to add contacts and make calls from a picture.
Summary
There are many applications for OCR-and it's easy to integrate into your application (more than you expect). In this article, we installed the Open source OCR package and used a wrapper library to integrate it into a very simple PHP application. We just touched on the surface of all the possibilities and hopefully this will give you some idea of how to use OCR in your own application.
From: http://www.codeceo.com/article/php-ocr-tesseract-get-text.html