2017年2月28日火曜日

[Python3] OpenCV3 for Linux/Mac をインストールする

Anaconda を利用している場合、conda コマンド使用して簡単にインストールすることができます。

1) opencv3 パッケージを検索します。
$ anaconda search -t conda opencv3
Using Anaconda API: https://api.anaconda.org
Run 'anaconda show <USER/PACKAGE>' to get more details:
Packages:
     Name                      |  Version | Package Types   | Platforms    
     ------------------------- |   ------ | --------------- | ---------------
     Changxu/opencv3           | 3.1.0_dev | conda           | linux-64    
     clg_boar/opencv3          |    3.0.0 | conda           | linux-64, win-64
     janc/opencv3              |    3.1.0 | conda           | osx-64      
                                          : with ffmpeg and opencl
     jlaura/OpenCV3            |    3.0.0 | conda           | linux-64, osx-64
                                          : OpenCV 3.0.0 with the optional contrib modules
     jqscali/opencv3           |    3.0.0 | conda           | linux-64    
     lbernard/opencv3          |    3.1.0 | conda           | linux-64    
     menpo/opencv3             |    3.2.0 | conda           | linux-64, win-32, win-64, osx-64

2) opencv3 パッケージの詳細を表示します。
$ anaconda show menpo/opencv3
Using Anaconda API: https://api.anaconda.org
Name:    opencv3
Summary: 
Access:  public
Package Types:  conda
Versions:
   + 3.1.0
   + 3.2.0

To install this package with conda run:
     conda install --channel https://conda.anaconda.org/menpo opencv3

3) conda コマンドを使用して opencv3 パッケージをインストールします。
$ conda install --channel https://conda.anaconda.org/menpo opencv3
Fetching package metadata ...........
Solving package specifications: .

Package plan for installation in environment /Users/xxxxx/anaconda:

The following NEW packages will be INSTALLED:

    opencv3: 3.1.0-py35_0   menpo
    tbb:     4.3_20141023-0 menpo

Proceed ([y]/n)? y

tbb-4.3_201410 100% |################################| Time: 0:00:03 496.34 kB/s
opencv3-3.1.0- 100% |################################| Time: 0:01:05 608.20 kB/s

4) 画像が表示されればインストール完了です。
$ python
Python 3.5.2 |Anaconda 4.3.0 (x86_64)| (default, Jul  2 2016, 17:52:12) 
[GCC 4.2.1 Compatible Apple LLVM 4.2 (clang-425.0.28)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>> from matplotlib import pyplot as plt
>>> image = cv2.imread('./1.jpg')
>>> cv2.imshow('test', image)
>>> cv2.waitKey(0)

2017年2月24日金曜日

[Python3] Google Custom Search API の検索結果より画像ファイルをダウンロードする

Google Custom Search API を使用して一つの検索ワードにつき、100イメージをダウンロードできるようになりました。これを繰り返していけば、画像認識を試すための教師データは確保できそう。

# pylint: disable-msg=C0103

"""
Google Custom Search API を Python3 から実行する その3
"""
import sys
import urllib.request
import urllib.parse
import json
import time

apikey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
engineid = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
query = urllib.parse.quote_plus('長澤まさみ', encoding='utf8')

count = 0

for i in range(10):
    start = 1 + (i * 10)
    url = ('https://www.googleapis.com/customsearch/v1?'
           'key=%s&cx=%s&start=%s&imgType=face&searchType=image&q=%s'
          ) % (apikey, engineid, start, query)
    try:
        response = urllib.request.urlopen(url)
        result = json.loads(response.read().decode('utf8'))
        for item in result['items']:
            count += 1
            fname = ('/tmp/%d.jpg') % (count)
            try:
                # 検索結果より画像をダウンロードし、連番のファイル名で保存する
                # リンク切れ等は無視する
                response = urllib.request.urlopen(item['link'])
                with open(fname, 'wb') as fout:
                    fout.write(response.read())
            except urllib.error.HTTPError as httperr:
                pass
            except urllib.error.URLError as urlerr:
                pass
    except urllib.error.HTTPError as httperr:
        print(httperr)
        time.sleep(10)

sys.exit(0)

2017年2月23日木曜日

[Python3] Google Custom Search API で 100件のイメージを取得する

"""
Google Custom Search API を Python3 から実行する その2
"""
import sys
import urllib.request
import urllib.parse
import json
import time

apikey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
engineid = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
query = urllib.parse.quote_plus('長澤まさみ', encoding='utf8')

# 10ページ分、合計100件のイメージを取得する
# 無償で利用できるのは10ページ分のみ
for i in range(10):
    start = 1 + (i * 10)
    url = ('https://www.googleapis.com/customsearch/v1?'
           'key=%s&cx=%s&start=%s&imgType=face&searchType=image&q=%s'
          ) % (apikey, engineid, start, query)
    try:
        response = urllib.request.urlopen(url)
        result = json.loads(response.read().decode('utf8'))
        # 検索結果よりイメージのタイトルとリンクを表示する
        for item in result['items']:
            print(item['title'])
            print(item['link'])
            #print(item['image']['thumbnailLink'])
    except urllib.error.HTTPError as httperr:
        print(httperr)
        time.sleep(10)

sys.exit(0)

2017年2月22日水曜日

[Python3] Google Custom Search API を試す

# pylint: disable-msg=C0103

"""
Google Custom Search API を Python3 から実行する
"""
import sys
import urllib.request
import urllib.parse
import json

apikey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
engineid = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
query = urllib.parse.quote_plus('長澤まさみ', encoding='utf8')

url = ('https://www.googleapis.com/customsearch/v1?'
       'key=%s&cx=%s&searchType=image&q=%s') % (apikey, engineid, query)

try:
    response = urllib.request.urlopen(url)
    result = json.loads(response.read().decode('utf8'))
except urllib.error.HTTPError as httperr:
    print(httperr)
    sys.exit(1)

# 検索結果よりイメージのタイトルとリンクを表示する
for item in result['items']:
    print(item['title'])
    print(item['link'])
    #print(item['image']['thumbnailLink'])

2017年2月21日火曜日

Google Custom Search API 利用の予備知識

Google Custom Search API を利用するためには「API キー」と「検索エンジン ID」が必要です。 「API キー」と「検索エンジン ID」は以下のサイトより取得します。

API キー : Google APIs から Google Custom Search API を有効化して取得
検索エンジンID : Google CSE から取得

Google Custom Search API の呼び出し形式
https://www.googleapis.com/customsearch/v1?key=[API キー]&cx=[検索エンジン ID]&searchType=image&q=UFO

パラメータの詳細はこちらにあります。

無償の範囲では1日100リクエストの利用制限がかけられているため、本格的に利用するには有償化が必要です。

Pricing
https://developers.google.com/custom-search/json-api/v1/overview?hl=ja#pricing