ahmadmayahi/php-google-vision
Composer 安装命令:
composer require ahmadmayahi/php-google-vision
包简介
An elegant wrapper around Google Vision
关键字:
README 文档
README
Requires PHP 8.0+
For feedback, please contact me.
This package provides an elegant wrapper around Google Vision API and more.
It's an effort to make Google Vision API easy and fun to work with.
Contents
- Installation
- Creating Google Service Account
- Configuration
- Original Responses
- Integration with Laravel
- Image Text Detection (OCR)
- Crop Hints Detection
- Face Detection
- Detect Image Properties
- Label Detection
- Landmark Detection
- Logo Detection
- Object Localizer
- Web Detection
Installation
You may install the package via composer:
composer require ahmadmayahi/php-google-vision
Creating Google Service Account
First, you must create a Google service account and setup the configuration object.
Configuration
use AhmadMayahi\Vision\Config; $config = (new Config()) // Required: path to your google service account. ->setCredentials('path/to/google-service-account.json') // Optional: defaults to `sys_get_temp_dir()` ->setTempDirPath('/my/tmp');
Original Responses
All the features come with getOriginalResponse() method which returns the original response that's returned by PHP Google Vision Package:
use AhmadMayahi\Vision\Vision; $response = Vision::init($config) ->file('/path/to/input/file.jpg') ->faceDetection() ->getOriginalResponse();
The file() method accepts the following types:
- Local file path:
path/to/your/file. - Google Storage path:
gs://path/to/file. - File resource, such as
fopen(). SplFileInfo.SplFileObject.
Integration with Laravel
Open up the AppServiceProvider and add the following lines:
use AhmadMayahi\Vision\Vision; use AhmadMayahi\Vision\Config; public function register() { $this->app->singleton(Vision::class, function ($app) { $config = (new Config()) ->setCredentials(config('vision.service_account_path')); return Vision::init($config); }); }
Using Dependency Injection:
use AhmadMayahi\Vision\Vision; use Illuminate\Http\Request; class FaceDetectionController { public function detect(Request $request, Vision $vision) { $vision = $vision ->file($request->face_file->path()) ->faceDetection() ->detect(); // ... } }
You may also resolve the object using the app helper as follows:
use AhmadMayahi\Vision\Vision; /** @var Vision $vision */ $vision = app(Vision::class); $result = $vision ->file('path/to/file') ->faceDetection() ->detect(); // ...
Image Text Detection (OCR)
Get plain text
The plain() method returns an object of type AhmadMayahi\Vision\Data\ImageText.
use AhmadMayahi\Vision\Vision; $response = Vision::init($config) ->file('/path/to/input/image.jpg') ->imageTextDetection() ->plain(); if ($response) { $response->locale; // locale, for example "en" $response->text; // Image text }
Both plain() and document() methods return null if no text will be detected.
You may also get the plain text using __toString() magic method:
echo $response;
Get Document
The getDocument returns an object of type AhmadMayahi\Vision\Data\ImageText.
use AhmadMayahi\Vision\Vision; $response = Vision::init($config) ->file('/path/to/input/image.jpg') ->imageTextDetection() ->document(); if ($response) { $response->locale; // locale, for example "en" for English $response->text; // Image text }
The difference between
plain()anddocuemnt()is that the first one only retrieves the plain text (no bullets, signs, etc...), whereas the latter one tries to retrieve the entire document (including bullets, symbols, etc...).
Handwriting
The document method can also be used to detect handwriting in an image.
PDF and Tiff
Coming soon.
Crop Hints Detection
Crop Hints suggests vertices for a crop region on an image.
Detect Crop Hints
use AhmadMayahi\Vision\Vision; $response = Vision::init($config) ->file('/path/to/input/image.jpg') ->cropHintsDetection() ->detect(); /** @var \AhmadMayahi\Vision\Data\CropHints $item */ foreach ($response as $item) { $item->bounds; // An array of \AhmadMayahi\Vision\Data\Vertex $item->confidence; $item->importanceFraction; }
Draw box around hints
You may use the drawBoxAroundHints method as follows:
use AhmadMayahi\Vision\Vision; use AhmadMayahi\Vision\Enums\Color; Vision::init($config) ->file('/path/to/input/image.jpg') ->cropHintsDetection() ->drawBoxAroundHints(Color::GREEN) ->toJpeg('out.jpg')
Crop Image
You may export the cropped image as follows:
use AhmadMayahi\Vision\Vision; $response = Vision::init($config) ->file('/path/to/input/image.jpg') ->cropHintsDetection() ->crop() ->toJpeg('out.jpg');
Original Image:
Cropped Image:
Face Detection
Face Detection detects multiple faces within an image along with the associated key facial attributes such as emotional state or wearing headwear.
The detect method returns a Generator of AhmadMayahi\Vision\Data\Face:
use AhmadMayahi\Vision\Vision; $vision = Vision::init($config); $faces = $vision ->file('/path/to/image.jpg') ->faceDetection() ->detect(); echo count($faces). ' faces found'; /** @var \AhmadMayahi\Vision\Data\Face $faceData */ foreach ($faces as $faceData) { $faceData->anger; // for example: POSSIBLE $faceData->isAngry(); // boolean $faceData->surprise; $faceData->isSurprised(); $faceData->joy; $faceData->isJoyful(); $faceData->blurred; $faceData->isBlurred(); $faceData->headwear; $faceData->isHeadwear(); $faceData->landmarking; $faceData->underExposed; $faceData->detectionConfidence; $faceData->bounds; }
The anger, surprise and joy etc... return likelihoods ratings which are expressed as six different values:
UNKNOWN.VERY_UNLIKELY.UNLIKELY.POSSIBLE.LIKELY.VERY_LIKELY.
See Likelihood.
You may get the results as array:
$faces = $vision ->file('/path/to/image.jpg') ->faceDetection() ->asArray();
Or as JSON:
$faces = $vision ->file('/path/to/image.jpg') ->faceDetection() ->asJson();
asArrayandasJsonis supported in all the features that returnGenerator.
Draw box around faces
use AhmadMayahi\Vision\Vision; use AhmadMayahi\Vision\Enums\Color; $analyzer = Vision::init($config) ->file('/path/to/input/image.jpg') ->faceDetection() ->drawBoxAroundFaces(Color::MAGENTA) // Alternatively, you may use `toPng`, `toGif`, `toBmp` methods. ->toJpeg('faces.jpg');
All the drawing methods return an object of type
AhmadMayahi\Vision\Support\Image.
This feature doesn't support Google Storage yet.
Image Properties Detection
The Image Properties feature detects general attributes of the image, such as dominant color.
The detect method returns a Generator of AhmadMayahi\Vision\Data\ImageProperties:
use AhmadMayahi\Vision\Vision; $properties = Vision::init($config) ->file('/path/to/input/image.jpg') ->imagePropertiesDetection() ->detect(); /** @var \AhmadMayahi\Vision\Data\ImageProperties $item */ foreach ($properties as $item) { $item->red; $item->blue; $item->green; $item->pixelFraction; }
Landmark Detection
Landmark Detection detects popular natural and human-made structures within an image.
use AhmadMayahi\Vision\Vision; $landmarks = Vision::init($config) ->file('/path/to/baghdad.jpg') ->landmarkDetection() ->detect(); /** @var \AhmadMayahi\Vision\Data\Landmark $landmark */ foreach ($landmarks as $landmark) { $landmark->name; // An array containing the detected locations in latitude/longitude format. $landmark->locations; }
Safe Search Detection
SafeSearch Detection detects explicit content such as adult content or violent content within an image.
The detect method returns an object of type AhmadMayahi\Vision\Data\SafeSearch:
use AhmadMayahi\Vision\Vision; $result = Vision::init($config) ->file('/path/to/input/image.jpg') ->safeSearchDetection() ->detect(); $result->adult; $result->isAdult(); // boolean $result->medical; $result->isMedical(); // boolean $result->violence; $result->isViolence(); // boolean $result->racy; $result->isRacy(); // boolean $result->spoof; $result->isSpoof(); // boolean
Label Detection
Detect and extract information about entities in an image, across a broad group of categories.
The detect method returns an a Generator of labels:
use AhmadMayahi\Vision\Vision; $labels = Vision::init($config) ->file('/path/to/input/image.jpg') ->labelDetection() ->detect();
Logo Detection
Detect and extract information about entities in an image, across a broad group of categories.
The detect method returns an Generator of logos:
use AhmadMayahi\Vision\Vision; $labels = Vision::init($config) ->file('/path/to/input/image.jpg') ->logoDetection() ->detect();
Object Localizer
Object Localizer detects and extract multiple objects in an image with Object Localization.
Detect Objects
The detect method returns a Generator of AhmadMayahi\Vision\Data\LocalizedObjectData:
use AhmadMayahi\Vision\Vision; $objects = Vision::init($config) ->file('/path/to/image.jpg') ->objectLocalizer() ->detect(); /** @var AhmadMayahi\Vision\Data\LocalizedObject $obj */ foreach ($objects as $obj) { $obj->name; $obj->languageCode; $obj->mid; $obj->normalizedVertices; $obj->score; }
Draw Box Around Objects
You may draw box around objects using the drawBoxAroundObjects method:
use AhmadMayahi\Vision\Vision; use AhmadMayahi\Vision\Enums\Color; $objects = Vision::init($config) ->file('/path/to/input/image.jpg') ->objectLocalizer() ->drawBoxAroundObjects() ->boxColor(Color::GREEN) ->toJpeg('out.jpg');
The drawBoxAroundObjects() takes an optionalcallback as a second parameter:
use AhmadMayahi\Vision\Vision; use AhmadMayahi\Vision\Enums\Color; use AhmadMayahi\Vision\Support\Image; use AhmadMayahi\Vision\Data\LocalizedObject; $objects = Vision::init($config) ->file('/path/to/input/image.jpg') ->objectLocalizer() ->drawBoxAroundObjects() ->boxColor(Color::RED) ->callback(function(Image $outputImage, LocalizedObject $object) { // Get GD Image $outputImage->getImage(); // Get object info $object->getName(); }) ->draw();
This feature doesn't support Google Storage yet.
Draw Box Around Objects With Text
You may want to draw box around objects and include the object's text as well:
use AhmadMayahi\Vision\Vision; use AhmadMayahi\Vision\Enums\Color; use AhmadMayahi\Vision\Enums\Font; use AhmadMayahi\Vision\Support\Image; use AhmadMayahi\Vision\Data\LocalizedObject; $objects = Vision::init($config) ->file('/path/to/input/image.jpg') ->objectLocalizer() ->drawBoxAroundObjectsWithText() ->boxColor(Color::GREEN) ->textColor(Color::RED) ->font(Font::OPEN_SANS_BOLD_ITALIC) ->fontSize(12) ->draw() ->toJpeg('output.jpg');
This feature doesn't support Google Storage yet.
Web Detection
Web Detection detects Web references to an image.
use AhmadMayahi\Vision\Vision; use AhmadMayahi\Vision\Enums\Color; use AhmadMayahi\Vision\Enums\Font; use AhmadMayahi\Vision\Support\Image; use AhmadMayahi\Vision\Data\LocalizedObject; $response = Vision::init($config) ->file('/path/to/input/image.jpg') ->webDetection() ->detect(); $response->fullMatchingImages; $response->partialMatchingImages; $response->bestGuessLabels;; $response->pagesWithMatchingImages; $response->visuallySimilarImages; $response->webEntities;
The detect method returns either an object of tupe AhmadMayahi\Vision\Data\WebData or null value.
Testing
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
Credits
License
The MIT License (MIT). Please see License File for more information.
ahmadmayahi/php-google-vision 适用场景与选型建议
ahmadmayahi/php-google-vision 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 468 次下载、GitHub Stars 达 27, 最近一次更新时间为 2021 年 09 月 20 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「OCR」 「ai」 「google vision」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 ahmadmayahi/php-google-vision 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 ahmadmayahi/php-google-vision 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 ahmadmayahi/php-google-vision 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Google Vision Api Bundle
Laravel OCR & Document Data Extractor - A powerful OCR and document parsing engine for Laravel
Magento 2 Social Login extension is designed for quick login to your Magento 2 store without procesing complex register steps
PHP Client for Kakao Vision API
The Best Image Ocr SDK For BAT.
The Best Image Ocr SDK For BAT.
统计信息
- 总下载量: 468
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 27
- 点击次数: 19
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2021-09-20





