如何从图像中提取信息(PNG)

数据挖掘 Python 深度学习 nlp 图像预处理 opencv
2022-02-21 10:52:31

我正在尝试从图像(png)中提取一些特定信息。

我尝试使用以下代码提取文本

import cv2
import pytesseract
import os
from PIL import Image
import sys

def get_string(img_path):
    # Read image with opencv
    img = cv2.imread(img_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 the image after apply opencv to do some ...
    cv2.imwrite("thres.png", img)
    # Recognize text with tesseract for python
    result = pytesseract.image_to_string(Image.open("invoice.png"))
    os.remove("invoice.png")

    return result

if __name__ == '__main__':
    from sys import argv

    if len(argv)<2:
        print("Usage: python image-to-text.py relative-filepath")
    else:
        print('--- Start recognize text from image ---')
        for i in range(1,len(argv)):
            print(argv[i])
            print(get_string(argv[i]))
            print()
            print()

        print('------ Done -------')

但我想从特定字段中提取数据。

 a) INVOICE NO.
 b) CUSTOMER NO.
 c) SUBTOTAL
 d) TOTAL
 e) DATE

如何从下图“发票”中提取所需信息?

PFB

在此处输入图像描述

2个回答

如果您的所有图像都与这个相似(或有一小部分可能的设计),您可以简单地参考图像上该字段所在的位置(按像素计算)并对其进行切片。

切片后,您可以使用任何 OCR 算法来提取该数据。

如果您的数据有更多的变化,您可以在整个图像上使用 OCR,这通常是一种缓慢的算法。

如果你有少于 50 张左右的图片来做这件事,那么手工做会更有效率(不值得写代码)

是一个相当广泛的问题,但也许可以帮助您入门。