LoginSignup
0
0

More than 5 years have passed since last update.

TensorFlowを使ってDir en greyの顔分類器を作ってみた - ③画像収集編

Last updated at Posted at 2017-05-31

はじめに

画像を収集しますが、既に自力で100枚以上の画像を集められる方はここをすっ飛ばしてください。

API

紹介

APIキーの取得

Microsoftアカウントを作成してください。または、FacebookやGithubアカウントがあればそれからOAuthでログインできます。
※ ページ内部がとても迷うので心の余裕があるときが望ましいです。

プログラム(適当に書いていて恥ずかしいので凝視しないでください)

image_crawler.php
<?php

for ($j = 0; $j < 9; $j++) {
    $offset = $j * 150;

    if ($offset == 0) {
        $url = 'https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=direngrey+shinya&count=150';
    } else {
        $url = 'https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=direngrey+shinya&count=150&offset=' . $offset;
    }

    $curl = curl_init();

    curl_setopt_array(
        $curl,
        array(
            CURLOPT_URL => $url,
            CURLOPT_HTTPHEADER => array(
                'Content-Type: multipart/form-data',
                'Ocp-Apim-Subscription-Key: {APIキー}'
              ),
              CURLOPT_POST => true,
              CURLOPT_POSTFIELDS  => true,
              CURLOPT_RETURNTRANSFER => true,
              CURLOPT_BINARYTRANSFER => true,
        )
    );

    $response = curl_exec($curl);
    $result = json_decode($response);

    for ($i = 0; $i < 150; $i++) {
        $imageUrl = $result->value[$i]->thumbnailUrl;

        if ($j == 0) {
            $j = 1;
        }

        $filePath = '{保存先ディレクトリ}' . $j * ($i + 1) . '.jpg';

        curl_setopt_array(
            $curl,
            array(
                CURLOPT_URL => $imageUrl,
                CURLOPT_HTTPGET => true,
                CURLOPT_HTTPHEADER => array(
                    'Content-Type: multipart/form-data',
                ),
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_BINARYTRANSFER => true,
            )
        );

        $response = curl_exec($curl);
        file_put_contents($filePath, $response);
    }

    curl_close($curl);
}

実行

php image_crawler.php

補足と言い訳

  • file_get_contentsではなくcurlを使って2回も行っているのは、プロキシ的に接続が上手くいかないからです。
  • 同じ画像がたくさん落ちてくるので、大変ですが手で消してください。
  • 上手く取れずに空のファイルができる場合もあるので、大変ですが手で消してください。
  • MacのFinderからファイル消すにはファイル選択してcommand+delete。
  • 結構上手くOpenCVが読み込めないファイルが多数あるので、事前に多めに画像を用意してください。
  • 検索している人物以外の人がたくさん出てくるので、検索ワードを工夫してください。
  • 日本語の検索クエリはURLエンコードしてください。

全ページリンク

0
0
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
0
0