首页 > 解决方案 > 使用 pytesseract 进行 OCR 时出现缓存错误

问题描述

我正在尝试使用 pytesseract OCR 从目录中的所有 PDF 中提取文本,但我收到一条错误消息,提示我的设备上没有足够的空间。

我想在不再需要后从缓存中删除每个图像,因为建议该用户这样做,但我在pytesseract文档中找不到任何解释如何执行此操作的内容。

这是我的代码:

import io
from PIL import Image
import pytesseract
from wand.image import Image as wi

def extract_text_from_image(path):
    pdfFile = wi(filename = path, resolution = 300)
    image = pdfFile.convert('jpeg')  

    imageBlobs = []
    for img in image.sequence:
        imgPage = wi(image = img)
        imageBlobs.append(imgPage.make_blob('jpeg'))

    extract = []
    for imgBlob in imageBlobs:
        image = Image.open(io.BytesIO(imgBlob))
        text = pytesseract.image_to_string(image, lang = 'eng')
        extract.append(text)

    return extract

这是错误消息:

CacheError: unable to extend cache 'C:/Users/b00kgrrl/AppData/Local/Temp/magick-11952ORBzkae3wXX_18': No space left on device @ error/cache.c/OpenPixelCache/3889

标签: pythonimagemagickocrpython-tesseract

解决方案


我使用在这里这里找到的代码自己解决了这个问题:

import io
from PIL import Image
import pytesseract
from wand.image import Image as wi
import winshell

def extract_text_from_image(path):

    pdfFile = wi(filename = path, resolution = 300)
    image = pdfFile.convert('jpeg')

    tempdir = r"C:\Users\b00kgrrl\AppData\Local\Temp"
    cache = os.listdir( tempdir )

    imageBlobs = []
    for img in image.sequence:
        imgPage = wi(image = img)
        imageBlobs.append(imgPage.make_blob('jpeg'))

    extract = []
    for imgBlob in imageBlobs:
        image = Image.open(io.BytesIO(imgBlob))
        text = pytesseract.image_to_string(image, lang = 'eng')
        extract.append(text)

        for item in cache:
            if item.endswith(".jpg") or item.startswith("magick-"):
                os.remove( os.path.join( tempdir, item ) )
                winshell.recycle_bin().empty(confirm=False, show_progress=False, sound=False)

    return extract

推荐阅读