今回はMicrosoft Cognitive Servicesの一つ「Computer Vision API」を使ってOCR認識を試します。

 

Microsoft Cognitive Servicesとは?

マイクロソフトが提供しているAzure Machine Learningなどの機械学習サービスの一種で、Cognitive Servicesでは顔認識や音声認識などの「認識サービス」をAPIとして提供しています。

現在、Cognitive Servicesには複数の種類が提供されており、ある一定の認識回数までは無償で提供されています。

 

Computer Vision APIとは?

今回使用する「Computer Vision API」とは、画像データをもとに様々な認識ができる汎用的なAPIの一種です。この記事ではOCR認識機能について話しますが、それ以外にも、以下の機能があります:

画像のタグ付け

画像の説明

画像のサムネイル作成

 

Computer Vision APIのプレビューへ参加

まず、Cognitive Servicesにある、Computer Vision APIのサイトへアクセスします。

https://www.microsoft.com/cognitive-services/en-us/computer-vision-api

「Get started for free」をクリックします ※Internet Explorerのみに対応

Microsoftアカウントでログインすると、試用版を選択する画面に移ります。

 

スクロールすると、「Computer Vision – Preview」があるので、チェックを入れます。

無償で提供されてますが、上限として月間5000回、1分間に20回までと制限がありますので、要注意です。

 

さらにスクロールすると、利用条項などの同意が求められますので、「I agree to the Microsoft Cognitive Services Terms…」にチェックを入れて「Subscribe」をクリックします。

 

これで登録完了です。

APIを使用するためのAPIキーが2つ「Key 1」と「Key 2」が表示されます。

初期状態ではXXXXXXで表示されてますので、「Show」をクリックすると表示されます。

使用回数の確認は「Show Quota」をクリックすればできます。

 

実際にComputer Vision APIを使ってOCR認識を試す

APIキーが生成されたので、次はVisual Studioを使って、簡単なコンソールプログラムを作ってみます。

公式には「Visual Studio 2015 Community Edition」以上での利用が推奨されています。

まず、新しいプロジェクトを作成し、

 

コンソールアプリケーションを選択します。

 

今回は2つのNuGetパッケージを追加します。

 

1つ目はJSON型を変換するためのNewtosoft.Jsonと

 

2つ目はComputer Vision APIのSDKが含まれている、Microsoft.ProjectOxford.Visionです。

 

それではコーディングに入ります。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.ProjectOxford.Vision;
using Microsoft.ProjectOxford.Vision.Contract;
using System.IO;

namespace VisionAPI
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Specify the file path to analyze: ");
            string imageFilePath = Console.ReadLine();

            Uri fileUri = new Uri(imageFilePath);
            var result = DoWork(fileUri, true);
            Console.ReadKey();
        }

        static async Task<OcrResults> UploadAndRecognizeImage(string imageFilePath, string language)
        {

            // Create Project Oxford Vision API Service client
            
            VisionServiceClient VisionServiceClient = new VisionServiceClient("Enter the generated API key here");

            using (Stream imageFileStream = File.OpenRead(imageFilePath))
            {
                // Upload an image and perform OCR
                OcrResults ocrResult = await VisionServiceClient.RecognizeTextAsync(imageFileStream, language);
                return ocrResult;
            }
        }

        /// Perform the work for this scenario

        static async Task DoWork(Uri imageUri, bool upload)
        {
            Console.WriteLine("Executing OCR...");

            string languageCode = "ja";
            var ocrResult = new OcrResults();
            ocrResult = await UploadAndRecognizeImage(imageUri.LocalPath, languageCode);
            Console.WriteLine("OCR complete");

            // Log analysis result in the log window
            //
            Console.WriteLine("");
            Console.WriteLine("Results are shown below:");
            LogOcrResults(ocrResult);
        }

        static void LogOcrResults(OcrResults results)
        {
            StringBuilder stringBuilder = new StringBuilder();

            if (results != null && results.Regions != null)
            {
                stringBuilder.Append("Details:");
                stringBuilder.AppendLine();
                foreach (var item in results.Regions)
                {
                    foreach (var line in item.Lines)
                    {
                        foreach (var word in line.Words)
                        {
                            stringBuilder.Append(word.Text);
                            stringBuilder.Append(" ");
                        }

                        stringBuilder.AppendLine();
                    }

                    stringBuilder.AppendLine();
                }
            }

            Console.WriteLine(stringBuilder.ToString());
        }
    }
}

 

これで、プログラムは完成です。

早速試してみます。

私が試した画像は以下の画像なのですが、

結果このようになりました。

認識率は100%ではありませんが、ほとんど認識できてますね。

 

情報元: https://www.microsoft.com/cognitive-services/en-us/documentation