How can I make a specific color of an image transparent?

49 views (last 30 days)
I have a binary image which I am overlaying on top of another image. I would like the white portion of the binary image to be transparent so that only the black covers the background image. I have tried everything with alphadata and can only seem to change the transparency of the entire binary image rather than a single color. Are there are methods which will solve me problem? Any help would be much appreciated.
Thanks
  1 Comment
Walter Roberson
Walter Roberson on 11 Jan 2012
set the alphadata of the binary image to be 1 minus the binary image (presuming that 1 in the binary image is for white.)

Sign in to comment.

Answers (2)

David Young
David Young on 10 Jan 2012
There may be a way that allows you to overlay the images using graphics operations, but here's an alternative way that does it by making a new array, which you can then display.
First some data for illustration:
img = imread('saturn.png'); % an rgb image
bw = sum(img,3) > 400; % a binary image to overlay
Now the main operation. (If the main image is grayscale rather than rgb, you don't need the call to repmat.) The parts of the main "under" the ones remain unchanged, the parts "under" zeros get set to zero.
mask = cast(bw, class(img)); % ensure the types are compatible
img_masked = img .* repmat(mask, [1 1 3]); % apply the mask
Display the result:
imshow(img_masked);
  6 Comments
Walter Roberson
Walter Roberson on 7 May 2021
If this is for display purposes then draw a grey background first and then draw the foreground with AlphaData set to 0 for the places intended to be transparent.
joann ren
joann ren on 7 May 2021
Edited: Walter Roberson on 15 Dec 2023
@Walter RobersonYes, thank you so much for your tip! I also made it by reading the following. This is exactly the solution you provided! learned. Thank you so much!! https://www.mathworks.com/company/newsletters/articles/image-overlay-using-transparency.html

Sign in to comment.


DGM
DGM on 15 Dec 2023
Edited: DGM on 15 Dec 2023
You already have a mask, so I'm not concerned with how to create a mask.
As usual, the MIMT way is the easy and universal way.
% an image and an antialiased mask
inpict = imread('peppers.png'); % RGB, uint8
mask = imread('sources/standardmods/pep/redpepmask.png'); % I, uint8
% compose the output
% replacepixels(FG,BG,mask)
outpict = replacepixels(inpict,0,mask); % one line
% show it
imshow(outpict)
The image can be gray or RGB. The mask can be logical, binarized numeric, or graduated/antialiased numeric. The classes don't need to match, so long as everything is properly scaled for its class. It all works just the same. The output is a clean raster image instead of a stack of graphics objects destined to become a screenshot.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!