使用 Tesseract OCR 从视频帧中提取数字

时间:2021-01-22 05:52:45

标签: python ocr tesseract python-tesseract

我有兴趣从我拥有的标准化视频(始终为高清分辨率 @ 1920x1080,30 FPS)中提取数字。数字总是出现在屏幕的固定部分,而且永远不会丢失。

我的方法是:

  1. 逐帧保存视频 PNG
  2. 加载单个 PNG 帧
  3. 选择感兴趣的领域(我想要四个部分
    从中提取数字;每个部分可能需要自己的图像处理;始终在完全相同的像素范围内)
  4. 使用 Python 和 Tesseract-OCR 提取数字
  5. 在数据框中存储值

其中两个部分的示例是:

enter image description here

enter image description here

我已经安装了 Python(我真的是 R 用户:S)和 tesseract,并且可以很好地运行 Tesseract 示例(即我已经确认我的设置有效)。

但是,当我在顶部图像上运行以下命令时 [247] Tesseract 无法提取数字,而您会认为它很容易提取,因为文本非常清晰。

from PIL import Image
import pytesseract
import os
import cv2
import argparse


img = cv2.imread("C:/Users/Luc/Videos/Monza GR4 1.56.156/frames/frame1060_speed.png")

cv2.imshow("RAW", img)
cv2.waitKeyEx(0)
cv2.destroyWindow()


imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
cv2.imshow("RBG", imgRGB)
cv2.waitKeyEx(0)
cv2.destroyWindow()


imgBW2WB = cv2.bitwise_not(imgRGB)
cv2.imshow("White black swapped", imgBW2WB)
cv2.waitKeyEx(0)
cv2.destroyWindow()


(thresh, blackAndWhiteImage) = cv2.threshold(imgBW2WB, 127, 255, cv2.THRESH_BINARY)
cv2.imshow("Remove some noise", blackAndWhiteImage)
cv2.waitKeyEx(0)
cv2.destroyWindow()


pytesseract.image_to_string(blackAndWhiteImage, 
                            config='--psm 10 --oem 3 -c tessedit_char_whitelist=0123456789')

输出为:

pytesseract.image_to_string(blackAndWhiteImage, 
                            config='--psm 10 --oem 3 -c tessedit_char_whitelist=0123456789')
Out[15]: '7\n\x0c'

我对 OCR 的经验很少(我在谷歌和 Youtube 上一起搜索过),非常感谢建议和指导。

问候, 吕克

2 个答案:

答案 0 :(得分:1)

您需要将 bytes 转换为 int。 请测试:

int.from_bytes(b'7\n\x0c', byteorder='little')

看起来你从 247 中得到了 47,但不是 2。干杯。

查看更多信息Convert bytes to int?

答案 1 :(得分:1)

请相应地使用此 Python 代码:

import cv2
from pytesseract import image_to_string
import numpy as np

def getText(filename):
    img = cv2.imread(filename)
    HSV_img = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
    h,s,v = cv2.split(HSV_img)
    v = cv2.GaussianBlur(v, (1,1), 0)
    thresh = cv2.threshold(v, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
    cv2.imwrite('{}.png'.format(filename),thresh)
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, ksize=(1, 2))
    thresh = cv2.dilate(thresh, kernel)
    txt = image_to_string(thresh, config="--psm 6 digits")
    return txt
    

text = getText('WYOtF.png')
print(text)
text = getText('0Oqfr.png')
print(text)

这里 getText() 函数将获取 png 图像文件的路径。转换到 HSV 域后,它将取值分量作为 v,然后在阈值化之前执行高斯模糊。您可以尝试根据您的图像改变 dilate 函数的内核大小。这两张图片是上面代码的输入,下面是输出。

输出

247
0.10.694

阈值结果

WYOtF.png

enter image description here enter image description here

0Oqfr.png

enter image description here enter image description here