Extract part of image using mask

11 ビュー (過去 30 日間)
Miel Achten
Miel Achten 2018 年 12 月 14 日
コメント済み: Image Analyst 2018 年 12 月 15 日
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

回答 (1 件)

Image Analyst
Image Analyst 2018 年 12 月 14 日
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 件のコメント
Miel Achten
Miel Achten 2018 年 12 月 15 日
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 2018 年 12 月 15 日
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.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeImage Processing Toolbox についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by