Search code examples
imagematlabimage-processingmask

Apply a 2D map to a 3D array in MATLAB


I have a 3D array of arbitrary size m x n x d where d is the dimension, in this case, a time point. I have a 2D mask of size m x n that I want to apply to the 3D stack, and in each instance in which the mask has a value of 1, to set the value of the corresponding index in the stack to nan. The way I am doing this so far is:

imageStack((mask == 1)) = nan;

However, when displaying an image from one dimension of the stack, i.e. imagesc(imageStack(:,:,1) after the process, it is clear that the mask has been applied. However, higher dimensions do not have this mask applied - it seems that is has only applied it to the first dimension and not the full stack of images. Am I missing something in my impelementation of the mask?


Solution

  • First create a mask with NaNs, to make the job easier. Your mask may work but you haven't shared it.

    masknan=mask==1; masknan(masknan)=nan;
    

    Then, if you are in a 2016b or newer, you can use implicit expansion for the job.

    image=imageStack.*masknan; % it will automatically broadcast to the 3rd dimension
    

    Otherwise, use bsxfun

    image=bsxfun(@times,imageStack,masknan);