Extract part of image using mask
11 views (last 30 days)
Show older comments
Hello,
For a project I need to extract only a part of my image. I already have a mask of that image (same size) and would like to extract the part of the image that is coloured white in the mask. See images in attachment.
Thank you in advance
Miel Achten
0 Comments
Answers (1)
Image Analyst
on 14 Dec 2018
To extract only the pixels of the image insde the mask, try this:
% Extract the individual red, green, and blue color channels.
redChannel = rgbImage(:, :, 1);
greenChannel = rgbImage(:, :, 2);
blueChannel = rgbImage(:, :, 3);
% Get a list of pixel values inside the mask only.
extractedRedPixels = redChannel(mask);
extractedGreenPixels = greenChannel(mask);
extractedBluePixels = blueChannel(mask);
If you just want to mask the RGB image instead of extracting the values, do this:
% Mask the image using bsxfun() function to multiply the mask by each channel individually.
maskedRgbImage = bsxfun(@times, rgbImage, cast(mask, 'like', rgbImage)); % Blacken outside mask.
maskedRgbImage will be black outside the mask region and the original image inside the mask region.
2 Comments
Image Analyst
on 15 Dec 2018
Then your image is not the color image that was posted. You are trying to get the green channel of a gray scale image, which doesn't have one. If you want to mask a gray scale image, skip the color channel extraction code and just go right to this:
% Mask the image using bsxfun() function to multiply the mask by each channel individually.
maskedGrayImage = bsxfun(@times, grayImage, cast(mask, 'like', grayImage)); % Blacken outside mask.
See Also
Categories
Find more on Image Processing Toolbox in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!