首页 > 解决方案 > Google Cloud Vision / PHP - 使用标签和安全搜索检测发出单个请求

问题描述

在谷歌云视觉上,您按请求收费。如果您进行“标签检测”,您将获得免费的“安全搜索”,但必须将其纳入同一个请求中。我有标签检测和安全搜索检测的工作代码,但我不确定如何将两者组合成一个请求。

有人用 Python 回答了这个问题,但不知道如何用 PHP 翻译它。

如何在 Google Cloud Vision API 上同时调用“标签检测”和“安全搜索检测”

有谁知道我如何用 PHP 调用它们?任何见解将不胜感激。谢谢。


# imports the Google Cloud client library
use Google\Cloud\Vision\V1\ImageAnnotatorClient;

# instantiates a client
$imageAnnotator = new ImageAnnotatorClient();

# the name of the image file to annotate
$fileName = 'images/d4aed5533322946.jpg';

# prepare the image to be annotated
$image = file_get_contents($fileName);

# performs label detection on the image file
$response = $imageAnnotator->labelDetection($image);
$labels = $response->getLabelAnnotations();

if ($labels) {
    echo("Labels:" . PHP_EOL);
    foreach ($labels as $label) {
        echo($label->getDescription() . PHP_EOL);
    }
} 
######### 安全搜索如下所示
function detect_safe_search($path)
{
    $imageAnnotator = new ImageAnnotatorClient();

    # annotate the image
    $image = file_get_contents($path);
    $response = $imageAnnotator->safeSearchDetection($image);
    $safe = $response->getSafeSearchAnnotation();

    $adult = $safe->getAdult();
    $medical = $safe->getMedical();
    $spoof = $safe->getSpoof();
    $violence = $safe->getViolence();
    $racy = $safe->getRacy();

    # names of likelihood from google.cloud.vision.enums
    $likelihoodName = ['UNKNOWN', 'VERY_UNLIKELY', 'UNLIKELY',
    'POSSIBLE','LIKELY', 'VERY_LIKELY'];

echo "Adult $adult\n";
    printf("Adult: %s" . PHP_EOL, $likelihoodName[$adult]);
    printf("Medical: %s" . PHP_EOL, $likelihoodName[$medical]);
    printf("Spoof: %s" . PHP_EOL, $likelihoodName[$spoof]);
    printf("Violence: %s" . PHP_EOL, $likelihoodName[$violence]);
    printf("Racy: %s" . PHP_EOL, $likelihoodName[$racy]);

    $imageAnnotator->close();
}

$path = 'images/d4aed5533322946.jpg';
detect_safe_search($path);

echo "\n";
$path = 'images/5.jpg.6f23b929dcc008f3bc394b0b6b0c6e5e.jpg';
detect_safe_search($path);

标签: phpgoogle-apigoogle-cloud-platformgoogle-cloud-vision

解决方案


使用ImageAnnotatorClient::annotateImage

use Google\Cloud\Vision\V1\Feature\Type;
$res = $v->annotateImage(file_get_contents($fileName), [
    Type::LABEL_DETECTION,
    Type::SAFE_SEARCH_DETECTION
]);

$labels = $res->getLabelAnnotations();
$safeSearch = $res->getSafeSearchAnnotation();

推荐阅读