我在https://cloud.google.com/vision/docs/detecting-labels#vision-label-detection-protocol中编写协议部分时输入了所有必填字段,因为我在下面编写了我的代码。但是,它仍然会返回400错误。
<?php
if(!isset($googleapikey)){
include('settings.php');
}
function vision($query){
global $googleapikey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://vision.googleapis.com/v1/images:annotate?key='.$googleapikey);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
$result = curl_exec ($ch);
curl_close ($ch);
return $result;
}
$vdata = array();
$vdata['requests'][0]['image']['source']['imageUri'] = 'https://cloud.google.com/vision/docs/images/ferris-wheel.jpg';
$vdata['requests'][0]['features'][0]['type'] = 'LABEL_DETECTION';
echo vision(json_encode($vdata));
?>
答案 0 :(得分:3)
您对Cloud Vision API的请求中唯一的错误是您没有设置HTTP标头字段 Content-type:application / json ,因为您没有将其分配给正确的变量(您指向$curl
而不是$ch
):
// Insread of this:
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
// Use this:
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
运行旧代码时显示的错误如下所示,表明查询未将内容数据理解为JSON。
Cannot bind query parameter. Field '{\"requests\":[{\"image\":{\"source\":{\"imageU ri\":\"https://cloud' could not be found in request message.
作为旁注,请允许我向您推荐Client Libraries for Cloud Vision API,其中包含一些nice documentation,并且可以让您在使用Google云平台中的某些API从脚本中轻松生活。在这种情况下,您不需要强制执行curl
命令,并且可以使用非常简单(且易于理解)的代码实现相同的结果,例如:
<?php
require __DIR__ . '/vendor/autoload.php';
use Google\Cloud\Vision\VisionClient;
$projectId = '<YOUR_PROJECT_ID>';
$vision = new VisionClient([
'projectId' => $projectId
]);
$fileName = 'https://cloud.google.com/vision/docs/images/ferris-wheel.jpg';
$image = $vision->image(file_get_contents($fileName), ['LABEL_DETECTION']);
$labels = $vision->annotate($image)->labels();
echo "Labels:\n";
foreach ($labels as $label) {
echo $label->description() . "\n";
}
?>