[라라벨7] ocr
구글 비전 api로 ocr 예제 구현했당.
(추가)
실제로 내가 사용한 코드는 이보다 사실 훨씬 짧다.
왜냐하면 메뉴얼페이지에 나오는대로 다시 만들었기 때문이지.
메뉴얼대로 하면
$image = file_get_contents(storage_path($path));
$response = $imageAnnotator->textDetection($image);
$texts = $response->getTextAnnotations();
foreach ($texts as $text) {
$result .= $text->getDescription() . PHP_EOL;
}
저게 다다.
돌아오긴 했지만 어찌됐던 내가 원하는대로 맘껏 코딩할 수 있어서 즐거웠던 ocr이었다.
아참참.
구글 ocr 제한이 있는데, 이미지 크기는 20MB, JSON 10MB, 한번에 최대 이미지 전송수는 16개로 제한되어있다.
얘네가 base64코딩 방식을 이용하는데, 보통 원본 이미지보다 37%정도 크기가 커져서 JSON 크기 용량 넘기기가 쉽상이다. (주의하랬음 메뉴얼에서)
여튼 한번 ocr 적용해보자!
참고 사이트 : oakml.com/ocr-with-laravel-and-google-cloud-vision/
OCR with Laravel and Google Cloud Vision. | Oakml
In this tutorial, I will show you how to easily read text from images directly from your Laravel application. We will be making use of Google’s Cloud Vision API. This robust API allows us to perform other forms of image analysis that I will not cover in
oakml.com
위에 사이트에서 하란대로 했더니... 안됐다.
왜냐하면 파일 업로드부분이 있다고 업로드 되는건 아니니께...
그래서
//if ($request->file('image')) {
//convert image to base64
// $image = base64_encode(file_get_contents($request->file('image')));
$image = base64_encode(file_get_contents('C:\Users\Downloads\제목 없음.png'));
//Sending image for OCR server
$request = new AnnotateImageRequest();
$request->setImage($image);
$request->setFeature("TEXT_DETECTION");
$gcvRequest = new GoogleCloudVision([$request], env('GOOGLE_CLOUD_KEY'));
//Send Request to check image OCR or not through annotate
$response = $gcvRequest->annotate();
echo json_encode(["description" => $response->responses[0]->textAnnotations[0]->description]);
// }
제일 위쪽에 request->file로 이미지 체크하는 부분이랑 file_get_contents부분에서 절대 주소로 줬다.
그랬더니 글쎄에~ 한글도 잘된당 오호호호호홋
이렇게 된 이상 입력폼은 그냥 폼일뿐인게 됐지만, 예제코드로 돌려보기에는 딱이었당.
이제 회사 시스템이랑 연결해야겠지.......
혹시 몰라서 원문 카피 함.
In this tutorial, I will show you how to easily read text from images directly from your Laravel application. We will be making use of Google’s Cloud Vision API. This robust API allows us to perform other forms of image analysis that I will not cover in this post.
Everyone wondered how you could read text from an image? Maybe you’re building a traffic application where you need to read plate numbers from snapshots of cars or something as simple as extracting text from snapshots of PDF files.
So let’s start our tutorial with below steps:
Step 1: Create an account with Google cloud console and it’s API.
An account with Google and a Google cloud console project and it’s API. So you can Create and Managing Projects to learn how to set up a Google cloud console project. Make sure to enable the vision API for your project. Click Before you begin to see how.
A Using API Keys for your Google cloud console project. Click Using API Keys to see how to get your API key.
Step 2: Install a composer in your Project.
So open your terminal and runs the below code:
composer require wapnen/google-cloud-vision-php
After running the command you have to open .env file in your project and put the below code.
GOOGLE_CLOUD_KEY= your api key
Now running your server so open your terminal and put below code.
php artisan serve
Step 3: Create a Controller and web routes
In this step, we have to create a controller file in your local directory. open your terminal and put below code.
php artisan make:controller OcrController
Now open your routes file routes/web.php and put the below code.
Route::get('/ocr', 'OcrController@displayForm'); Route::post('/ocr', 'OcrController@ocrImage');
So we have to create two methods displayForm & ocrImage.
- displayForm => This method to show the upload form
- ocrImage => This method used with the help of upload image to check image OCR or not.
So open your Controller file OcrController.php and put the below code.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use GoogleCloudVision\GoogleCloudVision; use GoogleCloudVision\Request\AnnotateImageRequest; class OcrController extends Controller{ public function displayForm(){ return view('ocr'); } public function ocrImage(Request $request){ if($request->file('image')){ //convert image to base64 $image = base64_encode(file_get_contents($request->file('image'))); //Sending image for OCR server $request = new AnnotateImageRequest(); $request->setImage($image); $request->setFeature("TEXT_DETECTION"); $gcvRequest = new GoogleCloudVision([$request], env('GOOGLE_CLOUD_KEY')); //Send Request to check image OCR or not through annotate $response = $gcvRequest->annotate(); echo json_encode(["description" => $response->responses[0]->textAnnotations[0]->description]); } } }
Now let me explain this tutorial main part. The methods of code above create a single AnnotateImageRequest() object. the setImage() function takes a base64encoded image string as a parameter. This is the image to be annotated. the setFeature() function sets the type of Google Cloud Vision API detection to perform on the image. Since we are performing OCR, we only need to set the TEXT_DETECTION feature. You can set as many features as you want by calling the setFeature() function on the AnnotateImageRequest() and passing the corresponding feature. Check the Google cloud vision API reference for available features.
Now, Our second The GoogleCloudVision() object takes an array of AnnotateImageRequest() objects as the first parameter and your API key as a second parameter. Finally, we called the annotate() function to send the image to google cloud where image checks the OCR.
Step 4: Create a blade file
In this part, we have to create a blade file where it will use to upload an image and save it ocr.blade.php, so create a file and put the below code.
@extends('layouts.app') @section('content') <div class="container"> <div class="row justify-content-center"> <div class="col-md-8"> <div class="card"> <div class="card-header">{{ __('Optical Character Recognition | Image OCR') }}</div> <div class="card-body"> <form role="form" method="POST" action="/ocr" enctype="multipart/form-data"> @csrf <div class="form-group row"> <label for="email" class="col-sm-4 col-form-label text-md-right">{{ __('Upload image') }}</label> <div class="col-md-6"> <input id="image" type="file" class="form-control{{ $errors->has('image') ? ' is-invalid' : '' }}" name="image" value="{{ old('image') }}" required autofocus> @if ($errors->has('image')) <span class="invalid-feedback"> <strong>{{ $errors->first('image') }}</strong> </span> @endif </div> </div> <div class="form-group row mb-0"> <div class="col-md-8 offset-md-4"> <button type="submit" class="btn btn-primary"> {{ __('Submit') }} </button> </div> </div> </form> </div> </div> </div> </div> </div> @endsection
Here the image to upload:
Upload Image to check:
Upload an image containing text and submit. Upload image with text to check OCR or not. If you have don’t image with text so download images here:
Now you have to open your browser and put below URL: