i want to remove black color from my image and make the background transparent so that i can paste it on another image... can anyone help?

22 views (last 30 days)
i want to remove black color from my image and make the background transparent so that i can paste it on another image... can anyone help?
  1 Comment
DGM
DGM on 2 Aug 2021
Edited: DGM on 2 Aug 2021
That depends. It depends on the image datatype and content, it depends on what exactly "black" means, and it depends what you mean by "make it transparent". To the latter point, compositing two images is a different goal than making an image with alpha content. It would help if you provide an example of your images and what exactly you're trying to do with them.

Sign in to comment.

Answers (1)

DGM
DGM on 2 Aug 2021
Edited: DGM on 2 Aug 2021
Let's start simple. Assume you have two single channel (I) images of the same class.
% generate test images for foreground and background
inpict = imread('cameraman.tif'); % raw single-channel source
FG = fliplr(imadjust(inpict,[0.05 1])); % make sure foreground extends to black
% make a checkerboard background
sout = size(inpict);
squaresize = [10 10];
xx = mod(0:(sout(2)-1),squaresize(2)*2)<squaresize(2);
yy = mod(0:(sout(1)-1),squaresize(1)*2)<squaresize(1);
BG = im2uint8(0.3 + bsxfun(@xor,xx,yy')*0.4);
% let's say 'black' means exactly zero
mask = FG>0; % logical mask
% you can combine images using logical indexing
outpict = BG;
outpict(mask) = FG(mask);
If 'black' means some range of colors, then the mask will have to accomodate that. If either image is a color image, then the compositing is a bit more complicated. If the mask is not necessarily logical, then the compositing approach would be again different.
Toward those ends, it's also possible to do simple operations by multiplication. This has the advantage of working with either logical or normalized numeric masks, and if you're running R2016b or later, the implicit array expansion will allow this to work on mixed I/RGB inputs.
% combine images using multiplicative blending (assuming uint8 data)
outpict = uint8(double(FG).*mask + double(BG).*(1-mask));
For example, this can combine a single channel FG with an RGB BG:
As with everything, you'll need to pay attention to the class of the different images and masks and take the necessary measures to make sure that they correspond.

Products

Community Treasure Hunt

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

Start Hunting!