【问题标题】:How to handle efficiently Google Vision API Client Lib response?如何有效处理 Google Vision API Client Lib 响应?
【发布时间】:2018-08-25 12:28:23
【问题描述】:

我是 Google Vision API 客户端库的新手

我正在使用适用于 PHP 的 Vision API Client Lib 来检测图像中的文本,这是我的代码:

<?php
require 'vendor/autoload.php';

use Google\Cloud\Vision\VisionClient;
function object_to_array($object) {
    return (array) $object;
}
$vision = new VisionClient(
['keyFile' => json_decode(file_get_contents("smartcity-credentials.json"), true)]
);
$img = file_get_contents('img2.jpg');
$image=$vision->image($img,['DOCUMENT_TEXT_DETECTION']);
$result=$vision->annotate($image);
$res=object_to_array($result);
var_dump($res);
?>

我只需要使用响应作为数组进行处理,但 $result 返回类似于对象/对象数组的东西(抱歉,我不太了解 OOP/Object)

虽然我将 $result 转换为数组 $res,但如果我使用 foreach 循环

foreach ($res as $key=>$value){
    echo $value;
    echo '<br>';
}

我明白了

可捕获的致命错误:Google\Cloud\Vision\Annotation\Document 类的对象无法转换为字符串

我们如何在上述响应中获取值(检测到的文本)以使用 ?。

【问题讨论】:

    标签: php json google-cloud-platform response google-cloud-vision


    【解决方案1】:

    您应该使用方法 fullText() 和 text() 来访问检测到的文本,如下所示:

    $document = $annotation->fullText();
    $text = $document->text();
    

    请参阅这些类的规范 AnnotationDocument

    【讨论】:

      【解决方案2】:

      您不能将Document 类型的$value 用作echo 的字符串。 使用print_r($annotation); 来查看您甚至得到的回报。 这个document text detection example 看起来很像,注意那里嵌套的foreach 循环。另见documentation:

      use Google\Cloud\Vision\VisionClient;
      
      $vision = new VisionClient();
      $imageResource = fopen(__DIR__.'/assets/the-constitution.jpg', 'r');
      $image = $vision->image($imageResource, ['DOCUMENT_TEXT_DETECTION']);
      
      $annotation = $vision->annotate($image);
      $document = $annotation->fullText();
      
      $info = $document->info();
      $pages = $document->pages();
      $text = $document->text();
      

      这里还有更多examples;特别是detect_document_text.php

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-10-01
        • 1970-01-01
        • 2022-01-20
        • 2018-07-15
        • 1970-01-01
        • 2017-08-23
        • 2019-04-03
        • 1970-01-01
        相关资源
        最近更新 更多