python - 如何使用 wand-py 和 imagemagick 运行此命令

标签 python imagemagick-convert wand

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

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

最佳答案

您需要绑定(bind) 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')

关于python - 如何使用 wand-py 和 imagemagick 运行此命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42772714/

相关文章:

Python/Pandas - DataFrame 索引 - 向前移动一个月

python - 对数据框列中的值进行自定义过滤器 (Python)

python - 我可以使用复合主键代替 ID 主键吗?

python-3.x - 如何使用魔杖扭曲图像

imagemagick - 使用 imagemagick 转换为 pdf 时如何管理图像位置?

python - 如何将 numpy 数组转换为 wand.image.Image 对象?

python - 将包含多个值的字符串拆分为多个字符串,每个字符串一个值

c++ - 将 hus 和 pes 文件转换为任何类型的图像

python - 如何将convert命令更改为python代码

相当于 ImageMagick "convert -append"的魔杖