Overview
- Webカメラ(BenQ ideaCam S1 Pro)を使って文字認識をやってみました。
- EasyOCRというパッケージを使えば比較的簡単に文字認識ができる。
- 基板の文字を読むにはマクロレンズが必須
Setup
- python3.12
pip install easyocr opencv-python
Implementation
- ソースコードはこんなかんじ
cv.VideoCapture
の数字は環境に合わせて変更
import cv2
import easyocr
import time
# easyocrのリーダーを初期化(日本語と英語に対応)
reader = easyocr.Reader(['ja', 'en'],gpu=True)
# Webカメラを開く
cap = cv2.VideoCapture(0)
while True:
# フレームを取得
ret, frame = cap.read()
if not ret:
break
# フレームをグレースケールに変換
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 文字認識を実行
start_time = time.time()
results = reader.readtext(gray)
end_time = time.time()
# 認識結果を描画
for (bbox, text, prob) in results:
(top_left, top_right, bottom_right, bottom_left) = bbox
top_left = tuple(map(int, top_left))
bottom_right = tuple(map(int, bottom_right))
# 文字列を描画
cv2.rectangle(frame, top_left, bottom_right, (0, 255, 0), 2)
cv2.putText(frame, text, (top_left[0], top_left[1] - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
# FPSを計算して表示
fps = 1 / (end_time - start_time)
cv2.putText(frame, f"FPS: {fps:.2f}", (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
# 結果を表示
cv2.imshow("Real-time OCR", frame)
# 'q'キーで終了
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# リソースを解放
cap.release()
cv2.destroyAllWindows()
Results
-
こんなかんじ
-
Youtube動画公開予定
Conclusion
- EasyOCRを使うと文字認識はすごく簡単に実装できる
- ideaCam S1 Proのマクロレンズを使うことで基板に映る文字列も文字認識できる