I'm using Emgu.CV to perform some basic image manipulation and composition. My images are loaded as Image<Bgra,Byte>
.
Question #1: When I use the Image<,>.Add()
method, the images are always blended together, regardless of the alpha value. Instead I'd like them to be composited one atop the other, and use the included alpha channel to determine how the images should be blended. So if I call image1.Add(image2)
any fully opaque pixels in image2 would completely cover the pixels from image1, while semi-transparent pixels would be blended based on the alpha value.
Here's what I'm trying to do in visual form. There's a city image with some "transparent holes" cut out, and a frog behind. This is what it should look like:
And this is what openCV produces.
How can I get this effect with OpenCV? And will it be as fast as calling Add()
?
Question #2: is there a way to perform this composition in-place instead of creating a new image with each call to Add()
? (e.g. image1.AddImageInPlace(image2)
modifies the bytes of image1
?)
NOTE: Looking for answers within Emgu.CV, which I'm using because of how well it handles perspective warping.
You'll have to iterate through each pixel. I'm assuming image 1 is the frog image, and image 2 is the city image, with image1 always being bigger than image2.
Using Osiris's suggestion as a starting point, and having checked out alpha compositing on Wikipedia, i ended up with the following which worked really nicely for my purposes.
This was used this with Emgucv. I was hoping that the opencv gpu::AlphaComposite methods were available in Emgucv which I believe would have done the following for me, but alas the version I am using didn't appear to have them implemented.
A newer version, using emgucv methods. rather than a loop. Not sure it improves on performance. double unit = 1.0 / 255.0; Image[] dstS = dst.Split(); Image[] srcS = src.Split(); Image[] rs = result.Split();
I found an interesting blog post on internet, which I think is related to what you are trying to do.
Please have a look at the Creating Overlays Method (archive.org link). You can use this idea to implement your own function to add two images in the way you mentioned above, making some particular areas in the image transparent while leaving the rest as it is.
Before OpenCV 2.4 there was no support of PNGs with alpha channel.
To verify if your current version supports it, print the number of channels after loading an image that you are certain to be RGBA. If it supports, the application will output the number 4, else it will output number 3 (RGB). Using the C API you would do:
If you can't update OpenCV:
If your version already supports PNGs with RGBA:
EDIT:
I had to deal with this problem recently and I've demonstrated how to deal with it on this answer.