How to convert this command to a python code using Wand & ImageMagick
Asked Answered
C

1

5

I want to convert an image so I can read it better using pyocr & tesseract. The Command line I want to convert to python is :

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

Using python Wand I managed to resize it but I don't know how to do the flattend and the white background My try :

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')

Please help
Edit, Here is the image to make tests on : enter image description here

Conviction answered 19/12, 2014 at 13:13 Comment(0)
O
11

For resize & background. Use the following, and note that you'll need to calculate the 300% yourself.

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")

Unfortunately the method MagickMergeImageLayers has yet to be implemented. You should author an enhancement request with the development team.

Update If you want to remove the transparency, just disable the alpha channel

from wand.image import Image

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

Another way

It might just be easier to create a new image with the same dimensions as the first, and just composite the source image over the new one.

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")
Orientalism answered 19/12, 2014 at 14:28 Comment(3)
I have added the image I'm working on, can you please test your code and see how I can make the background white whith the resize ?Conviction
@Sekai Updated answer with two options to make the background whiteOrientalism
Let me try, and I'll be back to youConviction

© 2022 - 2024 — McMap. All rights reserved.