25
25

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.

docomoの文字認識APIを使って画像から文字を抽出

Last updated at Posted at 2016-02-13

#やりたいこと
docomoのAPIを使って画像から文字を抽出したい。

追記(2016/02/16)
GitHubにプログラムをアップしました。→ source

#事前準備

#認識する画像ファイル (test.jpg)
test.jpg

#開発環境

  • python 2.7系

#プログラム

characterRecognition.py
#coding: utf-8
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
import urllib2
import json
import time 
import urllib
import re
import sys

#画像データを投げて、画像のIDをjson形式で取得 (情景画像認識要求)
def getImageID(fname):
    register_openers()
    url = 'https://api.apigw.smt.docomo.ne.jp/characterRecognition/v1/document?APIKEY=(API keyを入力して下さい)'
    
    f = open(fname, 'r')

    datagen, headers = multipart_encode({"image": f, 'lang': 'jpn'})
    request = urllib2.Request(url,datagen, headers)
    response = urllib2.urlopen(request)
    
    res_dat = response.read()
    return json.loads(res_dat)['job']['@id'] #画像のIDを返す

#取得したjsonから単語だけを取り出す。
def makeWordList(result):
    
    word_list = []
    count  = int(result['lines']['@count'])

    for i in range(count):
        word = result['lines']['line'][i]['@text']
        word_list.append(word)

    return word_list

#情景画像認識結果取得
def getWordList(img_id):

    register_openers()
    url = 'https://api.apigw.smt.docomo.ne.jp/characterRecognition/v1/document/' + img_id + '?APIKEY=(API keyを入力して下さい)'
    
    request = urllib2.Request(url)
    
    recog_result = {}
    for i in range(5):
        response = urllib2.urlopen(request)
        res_dat = response.read()
        
        recog_result = json.loads(res_dat)
        
        status = recog_result['job']['@status']
        
        if status == 'queue':
            print '受付中...'
        elif status == 'process':
            print '認識処理中...'
        elif status == 'success':
            print '認識成功' #, recog_result
            word_list = makeWordList(recog_result)
            return word_list
        elif status == 'failure':
            print '認識失敗'
            return None

        time.sleep(3) #ちょっと待つ



if __name__ == '__main__':
    
    #画像IDを取得
    img_id = getImageID(sys.argv[1])
    
    #単語リストを取得
    word_list = getWordList(img_id)
    
    #認識した文字列を表示
    for word in word_list:
        print word

#実行結果

>python characterRecognition.py test.jpg
認識処理中...
認識成功
文字認識のテスト

#補足(取得したjsonの例)

{
  "job": {
    "@status": "success",
    "@id": "(画像ID)", #画像のID
    "@queue-time": "2016/02/13 17:03:07"
  },
  "lines": {
    "line": [
      {
        "@text": "\u6587\u5b57\u8a8d\u8b58\u306e\u30c6\u30b9\u30c8", #認識した文字列
        "shape": {
          "@count": "4",
          "point": [       #文字の画像上の座標 (左上、左下、右下、右上)
            {
              "@x": "35",
              "@y": "33"
            },
            {
              "@x": "35",
              "@y": "67"
            },
            {
              "@x": "293",
              "@y": "67"
            },
            {
              "@x": "293",
              "@y": "33"
            }
          ]
        }
      }
    ],
    "@count": "1"
  },
  "message": null
}

#あとがき
とりあえずメモ用に書いてみました。
詳しく知りたい方はコメントをお待ちしています。

25
25
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?