openCV: adding transparency to IplImage
Asked Answered
A

2

3

I have a 3-channel IplImage. I would like to create a 4-channel image and set the alpha channel for it to a value less than 1.0 to make it semi-transparent.

First I set the alpha channel (the 4-th channel) to 0.5:

cvSet(Image_c4, cvScalar(0,0,0,0.5);

Here is the command that I used to copy the 3-channel image into a 4-channel image.

cvCvtColor(Image_c3, Image_c4, CV_RGB2RGBA);

The problem: Image_c3 is in color. Image_c4 becomes a gray scale copy of Image_c3 (and with no transparency).

Update: It turned out that the code above is actually correct and works and is actually more concise than the suggested solutions in the answers below. I had an unrelated bug somewhere else.

Ashworth answered 11/10, 2011 at 6:44 Comment(0)
C
5

Maybe there is another way but I add transparency like this:

// BGR split
cvSplit(im1_bgr, im1_b, im1_g, im1_r, NULL);

// Alpha channel creation (transparency)
IplImage *im1_a = cvCreateImage(cvGetSize(im1_bgr), 8, 1);
// Set the alpha value
cvSet(im1_a, cvScalar(128), NULL);

// Merge the 4 channel to an BGRA image
IplImage *im1_bgra = cvCreateImage(cvGetSize(im1_bgr), 8, 4);
cvMerge(im1_b, im1_g, im1_r, im1_a, im1_bgra);
Carboniferous answered 11/10, 2011 at 10:56 Comment(1)
Thanks for taking the time to respond. It turned out that the code in my question was actually correct and I had another unrelated bug. Your code is also correct, but the cvCvtColor does the same thing, but it's much simpler.Ashworth
G
0
//This code help to make a transparency image But it take src image as one //single color background see![Removing background and added black background color  ][1]
Mat dst;//(src.rows,src.cols,CV_8UC4);
Mat tmp,alpha;

cvtColor(src,tmp,CV_BGR2GRAY);
threshold(tmp,alpha,0,255,THRESH_BINARY);

Mat rgb[3];
split(src,rgb);

Mat rgba[4]={rgb[0],rgb[1],rgb[2],alpha};
merge(rgba,4,dst);
imwrite("dst.png",dst);
//dst is transparency image see here![output image as transparency image][2]


  [1]: https://i.sstatic.net/9THqs.png
  [2]: https://i.sstatic.net/mpmgy.png
Grassland answered 31/3, 2015 at 7:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.