見出し画像

AzureのAI visionを使ってみる | OCR編

OCRとは


「Optical Character Recognition」(光学文字認識)の略で、画像や手書き文書などに含まれる文字をデジタルデータとして認識し、テキストデータに変換する技術です。たとえば、スキャンした文書や写真に写っている文字をコンピューターが自動的に読み取り、編集可能なテキストに変換することができます。

OCR技術は、書籍のデジタル化、名刺のスキャン、手書きのノートをデジタル化するなど、さまざまな場面で活用されています。日本語の文字認識も対応しており、手書き文字や印刷文字を正確に認識するために特化した技術もあります。
Azure AI visionを使って物体検出をした記事を書きましたが、今回は、そのAzure AI visonを使ってOCRを行ってみます。

Azure AI visionでOCRをしてみる

使った画像は、以下の画像です。

from azure.ai.vision.imageanalysis import ImageAnalysisClient
from azure.ai.vision.imageanalysis.models import VisualFeatures
from azure.core.credentials import AzureKeyCredential

from dotenv import load_dotenv
import os

dotenv_path = ".env"
load_dotenv(dotenv_path)

VISION_ENDPOINT = os.getenv('VISION_ENDPOINT')
VISION_KEY = os.getenv('VISION_KEY')

# Create an Image Analysis client
client = ImageAnalysisClient(
    endpoint=VISION_ENDPOINT,
    credential=AzureKeyCredential(VISION_KEY)
)

image_path ="OCR_sample01.jpg"

# Load image to analyze into a 'bytes' object
with open(image_path, "rb") as f:
    image_data = f.read()
    
visual_features =[
        #VisualFeatures.TAGS,
        #VisualFeatures.OBJECTS,
        #VisualFeatures.CAPTION,
        #VisualFeatures.DENSE_CAPTIONS,
        VisualFeatures.READ,
        #VisualFeatures.SMART_CROPS,
        #VisualFeatures.PEOPLE,
    ]   

# Analyze all visual features from an image stream. This will be a synchronously (blocking) call.
result = client.analyze(
    image_data=image_data,
    visual_features=visual_features,
    #smart_crops_aspect_ratios=[0.9, 1.33],
    #gender_neutral_caption=True,
    #language="jp"
) 

if result.read is not None:
    for line in result.read.blocks[0].lines:
        print(line.text)
2024826日
こんにちは OCRを試す
サンブル画像です。
※こんにちは、OCRを試すサンプル画像です。
F10
F11
=3
F6
F7
F8
29
F4
F5
▶II
$ う
% え
& お
~
1
ゆ
)よ
を
=
45 え
...
Fn
目
ひらがな
ローマ字
Output is truncated. View as a scrollable element or open in a text editor. Adjust cell output settings...

ちゃんと手書き文字も読み取ってくれています。

import matplotlib.pyplot as plt
from PIL import Image, ImageDraw

image_filename = image_path
# Get objects in the image
if result.read is not None:
    print("\nObjects in image:")

    # Prepare image for drawing
    image = Image.open(image_path)
    fig = plt.figure(figsize=(image.width/100, image.height/100))
    plt.axis('off')
    draw = ImageDraw.Draw(image)
    color = 'cyan'

    for detected in result.read.blocks[0].lines:
        for detected_object in detected.words:
            r = detected_object.bounding_polygon

            width = abs((r[0]["x"]-r[2]["x"]))
            height = abs((r[0]["x"]-r[2]["x"]))

            bounding_box = ((r[0]["x"], r[0]["y"]), (r[0]["x"] + width, r[0]["y"] + height) )
            draw.rectangle(bounding_box, outline=color, width=3)

    # Save annotated image
    plt.imshow(image)
    plt.tight_layout(pad=0)
    outputfile = 'objects.jpg'
    fig.savefig(outputfile)
    print('  Results saved in', outputfile)


記号は一部認識していないようですが、精度としては十分ではないでしょうか。

GPT4oでは?


ブラウザ版のGPT4oにもお願いしてみます。

画像中にある文字を読んで出力してください。
読み取った文字だけを出力してください。

It seems there was an issue with loading the Japanese language data for OCR processing. I will try processing the image using the default language settings, which should still be able to recognize some of the text. Let me proceed with that. ​​

The default OCR settings did not successfully recognize the Japanese text in the image. To properly extract the text from the image, I would need to use Japanese language data, which isn't currently available in this environment.

To proceed, you can either install the necessary Japanese language files for Tesseract on your local machine or use an OCR service that supports Japanese. If you need further guidance on how to set this up, feel free to ask! ​

どうやらデフォルトで日本語OCRはできないようです。

日本語トレーニングデータと一緒にプロンプトに入れてみます。
(トレーニングデータはここからダウンロードできます。)

⑰

ヽ
ノ
マ
レ タ

よ ゥ c& と
吉 修 て す

へ

ト

ヶ o 笠 引 >(
ん た ぁ る
⑰ ル

試 す サ ン プ ル 画 像 で す 。

※ こ ん に ち は 、OCR

バグってマスネ
プロンプトを変えて、OCRを使用せずに読んでもらいます。

画像中にある文字を読んで出力してください。
OCRを使用せずに、読み取った文字だけを出力してください。
手書き部分:

2024年8月26日
こんにちは、OCRを試すサンプル画像です。

印刷部分:

※こんにちは、OCRを試すサンプル画像です。

OCRを使わない方が、ちゃんと読めてる。

この記事が気に入ったらサポートをしてみませんか?