我如何使用 wand-py 和 imagemagick 运行 这个命令

How can I run this command using wand-py and imagemagick

我正在尝试使用 wand-py 和 imagemagick 重新创建以下命令:

convert -density 500 hello_world.pdf -quality 100 -monochrome -enhance – morphology close diamond hello_world.jpg

您需要绑定来自 MagickCore 和 MagickWand 库的方法。请记住,不同系统的内核性能可能存在很大差异,因此如果您在处理大密度图像时遇到“操作已取消”消息,请不要感到惊讶。

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

"""
Kernel info methods on MagickCore library.
"""
libmagick.AcquireKernelInfo.argtypes = (ctypes.c_char_p,)
libmagick.AcquireKernelInfo.restype = ctypes.c_void_p
libmagick.DestroyKernelInfo.argtypes = (ctypes.c_void_p,)
libmagick.DestroyKernelInfo.restype = ctypes.c_void_p

"""
Morphology method on MagickWand library.
"""
library.MagickMorphologyImage.argtypes = (ctypes.c_void_p,  # wand
                                          ctypes.c_int,     # method
                                          ctypes.c_long,    # iterations
                                          ctypes.c_void_p)  # kernel
"""
Enhance method on MagickWand library.
"""
library.MagickEnhanceImage.argtypes = (ctypes.c_void_p,)    # wand

# convert -density 500 hello_world.pdf
with Image(filename='pdf-sample.pdf', resolution=500) as img:
    # -quality 100
    img.compression_quality = 100
    # -monochrome
    img.quantize(2,       # Target colors
                 'gray',  # Colorspace
                 1,       # Treedepth
                 False,   # No Dither
                 False)   # Quantization error
    # -enhance
    library.MagickEnhanceImage(img.wand)
    # -morphology close diamond
    p = ctypes.create_string_buffer(b'Diamond')
    kernel = libmagick.AcquireKernelInfo(p)
    CloseMorphology = 9  # See `morphology.h'
    library.MagickMorphologyImage(img.wand, CloseMorphology, 1, kernel)
    kernel = libmagick.DestroyKernelInfo(kernel) # Free memory
    # hello_world.jpg
    img.save(filename='hello_world.jpg')