【问题标题】:Text extraction from multiple image files using Python使用 Python 从多个图像文件中提取文本
【发布时间】:2019-07-30 09:17:20
【问题描述】:

我有一个包含多个图像文件的文件夹。我想从这些文件中提取文本并将输出保存为 csv 文件,其中包含 2 列,第 1 列:Image_no.,第 2 列:Text。

TIA

我在 Python 上试过这段代码:

img_dir = "MyFolder" # Folder name containing image files 
data_path = os.path.join(img_dir,'*g')
files = glob.glob(data_path)
data = []
for f1 in files:
    img = cv2.imread(f1)
    x=data.append(img)

Q1:如何查看从每张图片中提取的文字? Q2:如何将图片名称和对应文字导出到csv?

【问题讨论】:

  • 您当前的代码只是将每个图像中的所有像素附加到一个列表中。查看 tesseract 或其他可以轻松与 OpenCV 集成的 OCR 库,例如:pyimagesearch.com/2018/09/17/…

标签: image-processing text-extraction


【解决方案1】:

第 1 部分:

请安装 Tesseract 和 pytesseract

pip install pillow
pip install pytesseract
pip install tesseract

参考链接:

第 2 部分:

from PIL import Image
import pytesseract
import os
import pandas as pd

# Path is given for for 64 bit installer
pytesseract.pytesseract.tesseract_cmd = "C:/Program Files/Tesseract-OCR/tesseract.exe"

f = []
t = []
input_dir = r'C:/Users/suhas/Downloads/images/'

for root, dirs, filenames in os.walk(input_dir):
    for filename in filenames:
        try:
            print(filename)
            f.append(filename)
            img = Image.open(input_dir+ filename)
            text = pytesseract.image_to_string(img, lang = 'eng')
            t.append(text)
            print(text)
            print('-='*20)
        except:
            continue


df = pd.DataFrame(list(zip(f, t)),columns=['file_Name','Text'])

输出:

                     file_Name      Text
0   Screenshot_20191104-130254.png  MNP_6050
1   Screenshot_20191104-130336.png  MNP_6039
2   Screenshot_20191104-130943.png  MNP_6116
3   Screenshot_20191104-131248.png  MNP_6093
4   Screenshot_20191104-230714.png  MNP_6013
5   Screenshot_20191104-230834.png  MNP_6006

PS:为了获得干净的文本,您可能需要使用正则表达式

参考链接:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多