2015-06-28 47 views
1

我有一個遠程PDF文件,我需要逐頁閱讀並不斷向每個OCR傳遞OCR文本。將遠程PDF的頁面轉換爲OCR的臨時圖像

import pytesseract 
from pyPdf import PdfFileWriter, PdfFileReader 
import cStringIO 
from wand.image import Image 
import urllib2 
import tempfile 
import pytesseract 
from PIL import Image 

remoteFile = urllib2.urlopen(urllib2.Request("file:///home/user/Documents/TestDocs/test.pdf")).read() 
memoryFile = cStringIO.StringIO(remoteFile) 

pdfFile = PdfFileReader(memoryFile) 
for pageNum in xrange(pdfFile.getNumPages()): 
    currentPage = pdfFile.getPage(pageNum) 

    ## somehow convert currentPage to wand type 
    ## image and then pass to tesseract-api 
    ## 
    ## TEMP_IMAGE = some conversion to temp file 
    ## pytesseract.image_to_string(Image.open(TEMP_IMAGE)) 

memoryFile.close() 

我想用cStringIOtempfile,但我無法弄清楚如何使用它們用於此目的。

如何解決這個問題?

回答

1

這樣做有兩個選擇,給出您提供的代碼更兼容的方式是臨時存儲在該目錄中的圖像,然後在使用pytesseract讀取文本後刪除它們。我創建了一個魔杖類型的圖像來分別從PDF中提取每個圖像,然後將其轉換爲pytesseract的PIL類型圖像。以下是我用於此的代碼,將檢測到的文本寫入數組「文本」,其中每個元素都是原始PDF中的圖像,我還更新了一些導入以使其與Python3兼容(cStringIO-> io和urllib2 - > urllib.request裏)。

​​

另外,如果你想避免創建和刪除臨時文件爲每個圖像,你可以使用numpy的和OpenCV提取圖像作爲一個blob,將其轉換爲numpy的數組,然後把它變成一個PIL圖像爲pytesseract執行OCR(reference

import PyPDF2 
import os 
import pytesseract 
from wand.image import Image 
from PIL import Image as PILImage 
import urllib.request 
import io 
import numpy as np 
import cv2 

with urllib.request.urlopen('file:///home/user/Documents/TestDocs/test.pdf') as response: 
    pdf_read = response.read() 
    pdf_im = PyPDF2.PdfFileReader(io.BytesIO(pdf_read)) 
    text = [] 
    for p in range(pdf_im.getNumPages()): 
     with Image(filename=('file:///home/user/Documents/TestDocs/test.pdf') + '[' + str(p) + ']') as img: 
      img_buffer=np.asarray(bytearray(img.make_blob()), dtype=np.uint8) 
      retval = cv2.imdecode(img_buffer, cv2.IMREAD_GRAYSCALE) 
      text.append(pytesseract.image_to_string(PILImage.fromarray(retval)))