Robert Bean
Robert Bean

Reputation: 859

Image Cropping with a Matrix Filter

After some processing, I got a black&white mask of a BMP image.

Now, I want to show only the part of the BMP image where it is white in the mask.

I'm a newb with matlab(but I love it), and I've tried a lot of matrix tricks learned from google, well, none works(or I'm not doing them right ..)

Please provide me with some tips.

Thanks for your time in advance.

Upvotes: 0

Views: 505

Answers (2)

Bjoern H
Bjoern H

Reputation: 600

Using one of the two matlab functions repmat or bsxfun the masking operation can be performed in a single line of code for a source image with any number of channels.

Assuming that your image I is of size M-by-N-by-C and the mask is of size M-by-N, then we can obtain the masked image using either repmat

I2 = I .* repmat(mask, [1, 1, 3]);

or using bsxfun

I2 = bsxfun(@times, I, mask);

These are both very handy functions to know about and can be very useful when it comes to vectorizing your code in general. I would also recommend that you look through the answer to this question: In Matlab, when is it optimal to use bsxfun?

Upvotes: 1

Autonomous
Autonomous

Reputation: 9075

Assuming the mask is of the same size as image, then you can just do (for grayscale images):

maskedImage=yourImage.*mask %.* means pointwise multiplication. 

For color images, do the same operations on the three channels:

maskedImage(:,:,1)=yourImage(:,:,1).*mask 
maskedImage(:,:,2)=yourImage(:,:,2).*mask 
maskedImage(:,:,3)=yourImage(:,:,3).*mask 

Then to visualize the image, do:

imshow(maskedImage,[]);

Upvotes: 1

Related Questions