Apply transparent background to a figure
13 views (last 30 days)
Show older comments
I want to apply only to the background (white) of the figure "background.png" a certain level of transparency (thus keeping the pixels black).
This figure then needs to overlap with the "background_pink.png" figure.
I am using the following code:
figure();
folder_immagine_png = 'C:\...';
filename_png = 'background_pink.png';
ful_file_png = fullfile(folder_immagine_png,filename_png);
imshow(ful_file_png)
hold on
figure();
folder_immagine = 'C:\....';
filename = 'background.png';
ful_file = fullfile(folder_immagine,filename);
imshow(ful_file)
hold off
I have tried using the AlphaData command but to no avail.
4 Comments
Accepted Answer
Voss
on 2 Nov 2022
im_bw = imread('background.png');
im_pink = imread('background_pink.png');
% make an image of the pink background as-is:
image(im_pink)
hold on
% varying (in this case, random) opacity values:
alpha = rand(size(im_bw));
% set alpha to 1 (fully opaque) where im_bw is 0 (black):
alpha(im_bw == 0) = 1;
% add the new black-and-white image with opacity:
image(repmat(255*im_bw,[1 1 3]),'AlphaData',alpha)
5 Comments
DGM
on 3 Nov 2022
Again, you compose images by working on the data itself, not trying to capture a figure.
im_bw = imread('background.png');
im_pink = imread('background_pink.png');
% varying (in this case, random) opacity values:
alpha = rand(size(im_bw));
% set alpha to 1 (fully opaque) where im_bw is 0 (black):
alpha(im_bw == 0) = 1;
% compose the image directly
outpict = alpha.*im2double(im_bw) + (1-alpha).*im2double(im_pink);
imwrite(outpict,'op1.png')

The above example assumes that the alpha array is of floating-point class.
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
