Detect Text From Uploaded Image and Base64 string

|
| By Webner

How to Detect Text From Uploaded Image and Base64 string in laravel

Laravel has various packages available to achieve this. I have tried “yk/laravel-ocr” and “alimranahmed/laraocr” but these are not producing accurate results. After that, I used the “AWS sdk” and it proved to be more reliable. To use this package, you need “AWS access key and secret” for which you need to open an account on Amazon Web Services.

Below is the link which can help you to get these Access Keys:
https://docs.aws.amazon.com/general/latest/gr/managing-aws-access-keys.html

Step1 – Installation:
1. To install this package with Composer. Open your composer.json file and add the below line in required object:
“require”: {“aws/aws-sdk-php”: “3.*”}
2. Go to your project location in the terminal and run “composer update” in it.

Step2 – Create Controller:
1. Run the below command:

php artisan make:controller TextDetectionController

2. Paste the below code in the “TextDetectionController” file and replace AWS_Region, AWS_Key and AWS_Secret with your details.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Aws\Rekognition\RekognitionClient;
use Illuminate\Support\Facades\Log;

class TextDetectionController extends Controller
{
	/**
	 * Read text from image
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
	public static function detectText(Request $request){
		Log::info('Enter in text detection function -- '.print_r($request->all(),1));
		$image = request('image');
		if(isset($image)){
		   	$imagePath = $image->getPathName();
			$fp_image = fopen($imagePath, 'r');
			$image = fread($fp_image, filesize($imagePath));
			fclose($fp_image);

			$client = new RekognitionClient([
				'version'     => 'latest',
				'region'      => AWS_Region,
				'credentials' => [
					'key'    => AWS_Key,
					'secret' => AWS_Secret
				]
					
			]);
			
			$data = $client->detectText([
				'Image' => array(
					'Bytes' => $image,
				),
			])['TextDetections'];
			
			$string = '';
			// Make a string of all words which are detected from image
			foreach($data as $item)
			{
				if($item['Type'] === 'WORD')
				{
					$string .= $item['DetectedText'] . ' ';
				}
			}
		}
		return view('upload', compact('string'));
	}			
}
?>

This function will get an image and read the image content with the help of fread function. After that, it passes the image data to dectectText function of RekognitionClient class creating a string from all detected text and return that string to the same view. You can also detect text from the Base64 string of image. For this, replace

$imagePath = $image->getPathName();
$fp_image = fopen($imagePath, 'r');
	$image = fread($fp_image, filesize($imagePath));
	fclose($fp_image);

with

$imagePath = $image;
$content = base64_decode($imagePath);

Step3 – Create a view file “upload.blade.php”:

@extends('layouts.master')
@section('content')
@if(!empty($string))
    <p style="text-align: left;">Detect text is: {{$string}}</p>
@endif
   <div style="padding:10px"><h2>Upload Image</h2>
    <form class="" enctype="multipart/form-data" method="post" action="/textDetection">
        {{csrf_field()}}
        <input type="file" name="image" placeholder="select image">
        <button type="submit">Parse Text</button>
   </form></div>
@endsection

Step4 – Make an entry in web.php

1. Route::get(‘/upload, function () {
return view(‘upload’);
});

2. Route::post(‘/upload, ‘TextDetectionController@detectText’);

Step5 – Run it
This command will start a development server at http://127.0.0.1:8000/.

php artisan serve

Example:
Open http://127.0.0.1:8000/upload page and upload the image from which you want to extract text.

Output:

Leave a Reply

Your email address will not be published. Required fields are marked *