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 di
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.
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
.