LoginSignup
5
8

More than 5 years have passed since last update.

PythonでGoogle Custom Search APIを使い画像収集してみた

Last updated at Posted at 2018-11-02

Custom SearchとAPIの設定

まず、Custom SearchとAPIの設定を行うのですが、下記のURLを参考にしてみてください。
Custom Search・APIの設定

画像収集実装

images_get.py
import urllib.request
from urllib.parse import quote
import httplib2
import json 
import os
import sys
import requests

API_KEY = "" # 取得したらここに追加
CUSTOM_SEARCH_ENGINE = "" # 取得したらここに追加

# キーワードを指定してください
keywords=["犬","猫"]

# 画像を検索し、URLをimg_urlsに追加
def get_image_url(search_keywords, total_num):
    img_urls = []
    i = 0
    while i < total_num:
        query_img = "https://www.googleapis.com/customsearch/v1?key=" + API_KEY + "&cx=" + CUSTOM_SEARCH_ENGINE + "&num=" + str(10 if(total_num-i)>10 else (total_num-i)) + "&start=" + str(i+1) + "&q=" + quote(search_keywords) + "&searchType=image"
        res = urllib.request.urlopen(query_img)
        data = json.loads(res.read().decode('utf-8'))
        for j in range(len(data["items"])):
            img_urls.append(data["items"][j]["link"])
        i += 10
    return img_urls

# 画像のURLから画像を保存
def get_image(search_keywords, img_urls,j):
    for i in range(len(img_urls)):
        res = requests.get(img_urls[i])
        get_images = res.content
        filename = search_keywords + str(i) + ".jpg"
        with open(filename, 'wb') as f:
            f.write(get_images)

# 実行
for j in range(len(keywords)):
    print(keywords[j])
    img_urls = get_image_url(keywords[j],5) # キーワードごとに取得したい枚数を指定(今回は5)
    get_image(keywords[j], img_urls,j)

これを、画像を入れたいディレクトリで実行してください。
このように画像を取得できます。
犬2.jpg

画像を収集したい時に活用してください。

5
8
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
5
8