2017-12-01 37 views
3

enter image description here어떻게 ImageMagick이를 사용하여 고해상도 사진과 일부 PDF 파일을 변환하기 위해 노력하고있어

바이너리 문자열에서 지팡이와 고해상도 JPEG를 만듭니다. 저는 파이썬 3.62 - 64 비트와 지팡이 0.4.4를 사용하여 10, 64로 이기고 있습니다. 명령 행에서 나는 가지고있다 :

$ /e/ImageMagick-6.9.9-Q16-HDRI/convert.exe -density 400 myfile.pdf -scale 2000x1000 test3.jpg. 

나는 잘 작동하고있다. 파이썬에서

:

나에게 저해상도의 JPEG 파일을주고있다
from wand.image import Image 

file_path = os.path.dirname(os.path.abspath(__file__))+os.sep+"myfile.pdf" 

with Image(filename=file_path, resolution=400) as image: 
    image.save() 
    image_jpeg = image.convert('jpeg') 

. 같은 것을하기 위해이 코드를 내 지팡이 코드로 어떻게 변환합니까?

편집 :

with open(file_path,'rb') as f: 
    image_binary = f.read() 

f.close() 

with Image(blob=image_binary,resolution=400) as img: 
    img.transform('2000x1000', '100%') 
    img.make_blob('jpeg') 
    img.save(filename='out.jpg') 

이가 읽어 : 나는 문제가 입력 PDF 그렇게 http://docs.wand-py.org/en/0.4.4/guide/read.html#read-blob에 따라 I 시도, 이진 문자열로 이미지 객체로 읽어되어야한다는 것을 깨달았다

파일은 ok이지만 출력은 10 개의 파일로 분할됩니다. 왜? 이것을 1 고해상도 jpeg로 가져와야합니다.

편집 :

은 내가 OCR API를에 JPEG를 보낼 필요, 그래서 객체와 같은 파일에 출력을 쓸 수 있는지 궁금 해서요. https://www.imagemagick.org/api/magick-image.php#MagickWriteImageFile 보면, 나는 시도 :

emptyFile = Image(width=1500, height=2000) 

with Image(filename=file_path, resolution=400) as image: 

    library.MagickResetIterator(image.wand) 
    # Call C-API Append method. 
    resource_pointer = library.MagickAppendImages(image.wand, 
                True) 

    library.MagickWriteImagesFile(resource_pointer,emptyFile) 

이 제공 :

File "E:/ENVS/r3/pdfminer.six/ocr_space.py", line 113, in <module> 
test_file = ocr_stream(filename='test4.jpg') 
File "E:/ENVS/r3/pdfminer.six/ocr_space.py", line 96, in ocr_stream 
library.MagickWriteImagesFile(resource_pointer,emptyFile) 
ctypes.ArgumentError: argument 2: <class 'TypeError'>: wrong type 

가 어떻게이 작업을 얻을 수 있나요?

+0

정확한 문제는 무엇입니까? 프로그램은 무엇을 출력합니까? 무엇을 출력하고 싶습니까? –

답변

2

Why? I need to get this into 1 high res jpeg.

PDF에는 ImageMagick에서 개별 이미지를 "스택"으로 간주하는 페이지가 포함되어 있습니다. 라이브러리는 wand.image.Image.sequance을 제공하여 각 페이지에서 작동합니다.

그러나 모두 개의 이미지를 단일 JPEG에 추가하십시오. 각 페이지 &을 함께 스티치하거나 C-API의 메서드 MagickAppendImages을 호출 할 수 있습니다.

from wand.image import Image 
from wand.api import library 
import ctypes 

# Map C-API not provided by wand library. 
library.MagickAppendImages.argtypes = [ctypes.c_void_p, ctypes.c_int] 
library.MagickAppendImages.restype = ctypes.c_void_p 

with Image(filename="path_to_document.pdf", resolution=400) as image: 
    # Do all your preprocessing first 
    # Ether word directly on the wand instance, or iterate over each page. 
    # ... 
    # To write all "pages" into a single image. 
    # Reset the stack iterator. 
    library.MagickResetIterator(image.wand)      
    # Call C-API Append method. 
    resource_pointer = library.MagickAppendImages(image.wand, 
                True)   
    # Write C resource directly to disk. 
    library.MagickWriteImages(resource_pointer,     
           "output.jpeg".encode("ASCII"), 
           False) 

는 업데이트 :

I need to send the jpeg to an OCR api ...

당신이 OpenCV의의 파이썬 API를 사용하여 가정하면, 각 페이지를 반복하고, NumPy와 버퍼를 통해 OCR에 이미지 파일 데이터를 전달해야 만합니다.

so I was wondering if I could write the output to a file like object

from wand.image import Image import numpy import cv2 def ocr_process(file_data_buffer): """ Replace with whatever your OCR-API calls for """ mat_instance = cv2.imdecode(file_data_buffer) # ... work ... source_image="path_to_document.pdf" with Image(filename=source_image, resolution=400) as img: for page in img.sequence: file_buffer = numpy.asarray(bytearray(page.make_blob("JPEG")), dtype=numpy.uint8) ocr_process(file_buffer) 

는 다른 라이브러리에서 해당 파이썬 "이미지"객체 (또는 밑줄 C 구조)를 가정하지 마십시오 서로 비교할 수 있습니다.

문자 인식 API를 모른 채 ...

  • 를 사용하여 임시 중간 파일을 나는 부분을지나 당신을 도울 수 있지만 다음 중 하나를 제안 할 수 있습니다. 문자 인식 API가 지원하는 경우

    with Image(filename=INPUT_PATH) as img: 
        # work 
        img.save(filename=OUTPUT_PATH) 
    # OCR work on OUTPUT_PATH 
    
  • 을 사용하여 파일 디스크립터를 (느린 I/O를하지만, 쉽게/디버깅을 개발/배울 수). (위와 동일)

    with open(INPUT_PATH, 'rb') as fd: 
        with Image(file=fd) as img: 
         # work 
         # OCR work ??? 
    
  • 얼룩을 사용하십시오. (I/O 빠르지 만 필요 많은 더 많은 메모리)

    buffer = None 
    with Image(filename=INPUT_PATH) as img: 
        # work 
        buffer = img.make_blob(FORMAT) 
    if buffer: 
        # OCR work ??? 
    

심지어 더 많은 업데이트

함께 모든 의견을 포장, 해결책은 ... 수 있습니다

from wand.image import Image 
from wand.api import library 
import ctypes 
import requests 

# Map C-API not provided by wand library. 
library.MagickAppendImages.argtypes = [ctypes.c_void_p, ctypes.c_int] 
library.MagickAppendImages.restype = ctypes.c_void_p 

with Image(filename='path_to_document.pdf', resolution=400) as image: 
    # ... Do pre-processing ... 
    # Reset the stack iterator. 
    library.MagickResetIterator(image.wand) 
    # Call C-API Append method. 
    resource_pointer = library.MagickAppendImages(image.wand, True) 
    # Convert to JPEG. 
    library.MagickSetImageFormat(resource_pointer, b'JPEG') 
    # Create size sentinel. 
    length = ctypes.c_size_t() 
    # Write image blob to memory. 
    image_data_pointer = library.MagickGetImagesBlob(resource_pointer, 
                ctypes.byref(length)) 
    # Ensure success 
    if image_data_pointer and length.value: 
     # Create buffer from memory address 
     payload = ctypes.string_at(image_data_pointer, length.value) 
     # Define local filename. 
     payload_filename = 'my_hires_image.jpg' 
     # Post payload as multipart encoded image file with filename. 
     requests.post(THE_URL, files={'file': (payload_filename, payload)}) 
+0

고마워, 내 자신의 이해를 위해서 : imageMagick 프로그램 자체가 C로 작성되었다고 가정합니다. Wand는 C API에 액세스하여 일부 기능은 아니지만 모든 기능을 제공합니다. – user61629

+0

수정하십시오. ImageMagick은 C로 작성되었으며'MagickWand '라 불리는 C-API 라이브러리와 함께 제공됩니다. 파이썬 패키지'wand'는'ctypes' 모듈을 통해'MagickWand'와 통합됩니다. – emcconville

+0

감사합니다. 작동하지 않습니다. 한가지 더 물어봐도 될까요? 위의 편집을 참조하십시오. – user61629

2

무엇과 같이 약 : 관련

with ok.resize(2000, 1000) 

:

ok = Image(filename=file_path, resolution=400) 
with ok.transform('2000x1000', '100%') as image: 
    image.compression_quality = 100 
    image.save() 

또는

+0

코드를 붙여 넣었지만 ok.transform ('2000x1000', '100 %')을 이미지로 사용했습니다. AttributeError : '__enter__' – user61629

+0

문제는 다음과 같은 이미지를 읽어야하는 것 같습니다. 이진 문자열. 편집을 참조하십시오. – user61629