Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a color completely transparent in OpenCV

I have a basic png file with two colors in it, green and magenta. What I'm looking to do is to take all the magenta pixels and make them transparent so that I can merge the image into another image.

An example would be if I have an image file of a 2D character on a magenta background. I would remove all the magenta in the background so that it's transparent. From there I would just take the image of the character and add it as a layer in another image so it looks like the character has been placed in an environment.

Thanks in advance.

like image 640
Seb Avatar asked Jul 13 '11 15:07

Seb


1 Answers

That's the code i would use,

First, load your image :

IplImage *myImage;
myImage = cvLoadImage("/path/of/your/image.jpg");

Then use a mask like this to select the color, you should refer to the documentation. In the following, I want to select a blue (don't forget that in OpenCV images are in BGR format, therefore 125,0,0 is a blue (it corresponds to the lower bound) and 255,127,127 is blue with a certain tolerance and is the upper bound. I chose lower and upper bound with a tolerance to take all the blue of your image, but you can select whatever you want...

cvInRangeS(image, 
           cvScalar(125.0, 0.0, 0.0), 
           cvScalar(255.0, 127.0, 127.0), 
           mask
           );

Now we have selected the mask, let's inverse it (as we don't want to keep the mask, but to remove it)

cvNot(mask, mask);

And then copy your image with the mask,

IplImage *myImageWithTransparency; //You may need to initialize it before
cvCopy(myImage,myImageWithTransparency,mask);

Hope it could help,

Please refer to the OpenCVDocumentation for further information

Here it is

Julien,

like image 163
jmartel Avatar answered Oct 13 '22 01:10

jmartel