如何使用Wand和ImageMagick将此命令转换为python代码

Sek*_*kai 3 python imagemagick wand

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

convert pic.png -background white -flatten -resize 300% pic_2.png
Run Code Online (Sandbox Code Playgroud)

使用python Wand我设法调整它,但我不知道如何做flattend和白色背景我尝试:

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')
Run Code Online (Sandbox Code Playgroud)

请帮助
编辑,这是要进行测试的图像: 在此输入图像描述

emc*_*lle 9

用于调整大小和背景.使用以下内容,请注意您需要自己计算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")
Run Code Online (Sandbox Code Playgroud)

不幸的是,方法MagickMergeImageLayers还没有实现.您应该与开发团队一起创建增强请求.

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

from wand.image import Image

with Image(filename="pic.png") as img:
  # Remove alpha
  img.alpha_channel = False
  img.save(filename="pic2.png")
Run Code Online (Sandbox Code Playgroud)

其他方式

创建一个与第一个图像尺寸相同的新图像可能更容易,只需将源图像合成到新图像上即可.

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")
Run Code Online (Sandbox Code Playgroud)