2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHPでgoogleサービス「visionAPI」の実行方法

Posted at

vision APIについて

Googleの画像認識APIをPHPで実行する方法です。

概要

事前にgoogleでAPIキーを発行する必要があります。
サービス内容については以下にまとめてあります。
http://vitalify.jp/blog/2017/05/google%E3%81%AE%E7%94%BB%E5%83%8F%E8%AA%8D%E8%AD%98api%E3%80%8Cvisionapi%E3%80%8D%E3%82%92%E4%BD%BF%E3%81%A3%E3%81%A6%E7%94%BB%E5%83%8F%E5%88%A4%E5%AE%9A%E3%82%92%E3%81%97%E3%81%A6%E3%81%BF%E3%81%9F.html

 実行方法

<?php
//リクエストするドメインとキー情報
$domain = "https://vision.googleapis.com";
$apiKey = [発行したapiキー];

//画像をbase64でデコードする
$imgPath = [画像ファイルのパス];
$imgData = file_get_contents($imgPath);
$imgPostData = base64_encode($imgData);

//リクエストボディを指定
$requestBody = json_encode( array(
		"requests" => array(
			array(
				"image" => array(
					"content" => base64_encode( file_get_contents( $imgPath ) ) ,
				),
				//以下は欲しい情報に応じてリクエストする
				"features" => array(
					array(
						"type" => "FACE_DETECTION"
					) ,
					array(
						"type" => "LABEL_DETECTION",
						"maxResults" => 5
					) ,
					array(
						"type" => "SAFE_SEARCH_DETECTION"
					)
				),
			),
		),
	) );


$curl = curl_init();
//上記で記載のURLを指定
curl_setopt($curl, CURLOPT_URL, $domain."/v1/images:annotate?key=".$apiKey);
curl_setopt($curl, CURLOPT_HTTPHEADER, array( "Content-Type: application/json" )) ;
//上記で記載のリクエストbodyを指定
curl_setopt($curl, CURLOPT_POSTFIELDS, $requestBody);
//post形式を指定
curl_setopt($curl, CURLOPT_CUSTOMREQUEST,"POST");

//実行し、結果を変数に格納
$postData =curl_exec($curl);
curl_close($curl);

//表示
var_dump($postData);

<?php } ?>
 

リクエストのjson情報を変えれば、様々な情報を取得可能です。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?