Compositing two images with python wand

Alberto A picture Alberto A · Feb 28, 2013 · Viewed 7k times · Source

I need to use python wand (image-magick bindings for python) to create a composite image, but I'm having some trouble figuring out how to do anything other than simply copy pasting the foreground image into the background image. What I want is, given I have two images like:

foreground

and

enter image description here

both jpegs, I want to remove the white background of the cat and then paste it on the room. Answers for other python image modules, like PIL, are also fine, I just need something to automatize the composition process. Thanks in advance.

Answer

minhee picture minhee · Mar 3, 2013

You can achieve this using Image.composite() method:

import urllib2

from wand.image import Image
from wand.display import display


fg_url = 'http://i.stack.imgur.com/Mz9y0.jpg'
bg_url = 'http://i.stack.imgur.com/TAcBA.jpg'

bg = urllib2.urlopen(bg_url)
with Image(file=bg) as bg_img:
    fg = urllib2.urlopen(fg_url)
    with Image(file=fg) as fg_img:
        bg_img.composite(fg_img, left=100, top=100)
    fg.close()
    display(bg_img)
bg.close()