google vision ocr 爬坑建议

首先安装 google vision shell composer require google/cloud-vision 第一次使用的时候真的遇到的问题很多,文档是英文的,自己慢慢摸索的途中不免进行去百度google搜索 但是搜索出来的结果却不尽人意,可能是搜索方式不太对哈哈~,其实使用蛮简单,因为是别人现成对轮子,只不过使用对时候坑比较多, 所以特别列出以下几点。 1. 身份认证(就这个身份认证我搞了2个小时) 2. $vision->image($img_path) 图片如果传入url的话会抛出异常

身份认证

进入 https://console.cloud.google.com/ 在列表里面找到api与服务选择凭据,创建凭据,选择服务帐号与密钥进行创建,我选择的格式是json 这个就是我们需要的凭据,导出以后放进项目

php require 'vendor/autoload.php';

use google\cloud\vision\visionclient;

$vision = new visionclient( [ 'keyfile' => jsondecode(filegetcontents($keypath), true) ] ); 

 

到这里身份认证就没有问题了,还有其他的方式,可自行研究,文档太高深,说实话不太喜欢阅读。

图片导入以及function选择

在google官方提供的文档当中是这样写的demo

require 'vendor/autoload.php';

use google\cloud\vision\visionclient;

$vision = new visionclient();

// annotate an image, detecting faces.
$image = $vision->image(
    fopen('/data/family_photo.jpg', 'r'),
    ['faces']
);

$annotation = $vision->annotate($image);

// determine if the detected faces have headwear.
foreach ($annotation->faces() as $key => $face) {
    if ($face->hasheadwear()) {
        echo "face $key has headwear.\n";
    }
}

 

 

[‘faces’]features方法是可以多传的,更具需求传入,在最后我列出了所有的features。

这里还存在一个问题,我的图片是url,我尝试使用fopenfilegetcontents`打开一个url,但是被抛出了异常(异常没深究,太高端看不懂,咱也不敢问), 最后是这样成功的,并成功拿到了返回。

[
    'faces',          // corresponds to `face_detection`
    'landmarks',      // corresponds to `landmark_detection`
    'logos',          // corresponds to `logo_detection`
    'labels',         // corresponds to `label_detection`
    'text',           // corresponds to `text_detection`,
    'document',       // corresponds to `document_text_detection`
    'safesearch',     // corresponds to `safe_search_detection`
    'imageproperties',// corresponds to `image_properties`
    'crop',           // corresponds to `crop_hints`
    'web'             // corresponds to `web_detection`
]

 

features

[
    'faces',          // corresponds to `face_detection`
    'landmarks',      // corresponds to `landmark_detection`
    'logos',          // corresponds to `logo_detection`
    'labels',         // corresponds to `label_detection`
    'text',           // corresponds to `text_detection`,
    'document',       // corresponds to `document_text_detection`
    'safesearch',     // corresponds to `safe_search_detection`
    'imageproperties',// corresponds to `image_properties`
    'crop',           // corresponds to `crop_hints`
    'web'             // corresponds to `web_detection`
]

 

 

以上初次使用的坑,见识略薄(也可能是我的理解和使用方式不对),也希望你们在使用的过程中能有所帮助!