# Extract pixel values inside a Binary Mask

조회 수: 37 (최근 30일)
ali eskandari 2021년 6월 11일
답변: Joseph Cheng 2021년 6월 11일
I have an image and the ROI points. I did the following to extract the ROI by creating a binary mask with poly2mask. now I want to extact the values of masked image.
My problem is that I cannot retain zeros inside the masked image using the code below. Could you please help me?
S = size(img); % Size of the binary masked
bw = poly2mask(x,y,S(1),S(2)); % Create a binary mask
ROI = img;
ROI(bw == 0) = 0;
ROI = ROI(ROI>0); % Just keep the non-zero values

댓글을 달려면 로그인하십시오.

### 답변 (1개)

Joseph Cheng 2021년 6월 11일
since you already created a binary mask you can just index multiply " .* " the mask with the original image as outside is 0 and inside the mask is 1.
%dummy image for example
img = imread('pears.png');
bwimg = single(rgb2gray(img));
[r c]=size(bwimg);
figure(1),subplot(131),imagesc(bwimg); colormap gray
title('original image')
%dummy mask gen for example
x = c*rand(1,4);
y = r*rand(1,4);
x(end+1) = x(1);
y(end+1) = y(1);
%create mask
bw = poly2mask(x,y,r,c);
subplot(132),imagesc(bw);colormap gray
title('mask')
%extractROI
%index multiply image with mask as outside is 0 and inside is 1
ROI=bwimg.*bw;
subplot(133),imagesc(ROI);colormap gray;title('Mask applied')

댓글을 달려면 로그인하십시오.

### 카테고리

Help CenterFile Exchange에서 Region and Image Properties에 대해 자세히 알아보기

### Community Treasure Hunt

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

Start Hunting!

Translated by