MATLAB Answers

0

How to apply same 2D logical mask to each 3D layer effctively?

Asked by JAI PRAKASH on 13 Jul 2018 at 8:02
Latest activity Commented on by Walter Roberson
on 14 Jul 2018 at 3:02
RGB = imread('onion.png');
mask = RGB(:,:,1)>100;
%% How can I do something like below
RGB(mask,1:3) = 0;       % I want to apply same 2D 'mask' for all the 3 layers

I got this intuition from this post "logical operation on a column within a matrix" .

  0 Comments

Sign in to comment.

Tags

Products


Release

R2018a

1 Answer

Answer by Image Analyst
on 13 Jul 2018 at 11:14

Try this:

% Mask the image using bsxfun() function to multiply the mask by each channel individually.
maskedRgbImage = bsxfun(@times, rgbImage, cast(mask, 'like', rgbImage));

  7 Comments

ya, above code is straight forward and fast.

But the below code I find 10% more faster

[m, n, p] = size(Im1);
maskIdx = find(Im2(:,:,1) > 0);
maskIdx = [maskIdx; m*n+maskIdx; 2*m*n+maskIdx];
Im1(maskIdx) = Im2(maskIdx);  % Im1 will become the OverlappedIm

frankly say, I still hope for further efficiency..

It might be slightly faster but it's not general. It's depending on there being at least some red in every pixel of Im2 that you want to use as a mask. So it won't work for a general color where the shape in Im2 could be anything but would work in your specific computer graphics case.

Using the multiply version can be faster sometimes because the multiply version on sufficiently large matrices can be sent to LAPACK for multithreaded execution.

Sign in to comment.