0

I'm wondering how to convert this working command line sequence for ImageMagick into a Python script using the Wand library:

convert me.jpg -fill none -fuzz 1% -draw 'matte 0,0 floodfill' -flop  -draw 'matte 0,0 floodfill' -flop me.png

It basically allows me to subtract a known background image from my foreground image with some tolerance (i.e. fuzz). I want to fill in the resulting area with a flat color.

I want to do all this in memory and with my Python script to avoid recompressing my decoded RAW image data as a jpeg twice. Doing it via the command line forces the extra compression step, doing it in the script would just require one jpeg save.

Some help with this would be most appreciated.

Edit: Correction, was getting confused with something else I had tried. The above command does not subtract from a known image. This actually takes the top left pixel and flood fills from there with 1% fuzz. Obvious really when you can see there is only one input image. Still knowing how to convert the above into Python is still helpful.

robeastham
  • 41
  • 1
  • 4
  • Make a command string and then use ```import os``` and ```os.system(command_string)```. For example, ```command_string = "convert me.jpg -fill none -fuzz 1% -draw 'matte 0,0 floodfill' -flop -draw 'matte 0,0 floodfill' -flop me.png"```. There are probably better ways, but I find myself doing this a lot – dermen May 12 '16 at 17:03
  • Thanks @dermen, but I'm already using this and it means saving the file twice. I need to do all operation in memory to avoid recompression, especially as I may need to do more than just the command above. – robeastham May 15 '16 at 02:27

1 Answers1

1

You can try something like this.

from wand.color import Color
from wand.drawing import Drawing
from wand.image import Image

with Image(filename='me.jpg') as img:
    with Drawing() as ctx:
        # -fill none
        ctx.fill_color = Color('transparent')
        #  -draw 'matte 0,0 floodfill'
        ctx.matte(x=0, y=0, paint_method='floodfill')
        ctx(img)
        # -flop
        img.flop()
        ctx(img)
        img.flop()
    img.save(filename='me.png')

For -fuzz 1%, you'll need to do a little extra work to calculate the quantum value.

from wand.color import Color
from wand.drawing import Drawing
from wand.image import Image
import ctypes
library.MagickSetImageFuzz.argtypes = (ctypes.c_void_p,
                                       ctypes.c_double)
with Image(filename='me.jpg') as img:
    # -fuzz 1%
    library.MagickSetImageFuzz(img.wand, img.quantum_range * 0.1)
    with Drawing() as ctx:
        # -fill none
        ctx.fill_color = Color('transparent')
        #  -draw 'matte 0,0 floodfill'
        ctx.matte(x=0, y=0, paint_method='floodfill')
        # -flop -draw 'matte 0,0 floodfill' -flop
        ctx.matte(x=img.width - 1, y=0, paint_method='floodfill')
        ctx(img)
    img.save(filename='me.png')
emcconville
  • 23,800
  • 4
  • 50
  • 66