I have an image with a transparent background, but when I open it in MATLAB, I get a black background. I'm overlaying it on top of a background image. How can I get this to display? I've tried using the alpha function alpha(image,0)
but it sets my entire image to 0. Is it possible for me to set the alpha of individual pixels to be equal to 0? That way I can run each pixel through a loop.
I'm not sure if this helps, but when I run a imfinfo('ryu1.png')
, I get :
...
Transparency = 'alpha'
SimpleTransparencyData = []
...
You can read in your image using imread
. However, you need to specify additional output parameters if you want to grab the alpha channel. You need to call it like this:
[im, map, alpha] = imread('ryu1.png');
im
is your image read in, map
is the colour map which we will ignore, but alpha
contains the transparency information that you want. First call imshow
and record the handle to the image, then set your transparency with the alpha
channel using the set
command. In other words:
[im, map, alpha] = imread('ryu1.png');
f = imshow(im);
set(f, 'AlphaData', alpha);
This should make the figure with the transparency intact.
Addition (Thanks to Yvon)
Supposing you already have a background image loaded into MATLAB. If you want to blend these two together, you need to do some alpha matting. You use the alpha channel and mix the two together. In other words, supposing your background image is stored in img_background
and img_overlay
is the image you want to go on top of the background, do this:
alphaMask = im2double(alpha); %// To make between 0 and 1
img_composite = im2uint8(double(img_background).*(1-alphaMask) + double(img_overlay).*alphaMask);
The first step is necessary as the alpha map that is loaded in will be the same type as the input image, which is usually uint8
. We need to convert this to a double
image such that it goes in between 0
and 1
, and im2double
is perfect to do this. The second line converts each of the images to double precision so that we can compute this sum and in order to make the data types between the alpha mask and both images are compatible. We then convert back to uint8
. You can then show this final image using imshow
.