【问题标题】:How to convert this command to a python code using Wand & ImageMagick如何使用 Wand & ImageMagick 将此命令转换为 python 代码
【发布时间】:2015-02-18 10:33:38
【问题描述】:

我想转换图像,以便使用 pyocr 和 tesseract 更好地阅读它。 我要转换为 python 的命令行是:

convert pic.png -background white -flatten -resize 300% pic_2.png

使用 python Wand 我设法调整了它的大小,但我不知道如何做扁平化和白色背景 我的尝试:

from wand.image import Image
with Image(filename='pic.png') as image:
    image.resize(270, 33)  #Can I use 300% directly ?
    image.save(filename='pic2.png')

请帮忙
编辑,这是要进行测试的图像:

【问题讨论】:

    标签: python imagemagick wand


    【解决方案1】:

    用于调整大小和背景。使用以下内容,并注意您需要自己计算 300%。

    from wand.image import Image
    from wand.color import Color
    
    with Image(filename="pic.png") as img:
      # -resize 300%
      scaler = 3
      img.resize(img.width * scaler, img.height * scaler)
      # -background white
      img.background_color = Color("white")
      img.save(filename="pic2.png")
    

    不幸的是, 方法 MagickMergeImageLayers 尚未实现。您应该提交增强请求with the development team

    更新 如果要移除透明度,只需禁用 Alpha 通道即可

    from wand.image import Image
    
    with Image(filename="pic.png") as img:
      # Remove alpha
      img.alpha_channel = False
      img.save(filename="pic2.png")
    

    另一种方式

    创建与第一个尺寸相同的新图像可能更容易,然后将源图像合成到新图像上。

    from wand.image import Image
    from wand.color import Color
    
    with Image(filename="pic.png") as img:
      with Image(width=img.width, height=img.height, background=Color("white")) as bg:
        bg.composite(img,0,0)
        # -resize 300%
        scaler = 3
        bg.resize(img.width * scaler, img.height * scaler)
        bg.save(filename="pic2.png")
    

    【讨论】:

    • 我已经添加了我正在处理的图像,您能否测试一下您的代码,看看如何在调整大小的同时使背景变白?
    • @Sekai 用两个选项更新了答案以使背景变白
    • 让我试试,我会回复你的
    猜你喜欢
    • 2023-03-25
    • 1970-01-01
    • 2015-04-25
    • 1970-01-01
    • 2021-12-02
    • 2019-08-27
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    相关资源
    最近更新 更多