【问题标题】:Extracting particular text associated value from an image从图像中提取特定文本相关值
【发布时间】:2019-06-30 18:38:13
【问题描述】:

我有一张图片,我想从图片中提取键值对的详细信息。

例如,我想提取“MASTER-AIRWAYBILL NO:”的值

我已经使用 python opencv 和 OCR 从图像中提取整个文本,但我不知道如何从图像的整个结果文本中仅提取“MASTER-AIRWAYBILL NO:”的值.

请查找代码:

import cv2
import numpy as np
import pytesseract
from PIL import Image
print ("Hello")
src_path = "C:\\Users\Venkatraman.R\Desktop\\alpha_bill.jpg"
pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files (x86)\Tesseract-OCR\tesseract.exe"


print (src_path)


# Read image with opencv
img = cv2.imread(src_path)

# Convert to gray
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Apply dilation and erosion to remove some noise
kernel = np.ones((1, 1), np.uint8)
img = cv2.dilate(img, kernel, iterations=1)
img = cv2.erode(img, kernel, iterations=1)

# Write image after removed noise
cv2.imwrite(src_path + "removed_noise.png", img)

#  Apply threshold to get image with only black and white
#img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 2)

# Write the image after apply opencv to do some ...
cv2.imwrite(src_path + "thres.png", img)

# Recognize text with tesseract for python
result = pytesseract.image_to_string(Image.open(src_path + "thres.png"))


# Remove template file
#os.remove(temp)


print ('--- Start recognize text from image ---')
print (result)

所以输出应该是这样的:

MASTER-AIRWAYBILL NO:157-46637194

【问题讨论】:

    标签: python opencv ocr


    【解决方案1】:

    您可以使用pytesseract image_to_string()regex 来提取所需的文本,即:

    from PIL import Image
    import pytesseract, re
    f = "ocr.jpg"
    t = pytesseract.image_to_string(Image.open(f))
    m = re.findall(r"MASTER-AIRWAYBILL NO: [\d—-]+", t)
    if m:
        print(m[0])
    

    输出:

    MASTER-AIRWAYBILL NO: 157—46637194
    

    【讨论】:

    • 输出打印为空
    • 像往常一样,我测试了答案的代码(python 3.6),它按预期工作。我使用的图像文件与您的问题相同:i.stack.imgur.com/RKebi.jpg。想评论否决的投票?
    • 即使使用相同,我通过打印它正在打印的 t 进行检查,但它没有打印 m 的值
    • 我用最新版的pytesseract 换成了py3.6。如果您不使用它,请更新它。我看不出您的结果与我的结果不同的任何其他原因。
    • 我用的是3.7.1版本的python
    【解决方案2】:

    我正在使用 python 2.7,我也想从图像中找到供应商名称 我该怎么找?

    m = re.findall(r"MASTER-AIRWAYBILL NO: [\d—-]+", t) 对于上面的行,它的显示错误

    如果我使用 m=re.findall(r'Vendor Name:[\d--]+', t) 那么它也会显示错误

    【讨论】:

    • 欢迎来到 SO,如果您遇到问题,请发布一个新问题,这不会为 OP 提供答案。一旦你有足够的声望,你就可以在 OP 中添加评论。
    【解决方案3】:

    你可以在安装tesseract后试试这个。

    from PIL import Image
    import pytesseract, re
    pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
    t = pytesseract.image_to_string(Image.open("path"))
    m = re.findall(r"Invoice No. [\d—-]+", t)
    if m:
        print(m[0])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-03
      • 2011-03-08
      • 2015-05-21
      • 2022-11-14
      • 2022-06-15
      • 2014-07-31
      相关资源
      最近更新 更多