Question

I have a problem I don't know how to resolve in Matlab. Basically. I have an image array hw x 3 and a seperate binary array that defines the background foreground. What I want to do, is split the image into two parts - corresponding to the mask.

Thanks in advance for the help!

Was it helpful?

Solution

The mask is the same for all thre channels, thus simply copy it.

I=... %image
M=... %mask
M3=cat(3,M,M,M);
F=zeros(size(I));
B=zeros(size(I));
F(M3)=I(M3);
B(~M3)=I(~M3);

Maybe foreground and background is switch, but I think you will get it.

A bit shorter, using multiplication instead of logical indexing:

I=... %image
M=... %mask
M3=cat(3,M,M,M);
F=M3.*I;
F=~M3.*I;

OTHER TIPS

It's a bit unclear what you mean by "split".
If you mean you want an image with only the foreground - and the background blacked out (set to [0 0 0] then

fg = bsxfun(@times, img, msk ); % where msk = 1 for FG
bg = bsxfun(@times, img, ~msk );
figure;
subplot(121);imshow( fg ); title('Foreground');
subplot(122);imshow( bg ); title('Background');

However, if by "split" you mean you want two arrays of colors |FG|x3 and |BG|x3 for foreground and background colors respectively then

fg = reshape(img,[],3); % all pixels stacked
bg = fg( ~msk, : ); % take the background 30vectors
fg = fg( msk, : ); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top