Extract part of image using mask

조회 수: 10 (최근 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 CenterFile Exchange에서 Image Processing Toolbox에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by