簡體   English   中英

如何使用魔杖 python 將掃描的 pdf 轉換為文本

[英]how to convert scanned pdf to text using wand python

在使用 Wand 和 imageMagick 將掃描的 PDF 轉換為文本時,我收到以下錯誤:

錯誤:

Traceback (most recent call last):
  File "C:/Users/gibin/PycharmProjects/ML/Image_PDF/.ksldwjldf.py", line 28, in <module>
    Get_text_from_image(r"C:\Users\gibin\PycharmProjects\ML\Image_PDF\536676972_image.pdf")
  File "C:/Users/gibin/PycharmProjects/ML/Image_PDF/.ksldwjldf.py", line 13, in Get_text_from_image
    pdf=wi(filename=pdf_path,resolution=300)
  File "C:\Users\gibin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\wand\image.py", line 8212, in __init__
    units=units)
  File "C:\Users\gibin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\wand\image.py", line 8686, in read
    self.raise_exception()
  File "C:\Users\gibin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\wand\resource.py", line 240, in raise_exception
    raise e
wand.exceptions.DelegateError: FailedToExecuteCommand `"gswin32c.exe" -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 "-sDEVICE=pngalpha" -dTextAlphaBits=4 -dGraphicsAlphaBits=4 "-r300x300"  "-sOutputFile=C:/Users/GIBIN_~1./AppData/Local/Temp/magick-23476_sCYGtEq3gb-%d" "-fC:/Users/GIBIN_~1./AppData/Local/Temp/magick-234763X1vpsurlvH5" "-fC:/Users/GIBIN_~1./AppData/Local/Temp/magick-23476fUlS8Tr85dwk"' (The system cannot find the file specified.
) @ error/delegate.c/ExternalDelegateCommand/459

代碼:

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

pytesseract.pytesseract.tesseract_cmd = r"C:\Users\gibin\AppData\Local\Tesseract-OCR\tesseract.exe"
def Get_text_from_image(pdf_path):
    print(pdf_path)
    pdf=wi(filename=pdf_path,resolution=300)
    pdfImg=pdf.convert('jpeg')
    imgBlobs=[]
    extracted_text=[]
    for img in pdfImg.sequence:
        page=wi(image=img)
        imgBlobs.append(page.make_blob('jpeg'))
        print(len(imgBlobs))
    for imgBlob in imgBlobs:
        im=Image.open(io.BytesIO(imgBlob))
        text=pytesseract.image_to_string(im)
        print(text)
        extracted_text.append(text)
    return ([i.replace("\n","") for i in extracted_text])
Get_text_from_image(r"C:\Users\gibin\PycharmProjects\ML\Image_PDF\536676972_image.pdf")

這在安裝 GHOSTSCRIPT 並將其添加為環境變量后工作正常。 這里下載 ghostscript

之后,您需要設置環境變量。 添加一個新的系統變量:

變量:GS_PROG

值:gswin64c.exe 文件所在位置的完整路徑

你見過這個Imagemagick Convert PDF to JPEG: FailedToExecuteCommand `"gswin32c.exe" / PDFDelegateFailed嗎? 相反,您也可以使用其他方法將 pdf 逐頁轉換為 jpg 圖像。 我已經使用 pdf2img 庫來做到這一點,如果您可以自由使用任何庫,那么更喜歡使用 pdf2img。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM