9

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.

minhee
  • 5,129
  • 5
  • 38
  • 77
Alberto A
  • 1,144
  • 3
  • 13
  • 32
  • A quick google search for `python composite image` yields many results (e.g. some [PIL functions](http://www.pythonware.com/library/pil/handbook/image.htm)). As your question currently stands, I don't know how you want us to help. You might consider asking a more specific question after you have tried something. – Wesley Baugh Feb 28 '13 at 21:12
  • Oh, yes, I should add that I've already tried 'composite' (and PIL's method 'paste') but in both cases, I couldn't find a way to automatize the process of eliminating the white background of the first image before pasting it into the second image. that is my main problem! – Alberto A Feb 28 '13 at 22:19

2 Answers2

13

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()
minhee
  • 5,129
  • 5
  • 38
  • 77
  • That's what I've been doing until now. But it doesn't solve my problem of automatically eliminating the cat image white background. Thanks for the answer anyway – Alberto A Mar 03 '13 at 15:30
2

For those that stumble across this in the future, what you probably want to do is change the 'white' color in the cat image to transparent before doing the composition. This should be achievable using the 'transparent_color()' method of the Image. Something like 'fg_img.transparent_color(wand.color.Color('#FFF')), probably also with a fuzz parameter.

See: http://www.imagemagick.org/Usage/compose/ http://docs.wand-py.org/en/latest/wand/image.html

clemej
  • 2,393
  • 2
  • 17
  • 27