0

Say that we have an image which pixels were labeled 1 and 2. How can we do the following in MATLAB?

  • Convert the locations of 1s and 2s into binary masks
  • Filter the image with those masks

Thanks.

Amro
  • 123,847
  • 25
  • 243
  • 454
Simplicity
  • 47,404
  • 98
  • 256
  • 385

1 Answers1

1

Example:

% some RGB image
img = im2double(imread('peppers.png'));
[h,w,~] = size(img);

% lets create some random labels. I'm simply dividing into two halves,
% where upper half is labeled 1, and lower half labeled 2
labels = [ones(h/2,w)*1; ones(h/2,w)*2];

% compute masks and filter image using each
img1 = bsxfun(@times, img, labels==1);
img2 = bsxfun(@times, img, labels==2);

% show result
subplot(121), imshow(img1)
subplot(122), imshow(img2)

images

Amro
  • 123,847
  • 25
  • 243
  • 454
  • Thanks for your reply. Regarding `img1 = bsxfun(@times, img, labels==1);`, do you mean here multiplying `img` with the pixels having value `1`? How is it a binary mask here? – Simplicity Aug 31 '13 at 22:13
  • 1
    @Simplicity: `labels==k` will create a logical matrix with `true` for locations where the label is `k`, and `false` otherwise. I then multiply this mask by the pixels of the image (element-wise). Multiplying by one keeps the original value, multiplying by zero will zero out the pixels. `bsxfun` was used to broadcast the mask across the third dimension for R,G,B image channels. – Amro Aug 31 '13 at 22:53
  • Sorry, regarding `subplot`, I returned to the documentation, but didn't understand what the values `121` and `122` represent? – Simplicity Sep 01 '13 at 00:07
  • 1
    @Simplicity: its a shorthand form of `subplot(1,2,1)` meaning: 1 row, 2 columns, and use the 1st tile as current axis (specified as a linear index). This is explained at the bottom of the page in the "Tips" section: http://www.mathworks.com/help/matlab/ref/subplot.html#f33-521269 – Amro Sep 01 '13 at 00:12
  • I should draw your attention to the fact that I used "double" images, rather than keep it in `uint8` data type. This is because MATLAB will annoyingly complain if you multiply integers with mixed types – Amro Sep 01 '13 at 00:25