ahmadmayahi/php-google-vision

Google Vision的优雅包装器

v1.0.0 2021-11-07 11:40 UTC

This package is auto-updated.

Last update: 2024-09-08 19:06:27 UTC


README

PHP Google Vision

Latest Version on Packagist Total Downloads Tests Check & fix styling
Test Coverage Scrutinizer Code Quality Code Intelligence Status

需要PHP 8.0+

如有反馈,请联系我

此包提供了对Google Vision API及更多功能的优雅包装。

这是为了让Google Vision API易于使用且有趣而努力。

内容

安装

您可以通过composer安装此包

composer require ahmadmayahi/php-google-vision

创建Google服务帐户

首先,您必须创建一个Google服务帐户并设置配置对象。

配置

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');

原始响应

所有功能都带有getOriginalResponse()方法,该方法返回由PHP Google Vision包返回的原始响应。

use AhmadMayahi\Vision\Vision;

$response = Vision::init($config)
    ->file('/path/to/input/file.jpg')
    ->faceDetection()
    ->getOriginalResponse();

file()方法接受以下类型

  • 本地文件路径:path/to/your/file
  • Google存储路径:gs://path/to/file
  • 文件资源,例如fopen()
  • SplFileInfo.
  • SplFileObject.

与Laravel集成

打开AppServiceProvider并添加以下行

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);
    });
}

使用依赖注入

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();
            
        // ...
    }
}

您还可以使用以下方式通过app助手解析对象

use AhmadMayahi\Vision\Vision;

/** @var Vision $vision */
$vision = app(Vision::class);

$result = $vision
    ->file('path/to/file')
    ->faceDetection()
    ->detect();

// ...

图像文字检测(OCR)

获取纯文本

plain()方法返回类型为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
}

plain()document()方法在没有检测到文本的情况下返回null

您还可以使用__toString()魔术方法获取纯文本

echo $response;

获取文档

getDocument返回类型为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
}

plain()docuemnt()之间的区别在于前者仅检索纯文本(无项目符号、符号等),而后者尝试检索整个文档(包括项目符号、符号等)。

手写识别

还可以使用document方法来检测图像中的手写。

PDF和Tiff

即将推出。

裁剪提示检测

裁剪提示建议图像裁剪区域的顶点。

检测裁剪提示

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;    
}

在提示周围画框

您可以使用以下方式使用drawBoxAroundHints方法

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')

Draw box around hints

裁剪图像

您可以使用以下方式导出裁剪后的图像

use AhmadMayahi\Vision\Vision;

$response = Vision::init($config)
    ->file('/path/to/input/image.jpg')
    ->cropHintsDetection()
    ->crop()
    ->toJpeg('out.jpg');

原始图像

Original Image

裁剪图像

Cropped Image

人脸检测

人脸检测检测图像中的多个面部,以及相关的关键面部属性,如情感状态或是否佩戴头饰

detect方法返回一个Generator,类型为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;
}

《愤怒》、《惊讶》和《快乐》等... 返回可能性评分,用六个不同的值表示

  • 未知.
  • 非常不可能.
  • 不太可能.
  • 可能.
  • 很可能.
  • 非常可能.

请参阅可能性

您可能会以数组的形式获得结果

$faces = $vision
    ->file('/path/to/image.jpg')
    ->faceDetection()
    ->asArray();

或JSON格式

$faces = $vision
    ->file('/path/to/image.jpg')
    ->faceDetection()
    ->asJson();

asArrayasJson支持所有返回Generator的所有功能。

在人脸周围画框

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');

所有绘图方法都返回类型为AhmadMayahi\Vision\Support\Image的对象。

Larry Page and Sergey Brin Faces

此功能目前不支持Google存储。

图像属性检测

《图像属性》功能检测图像的一般属性,例如主色调。

detect方法返回一个AhmadMayahi\Vision\Data\ImagePropertiesGenerator

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;    
}

地标检测

地标检测检测图像中的常见自然和人造结构。

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;
}

安全搜索检测

安全搜索检测检测图像中的成人内容或暴力内容等显式内容。

detect方法返回一个类型为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

标签检测

检测并提取图像中实体信息,涵盖广泛的类别。

detect方法返回一个标签的Generator

use AhmadMayahi\Vision\Vision;

$labels = Vision::init($config)
    ->file('/path/to/input/image.jpg')
    ->labelDetection()
    ->detect();

标志检测

检测并提取图像中实体信息,涵盖广泛的类别。

detect方法返回一个标志的Generator

use AhmadMayahi\Vision\Vision;

$labels = Vision::init($config)
    ->file('/path/to/input/image.jpg')
    ->logoDetection()
    ->detect();

对象定位器

对象定位器使用对象定位检测并提取图像中的多个对象。

检测对象

detect方法返回一个类型为AhmadMayahi\Vision\Data\LocalizedObjectDataGenerator

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;
}

在对象周围画框

您可以使用drawBoxAroundObjects方法在对象周围绘制矩形框。

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');

Larry Page and Sergey Brin faces

drawBoxAroundObjects()将可选的callback作为第二个参数。

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();

此功能目前不支持Google存储。

在对象周围画框并带文字

您可能希望绘制矩形框并包括对象的文本。

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');

Larry Page and Sergey Brin Objects

此功能目前不支持Google存储。

网页检测

网络检测检测图像的网络引用。

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;

detect方法返回类型为AhmadMayahi\Vision\Data\WebData的对象或null值。

测试

composer test

变更日志

请参阅变更日志以了解最近更改的详细信息。

贡献

请参阅贡献指南以获取详细信息。

安全漏洞

请参阅我们的安全策略以了解如何报告安全漏洞。

致谢

许可证

MIT许可证(MIT)。请参阅许可证文件以获取更多信息。