Extract part of image using mask

14 vues (au cours des 30 derniers jours)
Miel Achten
Miel Achten le 14 Déc 2018
Commenté : Image Analyst le 15 Déc 2018
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

Réponses (1)

Image Analyst
Image Analyst le 14 Déc 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 commentaires
Miel Achten
Miel Achten le 15 Déc 2018
Thank you for the answer.
I ran the code for extracting the pixel values. But Matlab gives the following error:
Index in position 3 exceeds array bounds (must not exceed 1).
Error in test_mask_forum (line 9)
greenChannel = rgbImage(:, :, 2);
I also ran the second code, and that gives this error:
Error using bsxfun
Non-singleton dimensions of the two input arrays must match each other.
Error in test_mask_forum (line 4)
maskedRgbImage = bsxfun(@times, rgbImage, cast(mask, 'like', rgbImage)); % Blacken outside mask.
Image Analyst
Image Analyst le 15 Déc 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.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Image Processing Toolbox dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by