使用Imagga服务的PHP / cURL图像识别集成

时间:2018-11-19 12:34:38

标签: php json curl

我正在尝试使用cURL和PHP从Imagga图像识别(人工智能服务,新的V2版本)中获取图像标签。

我设法获得了有效的回复,cURL正文回复如下所示:

{
"result":{
    "tags":[
        {"confidence":100,"tag":{"en":"pink"}},
        {"confidence":92.6405181884766,"tag":{"en":"petal"}},
        {"confidence":69.8676071166992,"tag":{"en":"flower"}},
        {"confidence":54.1640663146973,"tag":{"en":"bloom"}}
        ]
        }
,"status":{"text":"","type":"success"}
}

我试图收集标签,但是遇到了麻烦。

 $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 confidence is above 60, than echo it, do something with it...
 }

如果标签置信度高于60,如何回显某些标签?

1 个答案:

答案 0 :(得分:1)

只使用foreach

<?php
$body = '{
"result":{
    "tags":[
        {"confidence":100,"tag":{"en":"pink"}},
        {"confidence":92.6405181884766,"tag":{"en":"petal"}},
        {"confidence":69.8676071166992,"tag":{"en":"flower"}},
        {"confidence":54.1640663146973,"tag":{"en":"bloom"}}
        ]
        }
,"status":{"text":"","type":"success"}
}';


$resp = json_decode( $body, true );

foreach ($resp['result']['tags'] ?? $tags as $tag) {
    if (
        ($confidence = $tag['confidence'] ?? null) 
        && $confidence >= 60 
        && ($tagName = $tag['tag']['en'] ?? null)
    ) {
        echo $tagName . "\r\n";
    }
}