MATLAB: Creating a “mask” over an image

image processingimaging

I am given a project using matlab. With an image I am supposed to separate the RGB of the image into 3 2 dimensional matrices. This is the current code that I have used
r = f1(:,:,1); %assigns first color layer to variable r
g = f1(:,:,2); %assigns second color layer to variable g
b = f1(:,:,3); %assigns third color layer to variable b
The next step of the project is to use the matrix set for green values and by using only implicit commands create a new matrix that contains indices for green that are larger than the intensity threshold that is assigned by the user when asked. The matrix should be "number of pixels" x "number of pixels". How would you do this? This is the current method I am using, is it correct?
m1 = g>=n;
figure(3)
image(m1)
Furthermore, I am suppose to create a new matrix with "number of pixels" x "number of pixels" x 3 where the matrix created with the intensity threshold is duplicated along the 3 dimensions and generates a "mask" that tells whether or not the RGB content at any pixel met the given value. How would you do this? I have no code thus far for it.

Best Answer

See these snippets:
% Extract the individual red, green, and blue color channels.
redChannel = rgbImage(:, :, 1);
greenChannel = rgbImage(:, :, 2);
blueChannel = rgbImage(:, :, 3);
% Create the mask
mask = greenChannel > n;
% Mask image must be converted to the same integer type
% as the integer image we want to mask.
mask = cast(binaryImage, class(rgbImage));
% Masking method #1:
% Multiply the mask by each color channel individually.
maskedRed = redChannel .* mask;
maskedGreen = greenChannel .* mask;
maskedBlue = blueChannel .* mask;
% Recombine separate masked color channels into a single, true color RGB image.
maskedRgbImage = cat(3, maskedRed, maskedGreen, maskedBlue);
% Masking method #2:
% An alternate method to multiplication channel by channel.
% Mask the image using bsxfun() function
maskedRgbImage = bsxfun(@times, rgbImage, cast(mask, class(rgbImage)));