首页 > 解决方案 > 在 Python 中迭代所有子文件夹和 OCR 图像

问题描述

我有一个包含多个子文件夹和图像的文件夹,我想使用百度 OCR 为每个子文件夹提取图像文件中的文本,并为每个由子文件夹名称命名的子文件夹写入一个 excel(需要拆分内容)文件:

folder
        \ sub1\file0.jpg
        \ sub1\file1.jpg
        \ sub1\file2.png
        .
        .
        .
        \ sub2\xxx.png
        \ sub2\yyy.jpg
        \ sub2\zzz.png
        .
        .
        .

预期成绩:

folder
        \ sub1\file0.jpg
        \ sub1\file1.jpg
        \ sub1\file2.png
        \ sub1\sub1.xlsx
        .
        .
        .
        \ sub2\xxx.png
        \ sub2\yyy.jpg
        \ sub2\zzz.png
        \ sub2\sub2.xlsx
        .
        .
        .

这是我尝试过的,但我不知道如何实现整个过程。请分享您的见解和想法。谢谢。

Step1:迭代所有子文件夹和图片文件:

import os
dir_name = "D:/folder"     
for root, dirs, files in os.walk(dir_name, topdown=False):
    for file in files:
        print(file)
        print(root)
        print(dirs)

第 2 步:OCR 一张图像

from aip import AipOcr

APP_ID = '<APP_ID>'
API_KEY = '<APP_KEY>'
SECRET_KEY = '<APP_SECRET>'

aipOcr = AipOcr(APP_ID, API_KEY, SECRET_KEY)

filePath = "test.jpg"

def get_file_content(filePath):
    with open(filePath, 'rb') as fp:
        return fp.read()

options = {
    'detect_direction': 'true',
    'language_type': 'CHN_ENG',
    'recognize_granularity': 'big',
    'vertexes_location': 'true',
    #'probability': 'true',
    #'detect_language': 'true'
}

result = aipOcr.basicAccurate(get_file_content(filePath), options)

print(result)

df = DataFrame(result)

writer = ExcelWriter('test.xlsx')
df.to_excel(writer, index = False)
writer.save()

Step3:为每个子文件夹编写一个excel文件(感谢@Florian H)

在 Python 中使用子文件夹的名称为每个子文件夹创建空文件

from os import listdir
from os.path import isfile, join

mypath = "D:/"

def write_files(path):
    folders = [f for f in listdir(path) if not isfile(join(path, f))]
    if len(folders) == 0:
        #Writing the actual File
        open(path+"/"+path.split("/")[-1]+".xlsx", "w+")
    else:
        for folder in folders:
            write_files(path+"/"+folder)

write_files(mypath)

标签: pythonpandasoperating-systemocrlistdir

解决方案


推荐阅读