python - 读取彩色数字图像是什么数字以进行控制台

标签 python python-3.x image opencv image-processing

因此,我正在尝试创建一个程序,该程序可以查看图像的编号并在控制台中打印整数。 (我正在使用 python 3)

例如,程序识别出以下图像(程序必须检查的实际图像)是数字 2:

number 2

我试图将它与其他图像进行比较,其中 2 与 cv2.matchTemplate()但是每次蓝色像素 rgb 值对于每个图像都有点不同,图像可能会更大或更小。例如下图:

number 2

除了其他蓝色数字图像(0-9)之外,它还必须识别它,例如以下图像:

number 5

我尝试了多个匹配模板代码,并制作了一个包含数字 0-9 图像的文件夹作为模板,但每次几乎每个数字都在需要识别的数字中被识别。例如数字 5 在数字 2 的图像中被识别。如果它不能识别所有这些,它就会识别错误的。

我试过的那些:

  • Answer from this question
  • Both codes from this tutorial
  • And the one from this tutorial

  • 但就像我之前说的那样,这些问题也随之而来。

    我还尝试查看每张图像中蓝色的百分比,但这些数字接近于通过查看其中的蓝色来告诉数字不同。

    有没有人有办法解决吗?我使用 cv2.matchTemplate() 是不是很愚蠢?有没有更简单的选择? (我不介意为此使用库,因为这是更大代码段的一部分,但我更喜欢对其进行编码,而不是库)

    最佳答案

    除了使用模板匹配,更好的方法是使用 Pytesseract OCRimage_to_string() 读取数字.但在执行 OCR 之前,您需要对图像进行预处理。为获得最佳 OCR 性能,预处理图像应具有所需的文本/数字/字符,以黑色进行 OCR,背景为白色。一个简单的预处理步骤是将图像转换为灰度,即大津阈值以获得二值图像,然后将图像反转。这是预处理步骤的可视化:

    输入图片 ->灰度 ->大津的阈值->已准备好用于 OCR 的倒置图像

    enter image description here
    enter image description here
    enter image description here
    enter image description here

    Pytesseract OCR 的结果

    2



    这是其他图像的结果:

    enter image description here
    enter image description here
    enter image description here
    enter image description here

    2



    enter image description here
    enter image description here
    enter image description here
    enter image description here

    5



    我们使用 --psm 6配置选项来假设一个统一的文本块。见 here更多配置选项。

    代码
    import cv2
    import pytesseract
    
    pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
    
    # Load image, grayscale, Otsu's threshold, then invert
    image = cv2.imread('1.png')
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
    invert = 255 - thresh
    
    # Perfrom OCR with Pytesseract
    data = pytesseract.image_to_string(invert, lang='eng', config='--psm 6')
    print(data)
    
    cv2.imshow('thresh', thresh)
    cv2.imshow('invert', invert)
    cv2.waitKey()
    

    注:如果坚持使用模板匹配,则需要使用比例变体模板匹配。看看how to isolate everything inside of a contour, scale it, and test the similarity to an image?Python OpenCV line detection to detect X symbol in image对于一些例子。如果您确定您的图像是蓝色的,那么另一种方法是将颜色阈值与 cv2.inRange() 一起使用。获得二值蒙版图像,然后在图像上应用 OCR。

    关于python - 读取彩色数字图像是什么数字以进行控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59794624/

    相关文章:

    python - Dask 数据框没有属性分类

    c# - 适合 C# 程序员的是 C++ 还是 Python?

    python - 属性错误 : 'dict' object has no attribute 'predictors'

    C# - 快速反转图像字节?

    python - 如何在不损坏文本的情况下去除点/噪音?

    python - 编辑和重新排序列表中的元组

    python - 为什么 "printing"出现在 "returning"之前?

    python - Google Cloud 中的 Python 3 类型包返回错误

    python - 类型错误 : 'float' object not callable in Python

    php - 压缩并保存base64图像