base64google-cloud-visiongoogle-product-search

Google cloud vision - product search return null for base64 image


I'm implementing google cloud vision for the first time. Successfully created product set, products and assigned images to products. When I try to execute product search sending base64 encoded image the result is always null. But when I try it with image from google cloud storage it's working. Any idea why it's not working?

    $productSearchClient = new ProductSearchClient();
    $productSetPath = $productSearchClient->productSetName(config('web.google_vision.project_id'), config('web.google_vision.location'), 2);

    # product search specific parameters
    $productSearchParams = (new ProductSearchParams())
        ->setProductSet($productSetPath)
        ->setProductCategories(['general-v1']);

    # search products similar to the image
    $imageAnnotatorClient = new ImageAnnotatorClient(); 
    //$image = 'gs://picfly-bucket/wendys-5.jpeg';
    $image = base64_encode(file_get_contents(public_path('gallery/test/wendy-search.png')));
    $response = $imageAnnotatorClient->productSearch($image, $productSearchParams);
    dd($response->getProductSearchResults());

Solution

  • As per this doc, your code reads a local file and queries the API by including inline the raw image bytes (base64 encoded image) in the request. So, you should not call base64_encode() explicitly. The Vision library does the base64 encoding by default. You just need to call fopen() to open your local image data. The code would look like:

    $image = fopen('gallery/test/wendy-search.png', 'r');
    $response = $imageAnnotatorClient->productSearch($image, $productSearchParams);