douding7189 2019-02-14 05:38
浏览 112
已采纳

Google Cloud Vision / PHP - 使用标签和安全搜索检测发出单一请求

On google cloud vision you get charged per request. If you do a "Label Detection" you get a free "Safe Search" but it has to be rolled into the same request. I have working code for both the Label Detection and the Safe Search detection but I am not sure how to combine the two into one request.

Someone had answered this question in Python but not sure how to translate it in PHP.

How to call for "Label Detection" and "Safe Search Detection" at a time on Google Cloud Vision API

Does anyone know how I could call them in PHP? Any insight would be appreciated. Thanks.


# 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);
    }
} 
######### Safe Search would look as follows
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
";
    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 "
";
$path = 'images/5.jpg.6f23b929dcc008f3bc394b0b6b0c6e5e.jpg';
detect_safe_search($path);
  • 写回答

1条回答 默认 最新

  • duanmeng1862 2019-02-14 14:47
    关注

    Use 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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?