How to subtract Black and White image from RBG Original image.

2 views (last 30 days)
Hi, I have these two images and I want exactly white pixels from the BW image remain in original image like dog, flowers and grass under the dog should remain in original image as it is and rest of the original image becomes black. I have tried imsubtract(i,BW) but does not works. Thank you.

Accepted Answer

Shounak Shastri
Shounak Shastri on 28 Mar 2018
You cannot subtract the image because the two images are of different dimensions. You can check this in your workspace. Consider, M is the length and N is the breadth of the original image. Then, the BW image would be " M x N " and the original (color image) would be " M x N x 3 " where the three represents the three color components (red, blue and green).
Off the top of my head, you could run a for loop as shown below.
new_image = zeros(size(original_image)); %initialize a new image where you would store your results
for kk = 1:3
for ii = 1:M
for jj = 1:N
if BW (ii, jj) ~= 0
new_img (ii, jj, kk) = original_image (ii,jj,kk);
end
end
end
end
new_image = uint8(new_image); %the new image would be in double.
imshow(new_image);
I would like to add that this might not be the most efficient way to do it.
Best of Luck!
  1 Comment
DGM
DGM on 19 Jan 2023
% an image
inpict = imread('peppers.png');
% a single-channel logical mask
mask = imread('redpepmask.png')>128;
% generate the output image
outpict = inpict;
outpict(repmat(~mask,[1 1 size(inpict,3)])) = 0;
imshow(outpict)

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!