Day 12 Azure cognitive service: OCR- 光学字元辨识

Azure cognitive service: OCR- 光学字元辨识

OCR- Optical Character Recognition


The quick brown fox jumps over the lazy dog. 这句话涵盖了 a 到 z ,共 26 个字母,这句话原本是用来检测键盘有没有故障。

光学字元辨识是透过影像处理,撷取并辨别影像上的文字,稍微介绍一下简单作法的流程:

  • 影像前处理:把多余的杂讯去除,比较单纯的情况,可以先将图片二值化,变成黑白图片,然後再把杂讯去除。
原始影像 二值化 滤杂讯
  • 文字侦测:找出图像中是文字的部分
    • 利用深度学习找出文字的位置,例如:EAST- Efficient accurate scene text detector。
    • 在文字图形相对单纯的情况,例如:有些网站会用验证码来确认使用者是人类,也就是所谓的验证码(Completely Automated Public Turing test to tell Computers and Humans Apart,CAPTCHA)。这种情况可能是固定字数的字母,字母大小可能也差不多,再加上一些杂讯,可以用简单的规则侦测每个字母的位置。
原始影像 前处理 文字切分
  • 文字辨识:辨别图像中的文字为何
    • 可以利用深度学习得到结果,例如:CRNN- Convolutional Recurrent Neural Network。
    • 或者,当文字相对单纯的情况,可以用比较简单的做法,例如:LeNet、KNN或SVM,把侦测到的字母切成固定大小的影像,透过机器学习的方法去做分类,辨别每个字母。
  • 後处理:文字辨识不见得会完全正确,这时可以根据上下文,再搭配已经建立好的词库,校正文字辨识的结果。

以上这些流程,除了後处理以外,其他都可以靠 Azure OCR 来帮忙搞定,下面开始利用 Azure 来处理 OCR。

OCR with Azure

  • 先取得金钥 (SUBSCRIPTION KEY) 和 端点 (ENDPOINT),作法与物体侦测一样,都是从电脑视觉服务的页面取得。
  • 安装Python套件
    • azure-cognitiveservices-vision-computervision
    • Pillow
    • requests
from azure.cognitiveservices.vision.computervision \
import ComputerVisionClient
from msrest.authentication import (
  CognitiveServicesCredentials
)
from azure.cognitiveservices.vision.computervision.models \
import OperationStatusCodes
from io import BytesIO
import requests
from PIL import Image, ImageDraw, ImageFont

# 利用金钥SUBSCRIPTION_KEY和端点ENDPOINT,取得使用电脑视觉服务的权限。
SUBSCRIPTION_KEY = "YOUR SUBSCRIPTION_KEY"
ENDPOINT = "YOUR ENDPOINT"
CV_CLIENT = ComputerVisionClient(
    ENDPOINT, CognitiveServicesCredentials(SUBSCRIPTION_KEY)
)

# 读取 URL 得到图片
url = "https://i.imgur.com/qyWiqQv.jpg"
response = requests.get(url)
img = Image.open(BytesIO(response.content))


draw = ImageDraw.Draw(img)
font_size = int(5e-2 * img.size[1])
fnt = ImageFont.truetype(
  "../static/TaipeiSansTCBeta-Regular.ttf",
  size=font_size)

# 开始利用 Azure 电脑视觉执行 OCR
ocr_results = CV_CLIENT.read(url, raw=True)
operation_location_remote = \
ocr_results.headers["Operation-Location"]
operation_id = operation_location_remote.split("/")[-1]

# 因为读取文字有多有少,所以时间会不一,透过 operation_id 可以确认目前进度
status = ["notStarted", "running"]
while True:
    get_handw_text_results = \
    CV_CLIENT.get_read_result(operation_id)
    if get_handw_text_results.status not in status:
        break
    time.sleep(1)

# 当执行状态 status 为 succeeded ,就可以把结果标示在原本的照片上了
succeeded = OperationStatusCodes.succeeded

if get_handw_text_results.status == succeeded:
    res = get_handw_text_results.analyze_result.read_results
    for text_result in res:
        for line in text_result.lines:
            bounding_box = line.bounding_box
            bounding_box += bounding_box[:2]
            draw.line(
                line.bounding_box, 
                fill=(255, 0, 0), 
                width=int(font_size / 10)
            )
            
            left = line.bounding_box[0]
            top = line.bounding_box[1]
            draw.text(
                [left, top - font_size],
                line.text,
                fill=(0, 255, 255),
                font=fnt,
            )

# bounding_box是四边形的顶点 [x1, y1, x2, y2, x3, y3, x4, y4],这边的四边形并非长方形,要使用 draw.line 画出封闭四边形。
# draw.line 需要知道起点位置,才能画出封闭形状。


img.save("output.png")

Azure OCR 使用限制

  • 支援语言
  • 手写的部分,只能辨识手写英文
  • 最新的Read API v3.2 支援 73 种语言

辨识完文字之後,看不懂的文字,还是看不懂,只好想办法翻译一下了。下一篇,使用 Azure 来翻译。


<<:  【Day12】能力封装--函式

>>:  D-18. SQL & NoSQL、SQL injection、primary key & foreign key

[Day 1] Google Data Analytics Professional Certificate 介绍

《30天带你上完 Google Data Analytics Certificate 课程》系列将...

[Day12] 注册API – urls之user app资料夹

昨天我们搭了一座桥梁从project到user app了,紧接着我们要到user app底下的url...

[Day 23] Mattermost - ChatOps

ChatOps with Mattermost chatops好处 成本低 互动性佳 即时反应提高效...

day8 : logging集中(中)

昨天成功地取得了vector agent搜集的metric和logger,在使用上因为metric算...

RISC-V on Rust 从零开始(1) - 安装 Rust 环境

工作之余兴起开发side project的念头,几经思考後决定以Rust语言撰写一个基本的RISC-...