The quick brown fox jumps over the lazy dog. 这句话涵盖了 a 到 z ,共 26 个字母,这句话原本是用来检测键盘有没有故障。
光学字元辨识是透过影像处理,撷取并辨别影像上的文字,稍微介绍一下简单作法的流程:
原始影像 | 二值化 | 滤杂讯 |
原始影像 | 前处理 | 文字切分 |
以上这些流程,除了後处理以外,其他都可以靠 Azure OCR 来帮忙搞定,下面开始利用 Azure 来处理 OCR。
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 来翻译。
>>: D-18. SQL & NoSQL、SQL injection、primary key & foreign key
《30天带你上完 Google Data Analytics Certificate 课程》系列将...
昨天我们搭了一座桥梁从project到user app了,紧接着我们要到user app底下的url...
ChatOps with Mattermost chatops好处 成本低 互动性佳 即时反应提高效...
昨天成功地取得了vector agent搜集的metric和logger,在使用上因为metric算...
工作之余兴起开发side project的念头,几经思考後决定以Rust语言撰写一个基本的RISC-...