LoginSignup
7
12

More than 5 years have passed since last update.

Python カメラからOCRをおこなってみるテスト

Posted at

やってみたかったのは静止画からOCRで英数字を読み出すこと。

探せばいろいろな記事がみつかったので、
少し変えて、カメラで写っている画像の中から英数字を読み出してみました。

カメラで写した特定の領域を赤枠で囲み、
その中の英数字を読み出してコンソールに出力します。

ocrTest.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import cv2
import pyocr
from PIL import Image
import pyocr.builders

tools = pyocr.get_available_tools()
tool = tools[0]

def OcrTest():
    cap = cv2.VideoCapture(0)

    while True:

        ret, frame = cap.read()

        Height, Width = frame.shape[:2]

        img = cv2.resize(frame,(int(Width),int(Height)))

        # OCRで読み取りたい領域を赤枠で囲む
        cv2.rectangle(img, (100, 100), (Width-200, Height-200), (0, 0, 255), 10)

        ocr(img, Width,Height)

        cv2.imshow('Ocr Test', img)

        cv2.waitKey(100)

    cap.release()
    cv2.destroyAllWindows() 

def ocr(img,Width,Height):
    dst = img[100:Height-200,100:Width-200] #OCRで読みたい領域を切り出す
    PIL_Image=Image.fromarray(dst)
    text = tool.image_to_string(
        PIL_Image,
        lang='eng',
        builder=pyocr.builders.TextBuilder())

    if(text != ""):
        print(text)

OcrTest()

結果

2018-08-20 (2).png

あたりまえですが、領域内にかざそうとしている最中はノイズがはいります。

7
12
0

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