5

我想转换图像,以便我可以使用 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')

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

4

1 回答 1

11

用于调整大小和背景。使用以下内容,并注意您需要自己计算 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尚未实现。您应该向开发团队提交增强请求。

更新 如果要删除透明度,只需禁用 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")
于 2014-12-19T14:28:01.390 回答