Search code examples
phpgoogle-apigoogle-api-php-clientgoogle-vision

Google Cloud Vision Client Library (PHP) Image Labels - Number of results?


I am using the upper mentioned library (Google Cloud Vision Client Library v1) in PHP to assign labels to images... so far so good. It all works, except it returns fewer results than on the google test page... as far as I understand it has to do with a "max_results" parameter which defaults to 10, but I am not able to find where/how to set it manually... There was a similar question here on Python and there it was as simple as passing it as a parameter - I have tried many options to do this in PHP, but apparently I am doing something wrong...

Here is a link to the documentation : https://googleapis.github.io/google-cloud-php/#/docs/cloud-vision/v0.19.3/vision/v1/imageannotatorclient?method=labelDetection I am guessing I have to pass it to the "optionalArgs" parameter... but not exactly sure how to do this...

Here is more or less what my code is:

require __DIR__ . '/vendor/autoload.php';

use Google\Cloud\Vision\V1\ImageAnnotatorClient;

$this->client = new ImageAnnotatorClient();
$response = $this->client->labelDetection(...THE IMAGE...);
$labels = $response->getLabelAnnotations();

if ($labels) {
    foreach ($labels as $label) {
        // do something with $label->getDescription()
    }
}

Anyone got an idea how to get more results in the $labels array?


Solution

  • New Method

    Since the other answer I provided seems to be deprecated, I am going to provide a sample that uses the setMaxResults method on the Feature object.

    $imageAnnotatorClient = new ImageAnnotatorClient();
    $gcsImageUri = 'some/image.jpg';
    $source = new ImageSource();
    $source->setGcsImageUri($gcsImageUri);
    $image = new Image();
    $image->setSource($source);
    $type = Feature_Type::FACE_DETECTION;
    $featuresElement = new Feature();
    $featuresElement->setType($type);
    $featuresElement->setMaxResults(100); // SET MAX RESULTS HERE
    $features = [$featuresElement];
    $requestsElement = new AnnotateImageRequest();
    $requestsElement->setImage($image);
    $requestsElement->setFeatures($features);
    $requests = [$requestsElement];
    $imageAnnotatorClient->batchAnnotateImages($requests);
    

    Deprecated Method

    The maxResults value gets specified in the Image constructor

    An example of this code can be found in the source code for the Image object.

     $imageResource = fopen(__DIR__ . '/assets/family-photo.jpg', 'r');
     $image = new Image($imageResource, [
       'FACE_DETECTION',
       'LOGO_DETECTION'
     ], [
         'maxResults' => [
             'FACE_DETECTION' => 1
         ],
         'imageContext' => [
              ....
         ]
       ]
    ]);