How to multiply a matrix by a boolean mask

9 次查看(过去 30 天)
Hello. I'm trying to multiply an image matrix by a roipoly boolean mask.
It's throwing a 'Matrix dimensions must agree' error in the BlendImages function as shown below. I understand that the mask is a boolean and therefore does not have the same dimensions as the matrix I'm trying to multiply it with.
The image dimensions: 480x640x3 double
Boolean mask dimensions: 480x640 double
How do I convert the boolean mask so that I can multiply the image with it? Any help would be much appreciated.
im1 = double(imread('image1.jpg'))/255;
im2 = double(imread('image2.jpg'))/255;
level = 4;
...
figure; imshow(im1);
mask = roipoly;
close;
% image1_laplacian and image2_laplacian are both cell arrays of images
blended = BlendImages(image1_laplacian, image2_laplacian, mask, level);
BlendImages function:
function blendedImage = BlendImages(pyr1, pyr2, mask, level)
maskImage = double(mask)/255;
pyr1_mask = GaussianPyramid(maskImage, level);
pyr2_mask = GaussianPyramid(1 - mask, level);
pyr_combined = cell(level, 1);
for i=1:level
% * ERROR ON NEXT LINE *
pyr_combined{i} = (pyr1{i} .* pyr1_mask{i}) + (pyr2{i} .* pyr2_mask{i});
figure; imshow(pyr_combined);
end

回答(1 个)

Image Analyst
Image Analyst 2014-3-11
Try it Sean's way:
% An alternate method to multiplication channel by channel.
% Mask the image using bsxfun() function
maskedRgbImage = bsxfun(@times, rgbImage, cast(mask, class(rgbImage)));
  4 个评论
t
t 2014-3-11
Not crop exactly. I apply gaussian blur to the mask. What I want to know how to do is then multiply this blurred mask by the image. Is there a way of doing this? Many thanks.
Image Analyst
Image Analyst 2014-3-11
Use fspecial to create the Gaussian window. Then create your mask. Cast it to double and use conv2() or imfilter() to blur the mask by the Gaussian. Then cast your grayscale image to double and do a dot-multiply to multiply it
g = fspecial(.............. whatever.......);
blurredMask = conv2(mask, g, 'same');
m = (double)grayImage .* blurredMask;

请先登录,再进行评论。

产品

Community Treasure Hunt

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

Start Hunting!

Translated by