我正在遵循如何从Microsoft Vision API获取图像标记的说明: https://docs.microsoft.com/en-us/azure/cognitive-services/computer-vision/quickstarts/php
我设法得到一个有效的CURL身体响应,如下所示:
{
"tags": [
{
"name": "person",
"confidence": 0.98979085683822632
},
{
"name": "man",
"confidence": 0.94493889808654785
},
{
"name": "outdoor",
"confidence": 0.938492476940155
},
{
"name": "window",
"confidence": 0.89513939619064331
}
]
}
我尝试了foreach
个标签,但我遇到了麻烦。
$response = curl_exec($curl);
$header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$body = substr($response, $header_size);
$header = substr($response, 0, $header_size);
$rows = explode("\n", $header);
$err = curl_error($curl);
curl_close($curl);
$resp = json_decode( $body, true );
if ($err) {echo $err; } else {
// foreach thought tags, and if tag value is above 0.9, than show/echo it, do something with it
}
我无法回复任何标签。我想只显示值大于0.9的标签名称。类似于:如果标签置信度> 0.9,回应它,用它做点什么。
答案 0 :(得分:2)
您可以使用此代码段(将端点和订阅密钥替换为您自己的代码):
<?php
$data = array("url" => "https://raw.githubusercontent.com/Microsoft/Cognitive-Face-Windows/master/Data/detection1.jpg");
$data_string = json_encode($data);
$curl = curl_init('https://<YOUR_SUBSCRIPTION-LOCATION>.api.cognitive.microsoft.com/vision/v1.0/tag');
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($curl, CURLOPT_POST, 1 );
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Ocp-Apim-Subscription-Key: <YOUR-SUBSCRIPTION-KEY>'
));
$response = curl_exec($curl);
if(curl_error($curl)) {
echo 'error:' . curl_error($curl);
}
else {
$json_object = json_decode($response, true);
$tags = $json_object["tags"];
foreach($tags as $key => $value) {
if ($value["confidence"] > 0.5) {
echo "Tag name: ".$value["name"]." Confidence: ".$value["confidence"]."<br />";
}
}
}
curl_close($curl);
?>
输出:
Tag name: person. Confidence: 0.99900645017624
Tag name: building. Confidence: 0.99334067106247
Tag name: outdoor. Confidence: 0.98552924394608
Tag name: woman. Confidence: 0.9338972568512
Tag name: glasses. Confidence: 0.87850379943848
Tag name: wearing. Confidence: 0.86172193288803
Tag name: sunglasses. Confidence: 0.67616695165634